1 // Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // NETGENPlugin : C++ implementation
24 // File : NETGENPlugin_Mesher.cxx
25 // Author : Michael Sazonov (OCN)
28 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SALOMEDS_Tool.hxx>
53 #include <utilities.h>
55 #include <BRepAdaptor_Surface.hxx>
56 #include <BRepBuilderAPI_Copy.hxx>
57 #include <BRepLProp_SLProps.hxx>
58 #include <BRepMesh_IncrementalMesh.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <GeomLib_IsPlanarSurface.hxx>
63 #include <NCollection_Map.hxx>
64 #include <Poly_Triangulation.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TColStd_MapOfInteger.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopLoc_Location.hxx>
71 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
72 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
73 #include <TopTools_DataMapOfShapeInteger.hxx>
74 #include <TopTools_DataMapOfShapeShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS_Compound.hxx>
79 // Netgen include files
83 #include <occgeom.hpp>
84 #include <meshing.hpp>
85 //#include <ngexception.hpp>
88 NETGENPLUGIN_DLL_HEADER
89 extern MeshingParameters mparam;
91 NETGENPLUGIN_DLL_HEADER
92 extern volatile multithreadt multithread;
94 NETGENPLUGIN_DLL_HEADER
95 extern bool merge_solids;
97 // values used for occgeo.facemeshstatus
98 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
110 using namespace nglib;
114 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
116 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
119 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
122 // dump elements added to ng mesh
123 //#define DUMP_SEGMENTS
124 //#define DUMP_TRIANGLES
125 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
128 TopTools_IndexedMapOfShape ShapesWithLocalSize;
129 std::map<int,double> VertexId2LocalSize;
130 std::map<int,double> EdgeId2LocalSize;
131 std::map<int,double> FaceId2LocalSize;
132 std::map<int,double> SolidId2LocalSize;
134 std::vector<SMESHUtils::ControlPnt> ControlPoints;
135 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
139 inline void NOOP_Deleter(void *) { ; }
141 //=============================================================================
143 * Link - a pair of integer numbers
145 //=============================================================================
149 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
150 Link() : n1(0), n2(0) {}
151 bool Contains( int n ) const { return n == n1 || n == n2; }
152 bool IsConnected( const Link& other ) const
154 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
156 static int HashCode(const Link& aLink, int aLimit)
158 return ::HashCode(aLink.n1 + aLink.n2, aLimit);
161 static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
163 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
164 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
168 typedef NCollection_Map<Link,Link> TLinkMap;
170 //================================================================================
172 * \brief return id of netgen point corresponding to SMDS node
174 //================================================================================
175 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
177 int ngNodeId( const SMDS_MeshNode* node,
178 netgen::Mesh& ngMesh,
179 TNode2IdMap& nodeNgIdMap)
181 int newNgId = ngMesh.GetNP() + 1;
183 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
185 if ( node_id->second == newNgId)
187 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
188 cout << "Ng " << newNgId << " - " << node;
190 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
191 ngMesh.AddPoint( p );
193 return node_id->second;
196 //================================================================================
198 * \brief Return computed EDGEs connected to the given one
200 //================================================================================
202 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
203 const TopoDS_Face& face,
204 const set< SMESH_subMesh* > & /*computedSM*/,
205 const SMESH_MesherHelper& helper,
206 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
209 list< TopoDS_Edge > edges;
210 list< int > nbEdgesInWire;
211 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
213 // find <edge> within <edges>
214 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
215 for ( ; eItFwd != edges.end(); ++eItFwd )
216 if ( edge.IsSame( *eItFwd ))
218 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
220 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
222 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
223 // so treat each INTERNAL edge separately
224 TopoDS_Edge e = *eItFwd;
226 edges.push_back( e );
230 // get all computed EDGEs connected to <edge>
232 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
233 TopoDS_Vertex vCommon;
234 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
237 // put edges before <edge> to <edges> back
238 while ( edges.begin() != eItFwd )
239 edges.splice( edges.end(), edges, edges.begin() );
243 while ( ++eItFwd != edges.end() )
245 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
247 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
248 bool computed = !sm->IsEmpty();
249 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
250 bool doubled = !eAdded.Add( *eItFwd );
251 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
252 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
253 if ( !connected || !computed || !orientOK || added || doubled )
255 // stop advancement; move edges from tail to head
256 while ( edges.back() != *ePrev )
257 edges.splice( edges.begin(), edges, --edges.end() );
263 while ( eItBack != edges.begin() )
267 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
269 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
270 bool computed = !sm->IsEmpty();
271 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
272 bool doubled = !eAdded.Add( *eItBack );
273 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
274 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
275 if ( !connected || !computed || !orientOK || added || doubled)
278 edges.erase( edges.begin(), ePrev );
282 if ( edges.front() != edges.back() )
284 // assure that the 1st vertex is meshed
285 TopoDS_Edge eLast = edges.back();
286 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
288 edges.front() != eLast )
289 edges.splice( edges.end(), edges, edges.begin() );
294 //================================================================================
296 * \brief Make triangulation of a shape precise enough
298 //================================================================================
300 void updateTriangulation( const TopoDS_Shape& shape )
302 // static set< Poly_Triangulation* > updated;
304 // TopLoc_Location loc;
305 // TopExp_Explorer fExp( shape, TopAbs_FACE );
306 // for ( ; fExp.More(); fExp.Next() )
308 // Handle(Poly_Triangulation) triangulation =
309 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
310 // if ( triangulation.IsNull() ||
311 // updated.insert( triangulation.operator->() ).second )
313 // BRepTools::Clean (shape);
316 BRepMesh_IncrementalMesh e(shape, 0.01, true);
318 catch (Standard_Failure&)
321 // updated.erase( triangulation.operator->() );
322 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
323 // updated.insert( triangulation.operator->() );
327 //================================================================================
329 * \brief Returns a medium node either existing in SMESH of created by NETGEN
330 * \param [in] corner1 - corner node 1
331 * \param [in] corner2 - corner node 2
332 * \param [in] defaultMedium - the node created by NETGEN
333 * \param [in] helper - holder of medium nodes existing in SMESH
334 * \return const SMDS_MeshNode* - the result node
336 //================================================================================
338 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
339 const SMDS_MeshNode* corner2,
340 const SMDS_MeshNode* defaultMedium,
341 const SMESH_MesherHelper* helper)
345 TLinkNodeMap::const_iterator l2n =
346 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
347 if ( l2n != helper->GetTLinkNodeMap().end() )
348 defaultMedium = l2n->second;
350 return defaultMedium;
353 //================================================================================
355 * \brief Assure that mesh on given shapes is quadratic
357 //================================================================================
359 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
360 // SMESH_Mesh* mesh )
362 // for ( int i = 1; i <= shapes.Extent(); ++i )
364 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
365 // if ( !smDS ) continue;
366 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
367 // if ( !elemIt->more() ) continue;
368 // const SMDS_MeshElement* e = elemIt->next();
369 // if ( !e || e->IsQuadratic() )
372 // TIDSortedElemSet elems;
373 // elems.insert( e );
374 // while ( elemIt->more() )
375 // elems.insert( elems.end(), elemIt->next() );
377 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
381 //================================================================================
383 * \brief Restrict size of elements on the given edge
385 //================================================================================
387 void setLocalSize(const TopoDS_Edge& edge,
390 const bool overrideMinH = true)
392 if ( size <= std::numeric_limits<double>::min() )
394 Standard_Real u1, u2;
395 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
396 if ( curve.IsNull() )
398 TopoDS_Iterator vIt( edge );
399 if ( !vIt.More() ) return;
400 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
401 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
405 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
406 Standard_Real delta = (u2-u1)/nb;
407 for(int i=0; i<nb; i++)
409 Standard_Real u = u1 + delta*i;
410 gp_Pnt p = curve->Value(u);
411 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
412 netgen::Point3d pi(p.X(), p.Y(), p.Z());
413 double resultSize = mesh.GetH(pi);
414 if ( resultSize - size > 0.1*size )
415 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
416 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
421 //================================================================================
423 * \brief Return triangle size for a given chordalError and radius of curvature
425 //================================================================================
427 double elemSizeForChordalError( double chordalError, double radius )
429 if ( 2 * radius < chordalError )
431 return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
434 //=============================================================================
438 //=============================================================================
440 void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize)
442 if ( GeomShape.IsNull() ) return;
443 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
444 if (GeomType == TopAbs_COMPOUND) {
445 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
446 setLocalSize(it.Value(), LocalSize);
451 if (! ShapesWithLocalSize.Contains(GeomShape))
452 key = ShapesWithLocalSize.Add(GeomShape);
454 key = ShapesWithLocalSize.FindIndex(GeomShape);
455 if (GeomType == TopAbs_VERTEX) {
456 VertexId2LocalSize[key] = LocalSize;
457 } else if (GeomType == TopAbs_EDGE) {
458 EdgeId2LocalSize[key] = LocalSize;
459 } else if (GeomType == TopAbs_FACE) {
460 FaceId2LocalSize[key] = LocalSize;
461 } else if (GeomType == TopAbs_SOLID) {
462 SolidId2LocalSize[key] = LocalSize;
467 //================================================================================
469 * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies
470 * \param [in] f - proxy face
471 * \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies
472 * \param [in] faceNgID - NETGEN ID of the FACE
473 * \return int - NETGEN ID of the FACE
475 //================================================================================
477 int getFaceNgID( const SMDS_MeshElement* face,
478 const int * solidSMDSIDs,
481 for ( int i = 0; i < 3; ++i )
483 const SMDS_MeshNode* n = face->GetNode( i );
484 const int shapeID = n->GetShapeID();
485 if ( shapeID == solidSMDSIDs[0] )
487 if ( shapeID == solidSMDSIDs[1] )
490 std::vector<const SMDS_MeshNode*> fNodes( face->begin_nodes(), face->end_nodes() );
491 std::vector<const SMDS_MeshElement*> vols;
492 if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ))
493 for ( size_t i = 0; i < vols.size(); ++i )
495 const int shapeID = vols[i]->GetShapeID();
496 if ( shapeID == solidSMDSIDs[0] )
498 if ( shapeID == solidSMDSIDs[1] )
506 //=============================================================================
510 //=============================================================================
512 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
513 const TopoDS_Shape& aShape,
519 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
520 _isViscousLayers2D(false),
521 _chordalError(-1), // means disabled
528 _viscousLayersHyp(NULL),
531 SetDefaultParameters();
532 ShapesWithLocalSize.Clear();
533 VertexId2LocalSize.clear();
534 EdgeId2LocalSize.clear();
535 FaceId2LocalSize.clear();
536 SolidId2LocalSize.clear();
537 ControlPoints.clear();
538 ShapesWithControlPoints.clear();
541 //================================================================================
545 //================================================================================
547 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
555 //================================================================================
557 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
558 * nullified at destruction of this
560 //================================================================================
562 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
573 //================================================================================
575 * \brief Initialize global NETGEN parameters with default values
577 //================================================================================
579 void NETGENPlugin_Mesher::SetDefaultParameters()
581 netgen::MeshingParameters& mparams = netgen::mparam;
582 mparams = netgen::MeshingParameters();
583 // maximal mesh edge size
584 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
586 // minimal number of segments per edge
587 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
588 // rate of growth of size between elements
589 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
590 // safety factor for curvatures (elements per radius)
591 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
592 // create elements of second order
593 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
594 // quad-dominated surface meshing
598 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
599 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
600 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
601 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
605 mparams.nthreads = std::thread::hardware_concurrency();
610 //=============================================================================
612 * Pass parameters to NETGEN
614 //=============================================================================
615 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
619 netgen::MeshingParameters& mparams = netgen::mparam;
620 // Initialize global NETGEN parameters:
621 // maximal mesh segment size
622 mparams.maxh = hyp->GetMaxSize();
623 // maximal mesh element linear size
624 mparams.minh = hyp->GetMinSize();
625 // minimal number of segments per edge
626 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
627 // rate of growth of size between elements
628 mparams.grading = hyp->GetGrowthRate();
629 // safety factor for curvatures (elements per radius)
630 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
631 // create elements of second order
632 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
633 // quad-dominated surface meshing
634 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
635 _optimize = hyp->GetOptimize();
636 _fineness = hyp->GetFineness();
637 mparams.uselocalh = hyp->GetSurfaceCurvature();
638 netgen::merge_solids = hyp->GetFuseEdges();
639 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
640 mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0;
641 mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0;
642 mparams.elsizeweight = hyp->GetElemSizeWeight();
643 mparams.opterrpow = hyp->GetWorstElemMeasure();
644 mparams.delaunay = hyp->GetUseDelauney();
645 mparams.checkoverlap = hyp->GetCheckOverlapping();
646 mparams.checkchartboundary = hyp->GetCheckChartBoundary();
651 mparams.meshsizefilename = hyp->GetMeshSizeFile();
654 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
656 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
657 if ( !localSizes.empty() )
659 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
660 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
661 for ( ; it != localSizes.end() ; it++)
663 std::string entry = (*it).first;
664 double val = (*it).second;
666 GEOM::GEOM_Object_var aGeomObj;
667 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
668 if ( !aSObj->_is_nil() ) {
669 CORBA::Object_var obj = aSObj->GetObject();
670 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
673 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
674 setLocalSize(S, val);
681 netgen::mparam.closeedgefac = 2;
686 //=============================================================================
688 * Pass simple parameters to NETGEN
690 //=============================================================================
692 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
696 SetDefaultParameters();
699 //================================================================================
701 * \brief Store a Viscous Layers hypothesis
703 //================================================================================
705 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
707 _viscousLayersHyp = hyp;
710 //================================================================================
712 * \brief Set local size on shapes defined by SetParameters()
714 //================================================================================
716 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
717 netgen::Mesh& ngMesh)
720 std::map<int,double>::const_iterator it;
721 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
723 int key = (*it).first;
724 double hi = (*it).second;
725 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
726 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
729 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
731 int key = (*it).first;
732 double hi = (*it).second;
733 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
734 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
735 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
738 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
740 int key = (*it).first;
741 double val = (*it).second;
742 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
743 int faceNgID = occgeo.fmap.FindIndex(shape);
747 occgeo.SetFaceMaxH(faceNgID-1, val, netgen::mparam);
749 occgeo.SetFaceMaxH(faceNgID, val);
751 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
752 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
754 else if ( !ShapesWithControlPoints.count( key ))
756 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
757 ShapesWithControlPoints.insert( key );
761 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
763 int key = (*it).first;
764 double val = (*it).second;
765 if ( !ShapesWithControlPoints.count( key ))
767 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
768 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
769 ShapesWithControlPoints.insert( key );
773 if ( !ControlPoints.empty() )
775 for ( size_t i = 0; i < ControlPoints.size(); ++i )
776 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
781 //================================================================================
783 * \brief Restrict local size to achieve a required _chordalError
785 //================================================================================
787 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
788 netgen::Mesh& ngMesh)
790 if ( _chordalError <= 0. )
794 BRepLProp_SLProps surfProp( 2, 1e-6 );
795 const double sizeCoef = 0.95;
797 // find non-planar FACEs with non-constant curvature
798 std::vector<int> fInd;
799 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
801 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
802 BRepAdaptor_Surface surfAd( face, false );
803 switch ( surfAd.GetType() )
807 case GeomAbs_Cylinder:
809 case GeomAbs_Torus: // constant curvature
811 surfProp.SetSurface( surfAd );
812 surfProp.SetParameters( 0, 0 );
813 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
814 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
816 occgeo.SetFaceMaxH( i-1, size * sizeCoef, netgen::mparam );
818 occgeo.SetFaceMaxH( i, size * sizeCoef );
820 // limit size one edges
821 TopTools_MapOfShape edgeMap;
822 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
823 if ( edgeMap.Add( eExp.Current() ))
824 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
828 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
829 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
838 TopoDS_Compound allFacesComp;
839 b.MakeCompound( allFacesComp );
840 for ( size_t i = 0; i < fInd.size(); ++i )
841 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
843 // copy the shape to avoid spoiling its triangulation
844 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
846 // create triangulation with desired chordal error
847 BRepMesh_IncrementalMesh( allFacesCompCopy,
849 /*isRelative = */Standard_False,
850 /*theAngDeflection = */ 0.5,
851 /*isInParallel = */Standard_True);
854 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
856 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
857 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
858 if ( triangulation.IsNull() ) continue;
860 BRepAdaptor_Surface surf( face, false );
861 surfProp.SetSurface( surf );
866 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
868 Standard_Integer n1,n2,n3;
869 triangulation->Triangles()(i).Get( n1,n2,n3 );
870 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
871 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
872 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
873 uv[0] = triangulation->UVNodes()(n1).XY();
874 uv[1] = triangulation->UVNodes()(n2).XY();
875 uv[2] = triangulation->UVNodes()(n3).XY();
876 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
877 if ( !surfProp.IsCurvatureDefined() )
880 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
882 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
883 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
884 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
886 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
888 int n2 = ( n1 + 1 ) % 3;
889 double minSize = size[n1], maxSize = size[n2];
890 if ( size[n1] > size[n2] )
891 minSize = size[n2], maxSize = size[n1];
893 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
895 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
896 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
897 sizeCoef * minSize );
901 gp_XY uvVec( uv[n2] - uv[n1] );
902 double len = ( p[n1] - p[n2] ).Modulus();
903 int nb = int( len / minSize ) + 1;
904 for ( int j = 0; j <= nb; ++j )
906 double r = double( j ) / nb;
907 gp_XY uvj = uv[n1] + r * uvVec;
909 surfProp.SetParameters( uvj.X(), uvj.Y() );
910 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
911 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
913 const gp_Pnt& pj = surfProp.Value();
914 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
915 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
924 //================================================================================
926 * \brief Initialize netgen::OCCGeometry with OCCT shape
928 //================================================================================
930 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
931 const TopoDS_Shape& shape,
933 list< SMESH_subMesh* > * meshedSM,
934 NETGENPlugin_Internals* intern)
936 updateTriangulation( shape );
939 BRepBndLib::Add (shape, bb);
940 double x1,y1,z1,x2,y2,z2;
941 bb.Get (x1,y1,z1,x2,y2,z2);
942 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
943 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
944 occgeo.boundingbox = netgen::Box<3> (p1,p2);
946 occgeo.shape = shape;
949 // fill maps of shapes of occgeo with not yet meshed subshapes
951 // get root submeshes
952 list< SMESH_subMesh* > rootSM;
953 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
954 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
955 rootSM.push_back( mesh.GetSubMesh( shape ));
958 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
959 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
964 // add subshapes of empty submeshes
965 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
966 for ( ; rootIt != rootEnd; ++rootIt ) {
967 SMESH_subMesh * root = *rootIt;
968 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
969 /*complexShapeFirst=*/true);
970 // to find a right orientation of subshapes (PAL20462)
971 TopTools_IndexedMapOfShape subShapes;
972 TopExp::MapShapes(root->GetSubShape(), subShapes);
973 while ( smIt->more() )
975 SMESH_subMesh* sm = smIt->next();
976 TopoDS_Shape shape = sm->GetSubShape();
977 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
978 if ( intern && intern->isShapeToPrecompute( shape ))
980 if ( !meshedSM || sm->IsEmpty() )
982 if ( shape.ShapeType() != TopAbs_VERTEX )
983 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
984 if ( shape.Orientation() >= TopAbs_INTERNAL )
985 shape.Orientation( TopAbs_FORWARD ); // issue 0020676
986 switch ( shape.ShapeType() ) {
987 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
988 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
989 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
990 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
994 // collect submeshes of meshed shapes
997 const int dim = SMESH_Gen::GetShapeDim( shape );
998 meshedSM[ dim ].push_back( sm );
1002 occgeo.facemeshstatus.SetSize (totNbFaces);
1003 occgeo.facemeshstatus = 0;
1004 occgeo.face_maxh_modified.SetSize(totNbFaces);
1005 occgeo.face_maxh_modified = 0;
1006 occgeo.face_maxh.SetSize(totNbFaces);
1007 occgeo.face_maxh = netgen::mparam.maxh;
1010 //================================================================================
1012 * \brief Return a default min size value suitable for the given geometry.
1014 //================================================================================
1016 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
1017 const double maxSize)
1019 updateTriangulation( geom );
1021 TopLoc_Location loc;
1023 const int* pi[4] = { &i1, &i2, &i3, &i1 };
1024 double minh = 1e100;
1026 TopExp_Explorer fExp( geom, TopAbs_FACE );
1027 for ( ; fExp.More(); fExp.Next() )
1029 Handle(Poly_Triangulation) triangulation =
1030 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1031 if ( triangulation.IsNull() ) continue;
1032 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1033 const TColgp_Array1OfPnt& points = triangulation->Nodes();
1034 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1035 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1037 trias(iT).Get( i1, i2, i3 );
1038 for ( int j = 0; j < 3; ++j )
1040 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1041 if ( dist2 < minh && fTol*fTol < dist2 )
1043 bb.Add( points(*pi[j]));
1047 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1049 minh = 1e-3 * sqrt( bb.SquareExtent());
1050 //cout << "BND BOX minh = " <<minh << endl;
1054 minh = sqrt( minh ); // triangulation for visualization is rather fine
1055 //cout << "TRIANGULATION minh = " <<minh << endl;
1057 if ( minh > 0.5 * maxSize )
1058 minh = maxSize / 3.;
1063 //================================================================================
1065 * \brief Restrict size of elements at a given point
1067 //================================================================================
1069 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1072 const bool overrideMinH)
1074 if ( size <= std::numeric_limits<double>::min() )
1076 if ( netgen::mparam.minh > size )
1080 ngMesh.SetMinimalH( size );
1081 netgen::mparam.minh = size;
1085 size = netgen::mparam.minh;
1088 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1089 ngMesh.RestrictLocalH( pi, size );
1092 //================================================================================
1094 * \brief fill ngMesh with nodes and elements of computed submeshes
1096 //================================================================================
1098 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1099 netgen::Mesh& ngMesh,
1100 vector<const SMDS_MeshNode*>& nodeVec,
1101 const list< SMESH_subMesh* > & meshedSM,
1102 SMESH_MesherHelper* quadHelper,
1103 SMESH_ProxyMesh::Ptr proxyMesh)
1105 TNode2IdMap nodeNgIdMap;
1106 for ( size_t i = 1; i < nodeVec.size(); ++i )
1107 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1109 TopTools_MapOfShape visitedShapes;
1110 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1111 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1113 SMESH_MesherHelper helper (*_mesh);
1114 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1116 int faceNgID = ngMesh.GetNFD();
1118 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1119 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1121 SMESH_subMesh* sm = *smIt;
1122 if ( !visitedShapes.Add( sm->GetSubShape() ))
1125 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1126 if ( !smDS ) continue;
1128 switch ( sm->GetSubShape().ShapeType() )
1130 case TopAbs_EDGE: { // EDGE
1131 // ----------------------
1132 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1133 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1134 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1136 // Add ng segments for each not meshed FACE the EDGE bounds
1137 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1138 while ( const TopoDS_Shape * anc = fIt->next() )
1140 faceNgID = occgeom.fmap.FindIndex( *anc );
1142 continue; // meshed face
1144 int faceSMDSId = meshDS->ShapeToIndex( *anc );
1145 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1146 continue; // already treated EDGE
1148 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1149 if ( face.Orientation() >= TopAbs_INTERNAL )
1150 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1152 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1153 helper.SetSubShape( face );
1154 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1155 visitedEdgeSM2Faces );
1156 if ( edges.empty() )
1157 continue; // wrong ancestor?
1159 // find out orientation of <edges> within <face>
1160 TopoDS_Edge eNotSeam = edges.front();
1161 if ( helper.HasSeam() )
1163 list< TopoDS_Edge >::iterator eIt = edges.begin();
1164 while ( helper.IsRealSeam( *eIt )) ++eIt;
1165 if ( eIt != edges.end() )
1168 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1169 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1171 // get all nodes from connected <edges>
1172 const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1173 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1174 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1175 if ( points.empty() )
1176 return false; // invalid node params?
1177 smIdType i, nbSeg = fSide.NbSegments();
1179 // remember EDGEs of fSide to treat only once
1180 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1181 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1183 double otherSeamParam = 0;
1184 bool isSeam = false;
1188 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1190 for ( i = 0; i < nbSeg; ++i )
1192 const UVPtStruct& p1 = points[ i ];
1193 const UVPtStruct& p2 = points[ i+1 ];
1195 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1198 if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1200 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1201 isSeam = helper.IsRealSeam( e );
1204 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1208 netgen::Segment seg;
1211 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1212 // node param on curve
1213 seg.epgeominfo[ 0 ].dist = p1.param;
1214 seg.epgeominfo[ 1 ].dist = p2.param;
1216 seg.epgeominfo[ 0 ].u = p1.u;
1217 seg.epgeominfo[ 0 ].v = p1.v;
1218 seg.epgeominfo[ 1 ].u = p2.u;
1219 seg.epgeominfo[ 1 ].v = p2.v;
1221 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1222 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1224 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1225 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1226 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1227 ngMesh.AddSegment (seg);
1229 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1230 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1232 #ifdef DUMP_SEGMENTS
1233 cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1234 << "\tface index: " << seg.si << endl
1235 << "\tp1: " << seg[0] << endl
1236 << "\tp2: " << seg[1] << endl
1237 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1238 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1239 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1240 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1241 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1242 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1246 if ( helper.GetPeriodicIndex() && 1 ) {
1247 seg.epgeominfo[ 0 ].u = otherSeamParam;
1248 seg.epgeominfo[ 1 ].u = otherSeamParam;
1249 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1251 seg.epgeominfo[ 0 ].v = otherSeamParam;
1252 seg.epgeominfo[ 1 ].v = otherSeamParam;
1253 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1255 swap( seg[0], seg[1] );
1256 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1257 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1258 ngMesh.AddSegment( seg );
1259 #ifdef DUMP_SEGMENTS
1260 cout << "Segment: " << seg.edgenr << endl
1261 << "\t is SEAM (reverse) of the previous. "
1262 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1263 << " = " << otherSeamParam << endl;
1266 else if ( fOri == TopAbs_INTERNAL )
1268 swap( seg[0], seg[1] );
1269 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1270 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1271 ngMesh.AddSegment( seg );
1272 #ifdef DUMP_SEGMENTS
1273 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1277 } // loop on geomEdge ancestors
1279 if ( quadHelper ) // remember medium nodes of sub-meshes
1281 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1282 while ( edges->more() )
1284 const SMDS_MeshElement* e = edges->next();
1285 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1291 } // case TopAbs_EDGE
1293 case TopAbs_FACE: { // FACE
1294 // ----------------------
1295 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1296 helper.SetSubShape( geomFace );
1297 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1299 // Find solids the geomFace bounds
1300 int solidID1 = 0, solidID2 = 0; // ng IDs
1301 int solidSMDSIDs[2] = { 0,0 }; // smds IDs
1303 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1304 while ( const TopoDS_Shape * solid = solidIt->next() )
1306 int id = occgeom.somap.FindIndex ( *solid );
1307 if ( solidID1 && id != solidID1 ) solidID2 = id;
1309 if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1312 bool isShrunk = true;
1313 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1315 // if a proxy sub-mesh contains temporary faces, then these faces
1316 // should be used to mesh only one SOLID
1317 smDS = proxyMesh->GetSubMesh( geomFace );
1318 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1319 while ( faces->more() )
1321 const SMDS_MeshElement* f = faces->next();
1322 if ( proxyMesh->IsTemporary( f ))
1325 if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1328 solidSMDSIDs[1] = 0;
1329 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1330 std::vector<const SMDS_MeshElement*> vols;
1331 if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1333 int geomID = vols[0]->GetShapeID();
1334 const TopoDS_Shape& solid = meshDS->IndexToShape( geomID );
1335 if ( !solid.IsNull() )
1336 solidID1 = occgeom.somap.FindIndex ( solid );
1342 const int fID = occgeom.fmap.FindIndex( geomFace );
1343 if ( isShrunk ) // shrunk mesh
1345 // move netgen points according to moved nodes
1346 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1347 while ( smIt->more() )
1349 SMESH_subMesh* sub = smIt->next();
1350 if ( !sub->GetSubMeshDS() ) continue;
1351 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1352 while ( nodeIt->more() )
1354 const SMDS_MeshNode* n = nodeIt->next();
1355 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1356 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1357 ngPoint(0) = n->X();
1358 ngPoint(1) = n->Y();
1359 ngPoint(2) = n->Z();
1362 // remove faces near boundary to avoid their overlapping
1363 // with shrunk faces
1364 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1366 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1367 if ( elem.GetIndex() == fID )
1369 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1370 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1372 ngMesh.DeleteSurfaceElement( i );
1378 // exclude faces generated by NETGEN from computation of 3D mesh
1382 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1383 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1385 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1386 if ( elem.GetIndex() == fID )
1387 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1393 solidSMDSIDs[1] = 0;
1395 const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 && !isShrunk );
1397 // Add ng face descriptors of meshed faces
1399 if ( hasVLOn2Sides )
1401 // viscous layers are on two sides of the FACE
1402 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1404 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1408 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1410 // if second oreder is required, even already meshed faces must be passed to NETGEN
1411 int fID = occgeom.fmap.Add( geomFace );
1412 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1413 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1414 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1416 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1417 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1418 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1420 // Problem with the second order in a quadrangular mesh remains.
1421 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1422 // by FillSMesh() (find "AddFaceDescriptor")
1423 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1424 // are on faces where quadrangles were.
1425 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1426 // of the mentioned above quadrangles and triangles
1428 // Orient the face correctly in solidID1 (issue 0020206)
1429 bool reverse = false;
1431 TopoDS_Shape solid = occgeom.somap( solidID1 );
1432 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1433 if ( faceOriInSolid >= 0 )
1435 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1438 // Add surface elements
1440 netgen::Element2d tri(3);
1441 tri.SetIndex( faceNgID );
1442 SMESH_TNodeXYZ xyz[3];
1444 #ifdef DUMP_TRIANGLES
1445 cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1446 << " internal="<<isInternalFace << endl;
1449 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1450 while ( faces->more() )
1452 const SMDS_MeshElement* f = faces->next();
1453 if ( f->NbNodes() % 3 != 0 ) // not triangle
1455 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace,*sm->GetFather(),TopAbs_SOLID);
1456 if ( const TopoDS_Shape * solid = solidIt->next() )
1457 sm = _mesh->GetSubMesh( *solid );
1458 SMESH_BadInputElements* badElems =
1459 new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1461 sm->GetComputeError().reset( badElems );
1465 if ( hasVLOn2Sides )
1466 tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1468 for ( int i = 0; i < 3; ++i )
1470 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1473 // get node UV on face
1474 int shapeID = node->GetShapeID();
1475 if ( helper.IsSeamShape( shapeID ))
1477 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1478 inFaceNode = f->GetNodeWrap( i-1 );
1480 inFaceNode = f->GetNodeWrap( i+1 );
1482 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1484 int ind = reverse ? 3-i : i+1;
1485 tri.GeomInfoPi(ind).u = uv.X();
1486 tri.GeomInfoPi(ind).v = uv.Y();
1487 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1490 // pass a triangle size to NG size-map
1491 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1492 ( xyz[1] - xyz[2] ).Modulus() +
1493 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1494 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1495 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1497 ngMesh.AddSurfaceElement (tri);
1498 #ifdef DUMP_TRIANGLES
1499 cout << tri << endl;
1502 if ( isInternalFace )
1504 swap( tri[1], tri[2] );
1505 ngMesh.AddSurfaceElement (tri);
1506 #ifdef DUMP_TRIANGLES
1507 cout << tri << endl;
1510 } // loop on sub-mesh faces
1512 if ( quadHelper ) // remember medium nodes of sub-meshes
1514 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1515 while ( faces->more() )
1517 const SMDS_MeshElement* f = faces->next();
1518 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1524 } // case TopAbs_FACE
1526 case TopAbs_VERTEX: { // VERTEX
1527 // --------------------------
1528 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1529 // else netgen removes a free node and nodeVector becomes invalid
1530 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1534 while ( const TopoDS_Shape* e = ansIt->next() )
1536 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1537 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1542 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1543 if ( nodeIt->more() )
1544 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1550 } // loop on submeshes
1553 nodeVec.resize( ngMesh.GetNP() + 1 );
1554 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1555 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1556 nodeVec[ node_NgId->second ] = node_NgId->first;
1561 //================================================================================
1563 * \brief Duplicate mesh faces on internal geom faces
1565 //================================================================================
1567 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1568 netgen::Mesh& ngMesh,
1569 NETGENPlugin_Internals& internalShapes)
1571 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1573 // find ng indices of internal faces
1575 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1577 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1578 if ( internalShapes.isInternalShape( smeshID ))
1579 ngFaceIds.insert( ngFaceID );
1581 if ( !ngFaceIds.empty() )
1584 int i, nbFaces = ngMesh.GetNSE();
1585 for ( i = 1; i <= nbFaces; ++i)
1587 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1588 if ( ngFaceIds.count( elem.GetIndex() ))
1590 swap( elem[1], elem[2] );
1591 ngMesh.AddSurfaceElement (elem);
1597 //================================================================================
1599 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1600 * meshed due to NETGEN failure
1601 * \param [in] occgeom - geometry
1602 * \param [in,out] ngMesh - the mesh to fix
1603 * \param [inout] faceID - ID of the FACE to fix the mesh on
1604 * \return bool - is mesh is or becomes OK
1606 //================================================================================
1608 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1609 netgen::Mesh& ngMesh,
1612 // we address a case where the FACE is almost fully meshed except small holes
1613 // of usually triangular shape at FACE boundary (IPAL52861)
1615 // The case appeared to be not simple: holes only look triangular but
1616 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1617 // NG points on a seam edge. But the code below is very nice, leave it for
1622 if ( occgeom.fmap.Extent() < faceID )
1624 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1626 // find free links on the FACE
1628 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1630 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1631 if ( faceID != elem.GetIndex() )
1633 int n0 = elem[ elem.GetNP() - 1 ];
1634 for ( int i = 0; i < elem.GetNP(); ++i )
1637 Link link( n0, n1 );
1638 if ( !linkMap.Add( link ))
1639 linkMap.Remove( link );
1643 // add/remove boundary links
1644 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1646 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1647 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1649 Link link( seg[1], seg[0] ); // reverse!!!
1650 if ( !linkMap.Add( link ))
1651 linkMap.Remove( link );
1653 if ( linkMap.IsEmpty() )
1655 if ( linkMap.Extent() < 3 )
1658 // make triangles of the links
1660 netgen::Element2d tri(3);
1661 tri.SetIndex ( faceID );
1663 TLinkMap::Iterator linkIt( linkMap );
1664 Link link1 = linkIt.Value();
1665 // look for a link connected to link1
1666 TLinkMap::Iterator linkIt2 = linkIt;
1667 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1669 const Link& link2 = linkIt2.Value();
1670 if ( link2.IsConnected( link1 ))
1672 // look for a link connected to both link1 and link2
1673 TLinkMap::Iterator linkIt3 = linkIt2;
1674 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1676 const Link& link3 = linkIt3.Value();
1677 if ( link3.IsConnected( link1 ) &&
1678 link3.IsConnected( link2 ) )
1683 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1684 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1686 ngMesh.AddSurfaceElement( tri );
1688 // prepare for the next tria search
1689 if ( linkMap.Extent() == 3 )
1691 linkMap.Remove( link3 );
1692 linkMap.Remove( link2 );
1694 linkMap.Remove( link1 );
1695 link1 = linkIt.Value();
1708 //================================================================================
1709 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1710 gp_XY_FunPtr(Subtracted);
1711 //gp_XY_FunPtr(Added);
1713 //================================================================================
1715 * \brief Evaluate distance between two 2d points along the surface
1717 //================================================================================
1719 double evalDist( const gp_XY& uv1,
1721 const Handle(Geom_Surface)& surf,
1722 const int stopHandler=-1)
1724 if ( stopHandler > 0 ) // continue recursion
1726 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1727 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1729 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1730 if ( stopHandler == 0 ) // stop recursion
1733 // start recursion if necessary
1734 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1735 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1736 return dist3D; // equal parametrization of a planar surface
1738 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1741 //================================================================================
1743 * \brief Data of vertex internal in geom face
1745 //================================================================================
1749 gp_XY uv; //!< UV in face parametric space
1750 int ngId; //!< ng id of corresponding node
1751 gp_XY uvClose; //!< UV of closest boundary node
1752 int ngIdClose; //!< ng id of closest boundary node
1755 //================================================================================
1757 * \brief Data of vertex internal in solid
1759 //================================================================================
1763 int ngId; //!< ng id of corresponding node
1764 int ngIdClose; //!< ng id of closest 2d mesh element
1765 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1768 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1770 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1773 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1775 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1779 //================================================================================
1781 * \brief Make netgen take internal vertices in faces into account by adding
1782 * segments including internal vertices
1784 * This function works in supposition that 1D mesh is already computed in ngMesh
1786 //================================================================================
1788 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1789 netgen::Mesh& ngMesh,
1790 vector<const SMDS_MeshNode*>& nodeVec,
1791 NETGENPlugin_Internals& internalShapes)
1793 if ((int) nodeVec.size() < ngMesh.GetNP() )
1794 nodeVec.resize( ngMesh.GetNP(), 0 );
1796 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1797 SMESH_MesherHelper helper( internalShapes.getMesh() );
1799 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1800 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1801 for ( ; f2v != face2Vert.end(); ++f2v )
1803 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1804 if ( face.IsNull() ) continue;
1805 int faceNgID = occgeom.fmap.FindIndex (face);
1806 if ( faceNgID < 0 ) continue;
1808 TopLoc_Location loc;
1809 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1811 helper.SetSubShape( face );
1812 helper.SetElementsOnShape( true );
1814 // Get data of internal vertices and add them to ngMesh
1816 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1818 int i, nbSegInit = ngMesh.GetNSeg();
1820 // boundary characteristics
1821 double totSegLen2D = 0;
1824 const list<int>& iVertices = f2v->second;
1825 list<int>::const_iterator iv = iVertices.begin();
1826 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1829 // get node on vertex
1830 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1831 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1834 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1835 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1836 nV = SMESH_Algo::VertexNode( V, meshDS );
1837 if ( !nV ) continue;
1840 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1841 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1842 vData.ngId = ngMesh.GetNP();
1843 nodeVec.push_back( nV );
1847 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1848 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1850 // loop on all segments of the face to find the node closest to vertex and to count
1851 // average segment 2d length
1852 double closeDist2 = numeric_limits<double>::max(), dist2;
1854 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1856 netgen::Segment & seg = ngMesh.LineSegment(i);
1857 if ( seg.si != faceNgID ) continue;
1859 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1861 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1862 if ( ngIdLast == seg[ iEnd ] ) continue;
1863 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1864 if ( dist2 < closeDist2 )
1865 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1866 ngIdLast = seg[ iEnd ];
1870 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1874 dist2VData.insert( make_pair( closeDist2, vData ));
1877 if ( totNbSeg == 0 ) break;
1878 double avgSegLen2d = totSegLen2D / totNbSeg;
1880 // Loop on vertices to add segments
1882 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1883 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1885 double closeDist2 = dist_vData->first, dist2;
1886 TIntVData & vData = dist_vData->second;
1888 // try to find more close node among segments added for internal vertices
1889 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1891 netgen::Segment & seg = ngMesh.LineSegment(i);
1892 if ( seg.si != faceNgID ) continue;
1894 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1896 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1897 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1898 if ( dist2 < closeDist2 )
1899 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1902 // decide whether to use the closest node as the second end of segment or to
1903 // create a new point
1904 int segEnd1 = vData.ngId;
1905 int segEnd2 = vData.ngIdClose; // to use closest node
1906 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1907 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1908 double nodeDist2D = sqrt( closeDist2 );
1909 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1910 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1911 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1912 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1913 if ( hintLenOK || avgLenOK )
1915 // create a point between the closest node and V
1918 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1919 // direction from V to closet node in 2D
1920 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1922 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1923 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1925 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1926 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1927 segEnd2 = ngMesh.GetNP();
1928 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1929 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1930 nodeVec.push_back( nP );
1932 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1935 netgen::Segment seg;
1937 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1938 seg[0] = segEnd1; // ng node id
1939 seg[1] = segEnd2; // ng node id
1940 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1943 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1944 seg.epgeominfo[ 0 ].u = uvV.X();
1945 seg.epgeominfo[ 0 ].v = uvV.Y();
1946 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1947 seg.epgeominfo[ 1 ].u = uvP.X();
1948 seg.epgeominfo[ 1 ].v = uvP.Y();
1950 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1951 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1953 ngMesh.AddSegment (seg);
1955 // add reverse segment
1956 swap( seg[0], seg[1] );
1957 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1958 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1959 ngMesh.AddSegment (seg);
1963 ngMesh.CalcSurfacesOfNode();
1966 //================================================================================
1968 * \brief Make netgen take internal vertices in solids into account by adding
1969 * faces including internal vertices
1971 * This function works in supposition that 2D mesh is already computed in ngMesh
1973 //================================================================================
1975 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1976 netgen::Mesh& ngMesh,
1977 vector<const SMDS_MeshNode*>& nodeVec,
1978 NETGENPlugin_Internals& internalShapes)
1980 #ifdef DUMP_TRIANGLES_SCRIPT
1981 // create a python script making a mesh containing triangles added for internal vertices
1982 ofstream py(DUMP_TRIANGLES_SCRIPT);
1983 py << "import SMESH"<< endl
1984 << "from salome.smesh import smeshBuilder"<<endl
1985 << "smesh = smeshBuilder.New()"<<endl
1986 << "m = smesh.Mesh(name='triangles')" << endl;
1988 if ((int) nodeVec.size() < ngMesh.GetNP() )
1989 nodeVec.resize( ngMesh.GetNP(), 0 );
1991 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1992 SMESH_MesherHelper helper( internalShapes.getMesh() );
1994 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1995 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1996 for ( ; s2v != so2Vert.end(); ++s2v )
1998 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1999 if ( solid.IsNull() ) continue;
2000 int solidNgID = occgeom.somap.FindIndex (solid);
2001 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
2003 helper.SetSubShape( solid );
2004 helper.SetElementsOnShape( true );
2006 // find ng indices of faces within the solid
2008 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
2009 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
2010 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
2011 ngFaceIds.insert( 1 );
2013 // Get data of internal vertices and add them to ngMesh
2015 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
2017 int i, nbFaceInit = ngMesh.GetNSE();
2019 // boundary characteristics
2020 double totSegLen = 0;
2023 const list<int>& iVertices = s2v->second;
2024 list<int>::const_iterator iv = iVertices.begin();
2025 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2028 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2030 // get node on vertex
2031 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2034 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2035 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2036 nV = SMESH_Algo::VertexNode( V, meshDS );
2037 if ( !nV ) continue;
2040 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2041 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2042 vData.ngId = ngMesh.GetNP();
2043 nodeVec.push_back( nV );
2045 // loop on all 2d elements to find the one closest to vertex and to count
2046 // average segment length
2047 double closeDist2 = numeric_limits<double>::max(), avgDist2;
2048 for (i = 1; i <= ngMesh.GetNSE(); ++i)
2050 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2051 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2053 multimap< double, int> dist2nID; // sort nodes of element by distance from V
2054 for ( int j = 0; j < elem.GetNP(); ++j)
2056 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2057 double d2 = dist2( mpV, mp );
2058 dist2nID.insert( make_pair( d2, elem[j] ));
2059 avgDist2 += d2 / elem.GetNP();
2061 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2063 double dist = dist2nID.begin()->first; //avgDist2;
2064 if ( dist < closeDist2 )
2065 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2067 dist2VData.insert( make_pair( closeDist2, vData ));
2070 if ( totNbSeg == 0 ) break;
2071 double avgSegLen = totSegLen / totNbSeg;
2073 // Loop on vertices to add triangles
2075 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2076 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2078 double closeDist2 = dist_vData->first;
2079 TIntVSoData & vData = dist_vData->second;
2081 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2083 // try to find more close face among ones added for internal vertices
2084 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2086 double avgDist2 = 0;
2087 multimap< double, int> dist2nID;
2088 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2089 for ( int j = 0; j < elem.GetNP(); ++j)
2091 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2092 dist2nID.insert( make_pair( d, elem[j] ));
2093 avgDist2 += d / elem.GetNP();
2094 if ( avgDist2 < closeDist2 )
2095 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2098 // sort nodes of the closest face by angle with vector from V to the closest node
2099 const double tol = numeric_limits<double>::min();
2100 map< double, int > angle2ID;
2101 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2102 netgen::MeshPoint mp[2];
2103 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2104 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2105 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2106 gp_Vec v2p1( pV, p1 );
2107 double distN1 = v2p1.Magnitude();
2108 if ( distN1 <= tol ) continue;
2110 for ( int j = 0; j < closeFace.GetNP(); ++j)
2112 mp[1] = ngMesh.Point( closeFace[j] );
2113 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2114 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2116 // get node with angle of 60 degrees or greater
2117 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2118 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2119 const double minAngle = 30. * M_PI / 180.;
2120 const double angle = angle_id->first;
2121 bool angleOK = ( angle > minAngle );
2123 // find points to create a triangle
2124 netgen::Element2d tri(3);
2126 tri[0] = vData.ngId;
2127 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2128 tri[2] = angle_id->second; // to use the node with best angle
2130 // decide whether to use the closest node and the node with best angle or to create new ones
2131 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2133 bool createNew = !angleOK; //, distOK = true;
2135 int triInd = isBestAngleN ? 2 : 1;
2136 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2141 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2142 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2144 else if ( angle < tol )
2146 v2p1.SetX( v2p1.X() + 1e-3 );
2152 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2153 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2154 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2155 createNew = (createNew || avgLenOK || hintLenOK );
2156 // we create a new node not closer than 0.5 to the closest face
2157 // in order not to clash with other close face
2158 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2159 distFromV = r * distN1;
2163 // create a new point, between the node and the vertex if angleOK
2164 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2165 gp_Vec v2p( pV, p ); v2p.Normalize();
2166 if ( isBestAngleN && !angleOK )
2167 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2169 p = pV + v2p.XYZ() * distFromV;
2171 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2173 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2174 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2175 tri[triInd] = ngMesh.GetNP();
2176 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2179 ngMesh.AddSurfaceElement (tri);
2180 swap( tri[1], tri[2] );
2181 ngMesh.AddSurfaceElement (tri);
2183 #ifdef DUMP_TRIANGLES_SCRIPT
2184 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2185 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2186 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2187 << "m.AddFace([n1,n2,n3])" << endl;
2189 } // loop on internal vertices of a solid
2191 } // loop on solids with internal vertices
2194 //================================================================================
2196 * \brief Fill netgen mesh with segments of a FACE
2197 * \param ngMesh - netgen mesh
2198 * \param geom - container of OCCT geometry to mesh
2199 * \param wires - data of nodes on FACE boundary
2200 * \param helper - mesher helper holding the FACE
2201 * \param nodeVec - vector of nodes in which node index == netgen ID
2202 * \retval SMESH_ComputeErrorPtr - error description
2204 //================================================================================
2206 SMESH_ComputeErrorPtr
2207 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2208 netgen::OCCGeometry& geom,
2209 const TSideVector& wires,
2210 SMESH_MesherHelper& helper,
2211 vector< const SMDS_MeshNode* > & nodeVec,
2212 const bool overrideMinH)
2214 // ----------------------------
2215 // Check wires and count nodes
2216 // ----------------------------
2217 smIdType nbNodes = 0;
2218 for ( size_t iW = 0; iW < wires.size(); ++iW )
2220 StdMeshers_FaceSidePtr wire = wires[ iW ];
2221 if ( wire->MissVertexNode() )
2223 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2224 // It seems that there is no reason for this limitation
2226 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2228 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2229 if ((int) uvPtVec.size() != wire->NbPoints() )
2230 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2231 SMESH_Comment("Unexpected nb of points on wire ") << iW
2232 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2233 nbNodes += wire->NbPoints();
2235 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2236 if ( nodeVec.empty() )
2237 nodeVec.push_back( 0 );
2239 // -----------------
2241 // -----------------
2243 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2244 NETGENPlugin_NETGEN_2D_ONLY */
2246 // map for nodes on vertices since they can be shared between wires
2247 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2248 map<const SMDS_MeshNode*, int > node2ngID;
2249 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2251 set< int > subIDs; // ids of sub-shapes of the FACE
2252 for ( size_t iW = 0; iW < wires.size(); ++iW )
2254 StdMeshers_FaceSidePtr wire = wires[ iW ];
2255 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2257 subIDs.insert( wire->EdgeID( iE ));
2258 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2261 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2262 if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2263 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2266 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2267 if ( ngMesh.GetNFD() < 1 )
2268 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2270 for ( size_t iW = 0; iW < wires.size(); ++iW )
2272 StdMeshers_FaceSidePtr wire = wires[ iW ];
2273 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2274 const smIdType nbSegments = wire->NbPoints() - 1;
2276 // assure the 1st node to be in node2ngID, which is needed to correctly
2277 // "close chain of segments" (see below) in case if the 1st node is not
2278 // onVertex because it is on a Viscous layer
2279 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2281 // compute length of every segment
2282 vector<double> segLen( nbSegments );
2283 for ( int i = 0; i < nbSegments; ++i )
2284 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2286 int edgeID = 1, posID = -2;
2287 bool isInternalWire = false;
2288 double vertexNormPar = 0;
2289 const int prevNbNGSeg = ngMesh.GetNSeg();
2290 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2292 // Add the first point of a segment
2294 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2295 const int posShapeID = n->GetShapeID();
2296 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2297 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2299 // skip nodes on degenerated edges
2300 if ( helper.IsDegenShape( posShapeID ) &&
2301 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2304 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2305 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2306 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2307 if ( ngID1 > ngMesh.GetNP() )
2309 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2310 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2311 nodeVec.push_back( n );
2313 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2315 ngID2 = ngMesh.GetNP() + 1;
2316 if ( i > 0 ) // prev segment belongs to same wire
2318 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2325 netgen::Segment seg;
2327 seg[0] = ngID1; // ng node id
2328 seg[1] = ngID2; // ng node id
2329 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2330 seg.si = faceID; // = geom.fmap.FindIndex (face);
2332 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2334 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2336 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2337 seg.epgeominfo[ iEnd ].u = pnt.u;
2338 seg.epgeominfo[ iEnd ].v = pnt.v;
2340 // find out edge id and node parameter on edge
2341 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2342 if ( onVertex || posShapeID != posID )
2345 double normParam = pnt.normParam;
2347 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2348 int edgeIndexInWire = wire->EdgeIndex( normParam );
2349 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2350 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2351 edgeID = geom.emap.FindIndex( edge );
2353 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2354 // if ( onVertex ) // param on curve is different on each of two edges
2355 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2357 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2360 ngMesh.AddSegment (seg);
2362 // restrict size of elements near the segment
2363 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2364 // get an average size of adjacent segments to avoid sharp change of
2365 // element size (regression on issue 0020452, note 0010898)
2366 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
2367 int iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
2368 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2369 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2370 int( segLen[ i ] > sumH / 100.) +
2371 int( segLen[ iNext ] > sumH / 100.));
2373 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2375 if ( isInternalWire )
2377 swap (seg[0], seg[1]);
2378 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2379 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2380 ngMesh.AddSegment (seg);
2382 } // loop on segments on a wire
2384 // close chain of segments
2385 if ( nbSegments > 0 )
2387 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2388 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2389 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2390 if ( lastSeg[1] > ngMesh.GetNP() )
2392 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2393 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2394 nodeVec.push_back( lastNode );
2396 if ( isInternalWire )
2398 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2399 realLastSeg[0] = lastSeg[1];
2403 #ifdef DUMP_SEGMENTS
2404 cout << "BEGIN WIRE " << iW << endl;
2405 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2407 netgen::Segment& seg = ngMesh.LineSegment( i );
2409 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2410 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2412 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2416 cout << "Segment: " << seg.edgenr << endl
2417 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2418 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2419 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2420 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2421 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2422 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2423 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2424 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2426 cout << "--END WIRE " << iW << endl;
2428 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2431 } // loop on WIREs of a FACE
2433 // add a segment instead of an internal vertex
2434 if ( wasNgMeshEmpty )
2436 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2437 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2439 ngMesh.CalcSurfacesOfNode();
2444 //================================================================================
2446 * \brief Fill SMESH mesh according to contents of netgen mesh
2447 * \param occgeo - container of OCCT geometry to mesh
2448 * \param ngMesh - netgen mesh
2449 * \param initState - bn of entities in netgen mesh before computing
2450 * \param sMesh - SMESH mesh to fill in
2451 * \param nodeVec - vector of nodes in which node index == netgen ID
2452 * \param comment - returns problem description
2453 * \param quadHelper - holder of medium nodes of sub-meshes
2454 * \retval int - error
2456 //================================================================================
2458 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2459 netgen::Mesh& ngMesh,
2460 const NETGENPlugin_ngMeshInfo& initState,
2462 std::vector<const SMDS_MeshNode*>& nodeVec,
2463 SMESH_Comment& comment,
2464 SMESH_MesherHelper* quadHelper)
2466 int nbNod = ngMesh.GetNP();
2467 int nbSeg = ngMesh.GetNSeg();
2468 int nbFac = ngMesh.GetNSE();
2469 int nbVol = ngMesh.GetNE();
2471 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2473 // quadHelper is used for either
2474 // 1) making quadratic elements when a lower dimension mesh is loaded
2475 // to SMESH before conversion to quadratic by NETGEN
2476 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2477 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2480 int ngID, nbInitNod = initState._nbNodes;
2481 if ( initState._elementsRemoved )
2483 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2484 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2485 size_t i, nodeVecSize = nodeVec.size();
2486 const double eps = std::numeric_limits<double>::min();
2487 for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
2489 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2490 gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2491 if ( ngPnt.SquareDistance( node ) < eps )
2493 nodeVec[ ngID ] = nodeVec[ i ];
2500 nodeVec.resize( ngID );
2501 nbInitNod = ngID - 1;
2503 // -------------------------------------
2504 // Create and insert nodes into nodeVec
2505 // -------------------------------------
2507 if ( nbNod > nbInitNod )
2508 nodeVec.resize( nbNod + 1 );
2509 for ( int i = nbInitNod+1; i <= nbNod; ++i )
2511 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2512 SMDS_MeshNode* node = NULL;
2513 TopoDS_Vertex aVert;
2514 // First, netgen creates nodes on vertices in occgeo.vmap,
2515 // so node index corresponds to vertex index
2516 // but (issue 0020776) netgen does not create nodes with equal coordinates
2517 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2519 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2520 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2522 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2523 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2524 if ( p.SquareDistance( pV ) > 1e-20 )
2527 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2530 if (!node) // node not found on vertex
2532 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2533 if (!aVert.IsNull())
2534 meshDS->SetNodeOnVertex(node, aVert);
2539 // -------------------------------------------
2540 // Create mesh segments along geometric edges
2541 // -------------------------------------------
2543 int nbInitSeg = initState._nbSegments;
2544 for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
2546 const netgen::Segment& seg = ngMesh.LineSegment(i);
2548 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2551 for (int j=0; j < 3; ++j)
2553 int pind = pinds[j];
2554 if (pind <= 0 || !nodeVec_ACCESS(pind))
2562 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2563 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2564 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2566 param = seg.epgeominfo[j].dist;
2569 else // middle point
2571 param = param2 * 0.5;
2573 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2575 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2580 SMDS_MeshEdge* edge = 0;
2581 if (nbp == 2) // second order ?
2583 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2585 if ( quadHelper ) // final mesh must be quadratic
2586 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2588 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2592 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2593 nodeVec_ACCESS(pinds[2])))
2595 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2596 nodeVec_ACCESS(pinds[2]));
2600 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2601 MESSAGE("Cannot create a mesh edge");
2602 nbSeg = nbFac = nbVol = 0;
2605 if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2606 meshDS->SetMeshElementOnShape(edge, aEdge);
2608 else if ( comment.empty() )
2610 comment << "Invalid netgen segment #" << i;
2614 // ----------------------------------------
2615 // Create mesh faces along geometric faces
2616 // ----------------------------------------
2618 int nbInitFac = initState._nbFaces;
2619 int quadFaceID = ngMesh.GetNFD() + 1;
2620 if ( nbInitFac < nbFac )
2621 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2622 // from computation of 3D mesh
2623 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2625 vector<const SMDS_MeshNode*> nodes;
2626 for ( int i = nbInitFac+1; i <= nbFac; ++i )
2628 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2629 const int aGeomFaceInd = elem.GetIndex();
2631 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2632 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2634 for ( int j = 1; j <= elem.GetNP(); ++j )
2636 int pind = elem.PNum(j);
2637 if ( pind < 1 || pind >= (int) nodeVec.size() )
2639 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2641 nodes.push_back( node );
2642 if (!aFace.IsNull() && node->GetShapeID() < 1)
2644 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2645 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2649 if ((int) nodes.size() != elem.GetNP() )
2651 if ( comment.empty() )
2652 comment << "Invalid netgen 2d element #" << i;
2653 continue; // bad node ids
2655 SMDS_MeshFace* face = NULL;
2656 switch (elem.GetType())
2659 if ( quadHelper ) // final mesh must be quadratic
2660 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2662 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2665 if ( quadHelper ) // final mesh must be quadratic
2666 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2668 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2669 // exclude qudrangle elements from computation of 3D mesh
2670 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2673 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2674 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2675 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2676 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2679 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2680 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2681 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2682 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2683 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2684 nodes[4],nodes[7],nodes[5],nodes[6]);
2685 // exclude qudrangle elements from computation of 3D mesh
2686 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2689 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2694 if ( comment.empty() ) comment << "Cannot create a mesh face";
2695 MESSAGE("Cannot create a mesh face");
2696 nbSeg = nbFac = nbVol = 0;
2699 if ( !aFace.IsNull() )
2700 meshDS->SetMeshElementOnShape( face, aFace );
2703 // ------------------
2704 // Create tetrahedra
2705 // ------------------
2707 for ( int i = 1; i <= nbVol; ++i )
2709 const netgen::Element& elem = ngMesh.VolumeElement(i);
2710 int aSolidInd = elem.GetIndex();
2711 TopoDS_Solid aSolid;
2712 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2713 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2715 for ( int j = 1; j <= elem.GetNP(); ++j )
2717 int pind = elem.PNum(j);
2718 if ( pind < 1 || pind >= (int)nodeVec.size() )
2720 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2722 nodes.push_back(node);
2723 if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2724 meshDS->SetNodeInVolume(node, aSolid);
2727 if ((int) nodes.size() != elem.GetNP() )
2729 if ( comment.empty() )
2730 comment << "Invalid netgen 3d element #" << i;
2733 SMDS_MeshVolume* vol = NULL;
2734 switch ( elem.GetType() )
2737 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2740 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2741 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2742 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2743 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2744 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2745 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2746 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2747 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2750 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2755 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2756 MESSAGE("Cannot create a mesh volume");
2757 nbSeg = nbFac = nbVol = 0;
2760 if (!aSolid.IsNull())
2761 meshDS->SetMeshElementOnShape(vol, aSolid);
2763 return comment.empty() ? 0 : 1;
2768 //================================================================================
2770 * \brief Convert error into text
2772 //================================================================================
2774 std::string text(int err)
2779 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2782 //================================================================================
2784 * \brief Convert exception into text
2786 //================================================================================
2788 std::string text(Standard_Failure& ex)
2790 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2791 str << " at " << netgen::multithread.task
2792 << ": " << ex.DynamicType()->Name();
2793 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2794 str << ": " << ex.GetMessageString();
2797 //================================================================================
2799 * \brief Convert exception into text
2801 //================================================================================
2803 std::string text(netgen::NgException& ex)
2805 SMESH_Comment str("NgException");
2806 if ( strlen( netgen::multithread.task ) > 0 )
2807 str << " at " << netgen::multithread.task;
2808 str << ": " << ex.What();
2812 //================================================================================
2814 * \brief Looks for triangles lying on a SOLID
2816 //================================================================================
2818 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2819 SMESH_subMesh* solidSM )
2821 TopTools_IndexedMapOfShape solidSubs;
2822 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2823 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2825 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2826 for ( ; e != elems.end(); ++e )
2828 const SMDS_MeshElement* elem = *e;
2829 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2831 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2832 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2833 while ( nIt->more() )
2835 const SMDS_MeshNode* n = nIt->next();
2836 const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() );
2837 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2838 if ( nbNodesOnSolid > 2 ||
2839 nbNodesOnSolid == nbNodes)
2846 const double edgeMeshingTime = 0.001;
2847 const double faceMeshingTime = 0.019;
2848 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2849 const double faceOptimizTime = 0.06;
2850 const double voluMeshingTime = 0.15;
2851 const double volOptimizeTime = 0.77;
2854 //=============================================================================
2856 * Here we are going to use the NETGEN mesher
2858 //=============================================================================
2860 bool NETGENPlugin_Mesher::Compute()
2862 NETGENPlugin_NetgenLibWrapper ngLib;
2864 netgen::MeshingParameters& mparams = netgen::mparam;
2866 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2867 SMESH_MesherHelper quadHelper( *_mesh );
2868 quadHelper.SetIsQuadratic( mparams.secondorder );
2870 // -------------------------
2871 // Prepare OCC geometry
2872 // -------------------------
2874 netgen::OCCGeometry occgeo;
2875 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2876 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2877 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2880 _totalTime = edgeFaceMeshingTime;
2882 _totalTime += faceOptimizTime;
2884 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2885 double doneTime = 0;
2888 _curShapeIndex = -1;
2890 // -------------------------
2891 // Generate the mesh
2892 // -------------------------
2895 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2897 SMESH_Comment comment;
2900 // vector of nodes in which node index == netgen ID
2901 vector< const SMDS_MeshNode* > nodeVec;
2909 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2910 mparams.uselocalh = false;
2911 mparams.grading = 0.8; // not limitited size growth
2913 if ( _simpleHyp->GetNumberOfSegments() )
2915 mparams.maxh = occgeo.boundingbox.Diam();
2918 mparams.maxh = _simpleHyp->GetLocalLength();
2921 if ( mparams.maxh == 0.0 )
2922 mparams.maxh = occgeo.boundingbox.Diam();
2923 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2924 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2926 // Local size on faces
2927 occgeo.face_maxh = mparams.maxh;
2929 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2930 int startWith = netgen::MESHCONST_ANALYSE;
2931 int endWith = netgen::MESHCONST_ANALYSE;
2936 err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
2938 if(netgen::multithread.terminate)
2941 comment << text(err);
2943 catch (Standard_Failure& ex)
2945 comment << text(ex);
2947 catch (netgen::NgException & ex)
2949 comment << text(ex);
2951 bool hasSizeFile = !mparams.meshsizefilename.empty();
2953 bool hasSizeFile = mparams.meshsizefilename;
2956 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2958 err = 0; //- MESHCONST_ANALYSE isn't so important step
2961 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2963 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2965 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2966 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2970 // Pass 1D simple parameters to NETGEN
2971 // --------------------------------
2972 double nbSeg = (double) _simpleHyp->GetNumberOfSegments();
2973 double segSize = _simpleHyp->GetLocalLength();
2974 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2976 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2978 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2979 setLocalSize( e, segSize, *_ngMesh );
2982 else // if ( ! _simpleHyp )
2984 // Local size on shapes
2985 SetLocalSize( occgeo, *_ngMesh );
2986 SetLocalSizeForChordalError( occgeo, *_ngMesh );
2989 // Precompute internal edges (issue 0020676) in order to
2990 // add mesh on them correctly (twice) to netgen mesh
2991 if ( !err && internals.hasInternalEdges() )
2993 // load internal shapes into OCCGeometry
2994 netgen::OCCGeometry intOccgeo;
2995 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2996 intOccgeo.boundingbox = occgeo.boundingbox;
2997 intOccgeo.shape = occgeo.shape;
2998 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2999 intOccgeo.face_maxh = netgen::mparam.maxh;
3000 netgen::Mesh *tmpNgMesh = NULL;
3004 // compute local H on internal shapes in the main mesh
3005 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
3007 // let netgen create a temporary mesh
3008 ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3010 if ( netgen::multithread.terminate )
3013 // copy LocalH from the main to temporary mesh
3014 initState.transferLocalH( _ngMesh, tmpNgMesh );
3016 // compute mesh on internal edges
3017 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3018 err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3020 comment << text(err);
3022 catch (Standard_Failure& ex)
3024 comment << text(ex);
3027 initState.restoreLocalH( tmpNgMesh );
3029 // fill SMESH by netgen mesh
3030 vector< const SMDS_MeshNode* > tmpNodeVec;
3031 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3032 err = ( err || !comment.empty() );
3034 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3037 // Fill _ngMesh with nodes and segments of computed submeshes
3040 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3041 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3043 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3048 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3053 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3055 if ( netgen::multithread.terminate )
3058 comment << text(err);
3060 catch (Standard_Failure& ex)
3062 comment << text(ex);
3067 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3069 mparams.uselocalh = true; // restore as it is used at surface optimization
3071 // ---------------------
3072 // compute surface mesh
3073 // ---------------------
3076 // Pass 2D simple parameters to NETGEN
3078 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3080 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3081 mparams.grading = 0.4; // moderate size growth
3084 // length from edges
3085 if ( _ngMesh->GetNSeg() ) {
3086 double edgeLength = 0;
3087 TopTools_MapOfShape visitedEdges;
3088 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3089 if( visitedEdges.Add(exp.Current()) )
3090 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3091 // we have to multiply length by 2 since for each TopoDS_Edge there
3092 // are double set of NETGEN edges, in other words, we have to
3093 // divide _ngMesh->GetNSeg() by 2.
3094 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3097 mparams.maxh = 1000;
3099 mparams.grading = 0.2; // slow size growth
3101 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3102 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3103 _ngMesh->SetGlobalH (mparams.maxh);
3104 netgen::Box<3> bb = occgeo.GetBoundingBox();
3105 bb.Increase (bb.Diam()/20);
3106 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3109 // Care of vertices internal in faces (issue 0020676)
3110 if ( internals.hasInternalVertexInFace() )
3112 // store computed segments in SMESH in order not to create SMESH
3113 // edges for ng segments added by AddIntVerticesInFaces()
3114 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3115 // add segments to faces with internal vertices
3116 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3117 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3120 // Build viscous layers
3121 if (( _isViscousLayers2D ) ||
3122 ( !occgeo.fmap.IsEmpty() &&
3123 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3125 if ( !internals.hasInternalVertexInFace() ) {
3126 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3127 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3129 SMESH_ProxyMesh::Ptr viscousMesh;
3130 SMESH_MesherHelper helper( *_mesh );
3131 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3133 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3134 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3137 if ( viscousMesh->NbProxySubMeshes() == 0 )
3139 // exclude from computation ng segments built on EDGEs of F
3140 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3142 netgen::Segment & seg = _ngMesh->LineSegment(i);
3143 if (seg.si == faceID)
3146 // add new segments to _ngMesh instead of excluded ones
3147 helper.SetSubShape( F );
3149 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3150 error, &helper, viscousMesh );
3151 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3153 if ( !error ) error = SMESH_ComputeError::New();
3155 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3158 // Let netgen compute 2D mesh
3159 startWith = netgen::MESHCONST_MESHSURFACE;
3160 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3165 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3167 if ( netgen::multithread.terminate )
3170 comment << text (err);
3172 catch (Standard_Failure& ex)
3174 comment << text(ex);
3175 //err = 1; -- try to make volumes anyway
3177 catch (netgen::NgException& exc)
3179 comment << text(exc);
3180 //err = 1; -- try to make volumes anyway
3185 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3186 _ticTime = doneTime / _totalTime / _progressTic;
3188 // ---------------------
3189 // generate volume mesh
3190 // ---------------------
3191 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3192 if ( !err && _isVolume &&
3193 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3195 // load SMESH with computed segments and faces
3196 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3198 // compute prismatic boundary volumes
3199 smIdType nbQuad = _mesh->NbQuadrangles();
3200 SMESH_ProxyMesh::Ptr viscousMesh;
3201 if ( _viscousLayersHyp )
3203 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3207 // compute pyramids on quadrangles
3208 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3210 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3212 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3213 pyramidMeshes[ iS-1 ].reset( adaptor );
3214 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3218 // add proxy faces to NG mesh
3219 list< SMESH_subMesh* > viscousSM;
3220 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3222 list< SMESH_subMesh* > quadFaceSM;
3223 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3224 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3226 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3227 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3229 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3231 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3232 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3234 if ( !quadFaceSM.empty() )
3235 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3237 if ( !viscousSM.empty() )
3238 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3240 // fill _ngMesh with faces of sub-meshes
3241 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3242 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3243 // toPython( _ngMesh )
3245 if (!err && _isVolume)
3247 // Pass 3D simple parameters to NETGEN
3248 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3249 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3251 _ngMesh->Compress();
3252 if ( double vol = simple3d->GetMaxElementVolume() ) {
3254 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3255 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3258 // length from faces
3259 mparams.maxh = _ngMesh->AverageH();
3261 _ngMesh->SetGlobalH (mparams.maxh);
3262 mparams.grading = 0.4;
3263 ngLib.CalcLocalH( ngLib._ngMesh );
3265 // Care of vertices internal in solids and internal faces (issue 0020676)
3266 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3268 // store computed faces in SMESH in order not to create SMESH
3269 // faces for ng faces added here
3270 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3271 // add ng faces to solids with internal vertices
3272 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3273 // duplicate mesh faces on internal faces
3274 FixIntFaces( occgeo, *_ngMesh, internals );
3275 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3277 // Let netgen compute 3D mesh
3278 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3283 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3285 if ( netgen::multithread.terminate )
3288 if ( comment.empty() ) // do not overwrite a previous error
3289 comment << text(err);
3291 catch (Standard_Failure& ex)
3293 if ( comment.empty() ) // do not overwrite a previous error
3294 comment << text(ex);
3297 catch (netgen::NgException& exc)
3299 if ( comment.empty() ) // do not overwrite a previous error
3300 comment << text(exc);
3303 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3305 // Let netgen optimize 3D mesh
3306 if ( !err && _optimize )
3308 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3313 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3315 if ( netgen::multithread.terminate )
3318 if ( comment.empty() ) // do not overwrite a previous error
3319 comment << text(err);
3321 catch (Standard_Failure& ex)
3323 if ( comment.empty() ) // do not overwrite a previous error
3324 comment << text(ex);
3326 catch (netgen::NgException& exc)
3328 if ( comment.empty() ) // do not overwrite a previous error
3329 comment << text(exc);
3333 if (!err && mparams.secondorder > 0)
3338 if ( !meshedSM[ MeshDim_1D ].empty() )
3340 // remove segments not attached to geometry (IPAL0052479)
3341 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3343 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3344 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3346 _ngMesh->DeleteSegment( i );
3347 initState._nbSegments--;
3350 _ngMesh->Compress();
3352 // convert to quadratic
3354 occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
3356 netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
3359 // care of elements already loaded to SMESH
3360 // if ( initState._nbSegments > 0 )
3361 // makeQuadratic( occgeo.emap, _mesh );
3362 // if ( initState._nbFaces > 0 )
3363 // makeQuadratic( occgeo.fmap, _mesh );
3365 catch (Standard_Failure& ex)
3367 if ( comment.empty() ) // do not overwrite a previous error
3368 comment << "Exception in netgen at passing to 2nd order ";
3370 catch (netgen::NgException& exc)
3372 if ( comment.empty() ) // do not overwrite a previous error
3373 comment << exc.What();
3378 _ticTime = 0.98 / _progressTic;
3380 //int nbNod = _ngMesh->GetNP();
3381 //int nbSeg = _ngMesh->GetNSeg();
3382 int nbFac = _ngMesh->GetNSE();
3383 int nbVol = _ngMesh->GetNE();
3384 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3386 // Feed back the SMESHDS with the generated Nodes and Elements
3387 if ( true /*isOK*/ ) // get whatever built
3389 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3391 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3393 for ( size_t i = 0; i < nodeVec.size(); ++i )
3394 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3396 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3399 for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3401 nodeVec.resize( i );
3406 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3407 if ( readErr && readErr->HasBadElems() )
3410 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3411 comment += readErr->myComment;
3413 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3414 error->myName = COMPERR_ALGO_FAILED;
3415 if ( !comment.empty() )
3416 error->myComment = comment;
3418 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3419 // appear if the geometry contains coincident sub-shape due
3420 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3421 const int nbMaps = 2;
3422 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3423 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3424 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3425 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3426 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3427 if ( !sm->IsMeshComputed() )
3428 sm->SetIsAlwaysComputed( true );
3430 // set bad compute error to subshapes of all failed sub-shapes
3431 if ( !error->IsOK() )
3433 bool pb2D = false, pb3D = false;
3434 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3435 int status = occgeo.facemeshstatus[i-1];
3436 if (status == netgen::FACE_MESHED_OK ) continue;
3437 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3438 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3439 if ( !smError || smError->IsOK() ) {
3440 if ( status == netgen::FACE_FAILED )
3441 smError.reset( new SMESH_ComputeError( *error ));
3443 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3444 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3445 smError->myName = COMPERR_WARNING;
3447 pb2D = pb2D || smError->IsKO();
3450 if ( !pb2D ) // all faces are OK
3451 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3452 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3454 bool smComputed = nbVol && !sm->IsEmpty();
3455 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3457 size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3458 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3459 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
3461 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3462 if ( !smComputed && ( !smError || smError->IsOK() ))
3465 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3467 smError->myName = COMPERR_WARNING;
3469 else if ( smError->HasBadElems() ) // bad surface mesh
3471 if ( !hasBadElemOnSolid
3472 ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3476 pb3D = pb3D || ( smError && smError->IsKO() );
3478 if ( !pb2D && !pb3D )
3479 err = 0; // no fatal errors, only warnings
3482 ngLib._isComputeOk = !err;
3487 //=============================================================================
3491 //=============================================================================
3492 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3494 netgen::MeshingParameters& mparams = netgen::mparam;
3497 // -------------------------
3498 // Prepare OCC geometry
3499 // -------------------------
3500 netgen::OCCGeometry occgeo;
3501 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3502 PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3504 bool tooManyElems = false;
3505 const int hugeNb = std::numeric_limits<int>::max() / 100;
3510 // pass 1D simple parameters to NETGEN
3513 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3514 mparams.uselocalh = false;
3515 mparams.grading = 0.8; // not limitited size growth
3517 if ( _simpleHyp->GetNumberOfSegments() )
3519 mparams.maxh = occgeo.boundingbox.Diam();
3522 mparams.maxh = _simpleHyp->GetLocalLength();
3525 if ( mparams.maxh == 0.0 )
3526 mparams.maxh = occgeo.boundingbox.Diam();
3527 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3528 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3530 // let netgen create _ngMesh and calculate element size on not meshed shapes
3531 NETGENPlugin_NetgenLibWrapper ngLib;
3532 netgen::Mesh *ngMesh = NULL;
3533 int startWith = netgen::MESHCONST_ANALYSE;
3534 int endWith = netgen::MESHCONST_MESHEDGES;
3535 int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
3537 if(netgen::multithread.terminate)
3540 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3542 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3543 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3546 // if ( _simpleHyp )
3548 // // Pass 1D simple parameters to NETGEN
3549 // // --------------------------------
3550 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3551 // double segSize = _simpleHyp->GetLocalLength();
3552 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3554 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3556 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3557 // setLocalSize( e, segSize, *ngMesh );
3560 // else // if ( ! _simpleHyp )
3562 // // Local size on shapes
3563 // SetLocalSize( occgeo, *ngMesh );
3565 // calculate total nb of segments and length of edges
3566 double fullLen = 0.0;
3567 smIdType fullNbSeg = 0;
3568 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3569 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3570 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3572 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3573 if( !Edge2NbSeg.Bind(E,0) )
3576 double aLen = SMESH_Algo::EdgeLength(E);
3579 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
3581 aVec.resize( SMDSEntity_Last, 0);
3583 fullNbSeg += aVec[ entity ];
3586 // store nb of segments computed by Netgen
3588 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3590 const netgen::Segment& seg = ngMesh->LineSegment(i);
3591 Link link(seg[0], seg[1]);
3592 if ( !linkMap.Add( link )) continue;
3593 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3594 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3596 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3600 // store nb of nodes on edges computed by Netgen
3601 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3602 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3604 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3605 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3606 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3608 fullNbSeg += aVec[ entity ];
3609 Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
3611 if ( fullNbSeg == 0 )
3618 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3620 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3621 mparams.grading = 0.4; // moderate size growth
3624 // length from edges
3625 mparams.maxh = fullLen / double( fullNbSeg );
3626 mparams.grading = 0.2; // slow size growth
3629 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3630 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3632 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3634 TopoDS_Face F = TopoDS::Face( exp.Current() );
3635 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3637 BRepGProp::SurfaceProperties(F,G);
3638 double anArea = G.Mass();
3639 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3641 if ( !tooManyElems )
3643 TopTools_MapOfShape edges;
3644 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3645 if ( edges.Add( exp1.Current() ))
3646 nb1d += Edge2NbSeg.Find(exp1.Current());
3648 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3649 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3651 vector<smIdType> aVec(SMDSEntity_Last, 0);
3652 if( mparams.secondorder > 0 ) {
3653 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3654 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3655 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3658 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3659 aVec[SMDSEntity_Triangle] = nbFaces;
3661 aResMap[sm].swap(aVec);
3668 // pass 3D simple parameters to NETGEN
3669 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3670 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3672 if ( double vol = simple3d->GetMaxElementVolume() ) {
3674 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3675 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3678 // using previous length from faces
3680 mparams.grading = 0.4;
3681 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3684 BRepGProp::VolumeProperties(_shape,G);
3685 double aVolume = G.Mass();
3686 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3687 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3688 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3689 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3690 vector<smIdType> aVec(SMDSEntity_Last, 0 );
3691 if ( tooManyElems ) // avoid FPE
3693 aVec[SMDSEntity_Node] = hugeNb;
3694 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3698 if( mparams.secondorder > 0 ) {
3699 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3700 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3703 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3704 aVec[SMDSEntity_Tetra] = nbVols;
3707 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3708 aResMap[sm].swap(aVec);
3714 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
3715 const int * algoProgressTic,
3716 const double * algoProgress) const
3718 ((int&) _progressTic ) = *algoProgressTic + 1;
3720 if ( !_occgeom ) return 0;
3722 double progress = -1;
3725 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3727 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3729 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3731 int doneShapeIndex = -1;
3732 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3733 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3735 if ( doneShapeIndex+1 != _curShapeIndex )
3737 ((int&) _curShapeIndex) = doneShapeIndex+1;
3738 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3739 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3740 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3741 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3742 // << " " << doneTime / _totalTime / _progressTic << endl;
3746 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3748 int curShapeIndex = _curShapeIndex;
3749 if ( _ngMesh->GetNE() > 0 )
3751 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3752 curShapeIndex = el.GetIndex();
3754 if ( curShapeIndex != _curShapeIndex )
3756 ((int&) _curShapeIndex) = curShapeIndex;
3757 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3758 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3759 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3760 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3761 // << " " << doneTime / _totalTime / _progressTic << endl;
3766 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3771 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3772 progress > voluMeshingTime )
3774 progress = voluMeshingTime;
3775 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3777 ((int&) *algoProgressTic )++;
3778 ((double&) *algoProgress) = progress;
3780 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3782 return Min( progress, 0.99 );
3785 //================================================================================
3787 * \brief Read mesh entities preventing successful computation from "test.out" file
3789 //================================================================================
3791 SMESH_ComputeErrorPtr
3792 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3794 if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3795 SMESH_BadInputElements* err =
3796 new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3797 "Some edges multiple times in surface mesh");
3798 SMESH_File file("test.out");
3800 vector<int> three1(3), three2(3);
3801 const char* badEdgeStr = " multiple times in surface mesh";
3802 const int badEdgeStrLen = (int) strlen( badEdgeStr );
3803 const int nbNodes = (int) nodeVec.size();
3805 while( !file.eof() )
3807 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3808 file.getInts( two ) &&
3809 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3810 two[0] < nbNodes && two[1] < nbNodes )
3812 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3813 file += (int) badEdgeStrLen;
3815 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3818 // openelement 18 with open element 126
3822 const char* pos = file;
3823 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3824 ok = ok && file.getInts( two );
3825 ok = ok && file.getInts( three1 );
3826 ok = ok && file.getInts( three2 );
3827 for ( int i = 0; ok && i < 3; ++i )
3828 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3829 for ( int i = 0; ok && i < 3; ++i )
3830 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3833 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3834 nodeVec[ three1[1]],
3835 nodeVec[ three1[2]]));
3836 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3837 nodeVec[ three2[1]],
3838 nodeVec[ three2[2]]));
3839 err->myComment = "Intersecting triangles";
3853 size_t nbBadElems = err->myBadElements.size();
3854 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3857 return SMESH_ComputeErrorPtr( err );
3860 //================================================================================
3862 * \brief Write a python script creating an equivalent SALOME mesh.
3863 * This is useful to see what mesh is passed as input for the next step of mesh
3864 * generation (of mesh of higher dimension)
3866 //================================================================================
3868 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3870 const char* pyFile = "/tmp/ngMesh.py";
3871 ofstream outfile( pyFile, ios::out );
3872 if ( !outfile ) return;
3874 outfile << "import salome, SMESH" << std::endl
3875 << "from salome.smesh import smeshBuilder" << std::endl
3876 << "smesh = smeshBuilder.New()" << std::endl
3877 << "mesh = smesh.Mesh()" << std::endl << std::endl;
3879 using namespace netgen;
3883 for ( int i = 1; i <= ngMesh->GetNP(); i++)
3885 const Point3d & p = ngMesh->Point(i);
3886 outfile << "mesh.AddNode( ";
3887 outfile << p.X() << ", ";
3888 outfile << p.Y() << ", ";
3889 outfile << p.Z() << ") ## "<< i << std::endl;
3892 int nbDom = ngMesh->GetNDomains();
3893 for ( int i = 0; i < nbDom; ++i )
3894 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3897 for (int i = 1; i <= ngMesh->GetNSE(); i++)
3899 outfile << "mesh.AddFace([ ";
3900 Element2d sel = ngMesh->SurfaceElement(i);
3901 for (int j = 1; j <= sel.GetNP(); j++)
3902 outfile << sel.PNum(j) << ( j < sel.GetNP() ? ", " : " ])");
3903 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3904 outfile << std::endl;
3905 nbDel += sel.IsDeleted();
3909 if ( int dom1 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainIn())
3910 outfile << "grp"<< dom1 <<".Add([ " << i - nbDel << " ])" << std::endl;
3911 if ( int dom2 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainOut())
3912 outfile << "grp"<< dom2 <<".Add([ " << i - nbDel << " ])" << std::endl;
3916 for (int i = 1; i <= ngMesh->GetNE(); i++)
3918 Element el = ngMesh->VolumeElement(i);
3919 outfile << "mesh.AddVolume([ ";
3920 for (int j = 1; j <= el.GetNP(); j++)
3921 outfile << el.PNum(j) << ( j < el.GetNP() ? ", " : " ])");
3922 outfile << std::endl;
3925 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3927 const Segment & seg = ngMesh->LineSegment (i);
3928 outfile << "mesh.AddEdge([ "
3930 << seg[1]+1 << " ])" << std::endl;
3936 for (pi = PointIndex::BASE;
3937 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3939 outfile << "mesh.AddNode( ";
3940 outfile << (*ngMesh)[pi](0) << ", ";
3941 outfile << (*ngMesh)[pi](1) << ", ";
3942 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3945 int nbDom = ngMesh->GetNDomains();
3946 for ( int i = 0; i < nbDom; ++i )
3947 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3950 SurfaceElementIndex sei;
3951 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3953 outfile << "mesh.AddFace([ ";
3954 Element2d sel = (*ngMesh)[sei];
3955 for (int j = 0; j < sel.GetNP(); j++)
3956 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3957 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3958 outfile << std::endl;
3959 nbDel += sel.IsDeleted();
3961 if ((*ngMesh)[sei].GetIndex())
3963 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3964 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3965 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3966 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3970 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3972 Element el = (*ngMesh)[ei];
3973 outfile << "mesh.AddVolume([ ";
3974 for (int j = 0; j < el.GetNP(); j++)
3975 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3976 outfile << std::endl;
3979 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3981 const Segment & seg = ngMesh->LineSegment (i);
3982 outfile << "mesh.AddEdge([ "
3984 << seg[1] << " ])" << std::endl;
3989 std::cout << "Write " << pyFile << std::endl;
3992 //================================================================================
3994 * \brief Constructor of NETGENPlugin_ngMeshInfo
3996 //================================================================================
3998 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
3999 bool checkRemovedElems):
4000 _elementsRemoved( false ), _copyOfLocalH(0)
4004 _nbNodes = ngMesh->GetNP();
4005 _nbSegments = ngMesh->GetNSeg();
4006 _nbFaces = ngMesh->GetNSE();
4007 _nbVolumes = ngMesh->GetNE();
4009 if ( checkRemovedElems )
4010 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
4011 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
4015 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
4019 //================================================================================
4021 * \brief Copy LocalH member from one netgen mesh to another
4023 //================================================================================
4025 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
4026 netgen::Mesh* toMesh )
4028 if ( !fromMesh->LocalHFunctionGenerated() ) return;
4029 if ( !toMesh->LocalHFunctionGenerated() )
4030 NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
4032 const size_t size = sizeof( netgen::LocalH );
4033 _copyOfLocalH = new char[ size ];
4034 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
4035 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
4038 //================================================================================
4040 * \brief Restore LocalH member of a netgen mesh
4042 //================================================================================
4044 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
4046 if ( _copyOfLocalH )
4048 const size_t size = sizeof( netgen::LocalH );
4049 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
4050 delete [] _copyOfLocalH;
4055 //================================================================================
4057 * \brief Find "internal" sub-shapes
4059 //================================================================================
4061 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
4062 const TopoDS_Shape& shape,
4064 : _mesh( mesh ), _is3D( is3D )
4066 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4068 TopExp_Explorer f,e;
4069 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
4071 int faceID = meshDS->ShapeToIndex( f.Current() );
4073 // find not computed internal edges
4075 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4076 if ( e.Current().Orientation() == TopAbs_INTERNAL )
4078 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4079 if ( eSM->IsEmpty() )
4081 _e2face.insert( make_pair( eSM->GetId(), faceID ));
4082 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4083 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4087 // find internal vertices in a face
4088 set<int> intVV; // issue 0020850 where same vertex is twice in a face
4089 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4090 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4092 int vID = meshDS->ShapeToIndex( fSub.Value() );
4093 if ( intVV.insert( vID ).second )
4094 _f2v[ faceID ].push_back( vID );
4099 // find internal faces and their subshapes where nodes are to be doubled
4100 // to make a crack with non-sewed borders
4102 if ( f.Current().Orientation() == TopAbs_INTERNAL )
4104 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4107 list< TopoDS_Shape > edges;
4108 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4109 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4111 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4112 edges.push_back( e.Current() );
4113 // find border faces
4114 PShapeIteratorPtr fIt =
4115 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4116 while ( const TopoDS_Shape* pFace = fIt->next() )
4117 if ( !pFace->IsSame( f.Current() ))
4118 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4121 // we consider vertex internal if it is shared by more than one internal edge
4122 list< TopoDS_Shape >::iterator edge = edges.begin();
4123 for ( ; edge != edges.end(); ++edge )
4124 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4126 set<int> internalEdges;
4127 PShapeIteratorPtr eIt =
4128 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4129 while ( const TopoDS_Shape* pEdge = eIt->next() )
4131 int edgeID = meshDS->ShapeToIndex( *pEdge );
4132 if ( isInternalShape( edgeID ))
4133 internalEdges.insert( edgeID );
4135 if ( internalEdges.size() > 1 )
4136 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4140 } // loop on geom faces
4142 // find vertices internal in solids
4145 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4147 int soID = meshDS->ShapeToIndex( so.Current() );
4148 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4149 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4150 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4155 //================================================================================
4157 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4158 * some nodes of which are to be doubled to make the second border of the "crack"
4160 //================================================================================
4162 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4164 if ( _intShapes.empty() ) return;
4166 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4167 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4169 // loop on internal geom edges
4170 set<int>::const_iterator intShapeId = _intShapes.begin();
4171 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4173 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4174 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4176 // get internal and non-internal geom faces sharing the internal edge <s>
4178 set<int>::iterator bordFace = _borderFaces.end();
4179 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4180 while ( const TopoDS_Shape* pFace = faces->next() )
4182 int faceID = meshDS->ShapeToIndex( *pFace );
4183 if ( isInternalShape( faceID ))
4186 bordFace = _borderFaces.insert( faceID ).first;
4188 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4190 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4191 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4192 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4193 int nbSuspectFaces = 0;
4194 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4195 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4196 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4197 while ( smIt->more() )
4199 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4200 if ( !sm ) continue;
4201 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4202 while ( nIt->more() )
4204 const SMDS_MeshNode* nOnEdge = nIt->next();
4205 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4206 while ( fIt->more() )
4208 const SMDS_MeshElement* f = fIt->next();
4209 const int nbNodes = f->NbCornerNodes();
4210 if ( intFaceSM->Contains( f ))
4212 for ( int i = 0; i < nbNodes; ++i )
4213 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4218 for ( int i = 0; i < nbNodes; ++i )
4219 nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4221 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4227 // suspectFaces[0] having link with same orientation as mesh faces on
4228 // the internal geom face are <borderElems>. suspectFaces[1] have
4229 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4230 // by links of <borderElems> found at the 1st and 2nd loops
4231 set< SMESH_OrientedLink > borderLinks;
4232 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4234 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4235 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4237 const SMDS_MeshElement* f = *fIt;
4238 bool isBorder = false, linkFound = false, borderLinkFound = false;
4239 list< SMESH_OrientedLink > faceLinks;
4240 int nbNodes = f->NbCornerNodes();
4241 for ( int i = 0; i < nbNodes; ++i )
4243 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4244 faceLinks.push_back( link );
4247 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4248 if ( foundLink != links.end() )
4251 isBorder = ( foundLink->_reversed == link._reversed );
4252 if ( !isBorder && !isPostponed ) break;
4253 faceLinks.pop_back();
4255 else if ( isPostponed && !borderLinkFound )
4257 foundLink = borderLinks.find( link );
4258 if ( foundLink != borderLinks.end() )
4260 borderLinkFound = true;
4261 isBorder = ( foundLink->_reversed != link._reversed );
4268 borderElems.insert( f );
4269 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4271 else if ( !linkFound && !borderLinkFound )
4273 suspectFaces[1].push_back( f );
4274 if ( nbF > 2 * nbSuspectFaces )
4275 break; // dead loop protection
4282 //================================================================================
4284 * \brief put internal shapes in maps and fill in submeshes to precompute
4286 //================================================================================
4288 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4289 TopTools_IndexedMapOfShape& emap,
4290 TopTools_IndexedMapOfShape& vmap,
4291 list< SMESH_subMesh* > smToPrecompute[])
4293 if ( !hasInternalEdges() ) return;
4294 map<int,int>::const_iterator ev_face = _e2face.begin();
4295 for ( ; ev_face != _e2face.end(); ++ev_face )
4297 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4298 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4300 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4302 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4304 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4308 //================================================================================
4310 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4312 //================================================================================
4314 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4315 TopTools_IndexedMapOfShape& emap,
4316 list< SMESH_subMesh* >& intFaceSM,
4317 list< SMESH_subMesh* >& boundarySM)
4319 if ( !hasInternalFaces() ) return;
4321 // <fmap> and <emap> are for not yet meshed shapes
4322 // <intFaceSM> is for submeshes of faces
4323 // <boundarySM> is for meshed edges and vertices
4328 set<int> shapeIDs ( _intShapes );
4329 if ( !_borderFaces.empty() )
4330 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4332 set<int>::const_iterator intS = shapeIDs.begin();
4333 for ( ; intS != shapeIDs.end(); ++intS )
4335 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4337 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4339 intFaceSM.push_back( sm );
4341 // add submeshes of not computed internal faces
4342 if ( !sm->IsEmpty() ) continue;
4344 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4345 while ( smIt->more() )
4348 const TopoDS_Shape& s = sm->GetSubShape();
4350 if ( sm->IsEmpty() )
4353 switch ( s.ShapeType() ) {
4354 case TopAbs_FACE: fmap.Add ( s ); break;
4355 case TopAbs_EDGE: emap.Add ( s ); break;
4361 if ( s.ShapeType() != TopAbs_FACE )
4362 boundarySM.push_back( sm );
4368 //================================================================================
4370 * \brief Return true if given shape is to be precomputed in order to be correctly
4371 * added to netgen mesh
4373 //================================================================================
4375 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4377 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4378 switch ( s.ShapeType() ) {
4379 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4380 case TopAbs_EDGE : return isInternalEdge( shapeID );
4381 case TopAbs_VERTEX: break;
4387 //================================================================================
4389 * \brief Return SMESH
4391 //================================================================================
4393 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4395 return const_cast<SMESH_Mesh&>( _mesh );
4398 //================================================================================
4400 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4402 //================================================================================
4404 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4406 static int theCouner = 0;
4410 //================================================================================
4412 * \brief Initialize netgen library
4414 //================================================================================
4416 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
4419 if ( instanceCounter() == 0 )
4422 if ( !netgen::testout )
4423 netgen::testout = new ofstream( "test.out" );
4426 ++instanceCounter();
4428 _isComputeOk = false;
4432 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4434 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4435 _outputFileName = getOutputFileName();
4436 _ngcout = netgen::mycout;
4437 _ngcerr = netgen::myerr;
4438 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4439 netgen::myerr = netgen::mycout;
4440 _coutBuffer = std::cout.rdbuf();
4442 std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4444 std::cout.rdbuf( netgen::mycout->rdbuf() );
4448 setMesh( Ng_NewMesh() );
4451 //================================================================================
4453 * \brief Finish using netgen library
4455 //================================================================================
4457 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4459 --instanceCounter();
4461 Ng_DeleteMesh( ngMesh() );
4465 std::cout.rdbuf( _coutBuffer );
4472 //================================================================================
4474 * \brief Set netgen mesh to delete at destruction
4476 //================================================================================
4478 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4481 Ng_DeleteMesh( ngMesh() );
4482 _ngMesh = (netgen::Mesh*) mesh;
4485 //================================================================================
4487 * \brief Perform a step of mesh generation
4488 * \param [inout] occgeo - geometry to mesh
4489 * \param [inout] startWith - start step
4490 * \param [inout] endWith - end step
4491 * \param [inout] ngMesh - netgen mesh
4492 * \return int - is error
4494 //================================================================================
4496 int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
4497 int startWith, int endWith,
4498 netgen::Mesh* & ngMesh )
4502 ngMesh = new netgen::Mesh;
4506 ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
4508 netgen::mparam.perfstepsstart = startWith;
4509 netgen::mparam.perfstepsend = endWith;
4510 std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
4511 err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
4516 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
4521 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
4528 //================================================================================
4530 * \brief Create a mesh size tree
4532 //================================================================================
4534 void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
4536 #if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
4537 ngMesh->CalcLocalH(netgen::mparam.grading);
4539 ngMesh->CalcLocalH();
4543 //================================================================================
4545 * \brief Return a unique file name
4547 //================================================================================
4549 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4551 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4553 TCollection_AsciiString aGenericName = aTmpDir.c_str();
4554 aGenericName += "NETGEN_";
4556 aGenericName += getpid();
4558 aGenericName += _getpid();
4560 aGenericName += "_";
4561 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4562 aGenericName += ".out";
4564 return aGenericName.ToCString();
4567 //================================================================================
4569 * \brief Remove "test.out" and "problemfaces" files in current directory
4571 //================================================================================
4573 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4575 bool rm = SMESH_File("test.out").remove() ;
4577 if ( rm && netgen::testout && instanceCounter() == 0 )
4579 delete netgen::testout;
4580 netgen::testout = 0;
4583 SMESH_File("problemfaces").remove();
4584 SMESH_File("occmesh.rep").remove();
4587 //================================================================================
4589 * \brief Remove file with netgen output
4591 //================================================================================
4593 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4595 if ( !_outputFileName.empty() )
4599 delete netgen::mycout;
4600 netgen::mycout = _ngcout;
4601 netgen::myerr = _ngcerr;
4604 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4605 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4606 SALOMEDS_Tool::ListOfFiles aFiles;
4608 aFiles.push_back(aFileName.c_str());
4610 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );