1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // NETGENPlugin : C++ implementation
24 // File : NETGENPlugin_Mesher.cxx
25 // Author : Michael Sazonov (OCN)
28 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SALOMEDS_Tool.hxx>
53 #include <utilities.h>
55 #include <BRepAdaptor_Surface.hxx>
56 #include <BRepBuilderAPI_Copy.hxx>
57 #include <BRepLProp_SLProps.hxx>
58 #include <BRepMesh_IncrementalMesh.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <GeomLib_IsPlanarSurface.hxx>
63 #include <NCollection_Map.hxx>
64 #include <Poly_Triangulation.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TColStd_MapOfInteger.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopLoc_Location.hxx>
71 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
72 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
73 #include <TopTools_DataMapOfShapeInteger.hxx>
74 #include <TopTools_DataMapOfShapeShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS_Compound.hxx>
79 // 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();
602 // Unused argument but set 0 to initialise it
603 mparams.elementorder = 0;
607 mparams.nthreads = NETGENPlugin_Hypothesis::GetDefaultNbThreads();
609 if ( getenv( "SALOME_NETGEN_DISABLE_MULTITHREADING" ))
611 mparams.nthreads = 1;
612 mparams.parallel_meshing = false;
618 //=============================================================================
620 * Pass parameters to NETGEN
622 //=============================================================================
623 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
627 netgen::MeshingParameters& mparams = netgen::mparam;
628 // Initialize global NETGEN parameters:
629 // maximal mesh segment size
630 mparams.maxh = hyp->GetMaxSize();
631 // maximal mesh element linear size
632 mparams.minh = hyp->GetMinSize();
633 // minimal number of segments per edge
634 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
635 // rate of growth of size between elements
636 mparams.grading = hyp->GetGrowthRate();
637 // safety factor for curvatures (elements per radius)
638 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
639 // create elements of second order
640 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
641 // quad-dominated surface meshing
642 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
643 _optimize = hyp->GetOptimize();
644 _fineness = hyp->GetFineness();
645 mparams.uselocalh = hyp->GetSurfaceCurvature();
646 netgen::merge_solids = hyp->GetFuseEdges();
647 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
648 mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0;
649 mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0;
650 mparams.elsizeweight = hyp->GetElemSizeWeight();
651 mparams.opterrpow = hyp->GetWorstElemMeasure();
652 mparams.delaunay = hyp->GetUseDelauney();
653 mparams.checkoverlap = hyp->GetCheckOverlapping();
654 mparams.checkchartboundary = hyp->GetCheckChartBoundary();
659 mparams.meshsizefilename = hyp->GetMeshSizeFile();
660 mparams.nthreads = hyp->GetNbThreads();
663 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
665 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
666 if ( !localSizes.empty() )
668 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
669 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
670 for ( ; it != localSizes.end() ; it++)
672 std::string entry = (*it).first;
673 double val = (*it).second;
675 GEOM::GEOM_Object_var aGeomObj;
676 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
677 if ( !aSObj->_is_nil() ) {
678 CORBA::Object_var obj = aSObj->GetObject();
679 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
682 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
683 setLocalSize(S, val);
690 netgen::mparam.closeedgefac = 2;
695 //=============================================================================
697 * Pass simple parameters to NETGEN
699 //=============================================================================
701 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
705 SetDefaultParameters();
708 //================================================================================
710 * \brief Store a Viscous Layers hypothesis
712 //================================================================================
714 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
716 _viscousLayersHyp = hyp;
719 //================================================================================
721 * \brief Set local size on shapes defined by SetParameters()
723 //================================================================================
725 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
726 netgen::Mesh& ngMesh)
729 std::map<int,double>::const_iterator it;
730 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
732 int key = (*it).first;
733 double hi = (*it).second;
734 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
735 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
738 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
740 int key = (*it).first;
741 double hi = (*it).second;
742 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
743 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
744 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
747 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
749 int key = (*it).first;
750 double val = (*it).second;
751 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
752 int faceNgID = occgeo.fmap.FindIndex(shape);
756 occgeo.SetFaceMaxH(faceNgID-1, val, netgen::mparam);
758 occgeo.SetFaceMaxH(faceNgID, val);
760 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
761 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
763 else if ( !ShapesWithControlPoints.count( key ))
765 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
766 ShapesWithControlPoints.insert( key );
770 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
772 int key = (*it).first;
773 double val = (*it).second;
774 if ( !ShapesWithControlPoints.count( key ))
776 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
777 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
778 ShapesWithControlPoints.insert( key );
782 if ( !ControlPoints.empty() )
784 for ( size_t i = 0; i < ControlPoints.size(); ++i )
785 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
790 //================================================================================
792 * \brief Restrict local size to achieve a required _chordalError
794 //================================================================================
796 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
797 netgen::Mesh& ngMesh)
799 if ( _chordalError <= 0. )
803 BRepLProp_SLProps surfProp( 2, 1e-6 );
804 const double sizeCoef = 0.95;
806 // find non-planar FACEs with non-constant curvature
807 std::vector<int> fInd;
808 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
810 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
811 BRepAdaptor_Surface surfAd( face, false );
812 switch ( surfAd.GetType() )
816 case GeomAbs_Cylinder:
818 case GeomAbs_Torus: // constant curvature
820 surfProp.SetSurface( surfAd );
821 surfProp.SetParameters( 0, 0 );
822 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
823 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
825 occgeo.SetFaceMaxH( i-1, size * sizeCoef, netgen::mparam );
827 occgeo.SetFaceMaxH( i, size * sizeCoef );
829 // limit size one edges
830 TopTools_MapOfShape edgeMap;
831 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
832 if ( edgeMap.Add( eExp.Current() ))
833 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
837 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
838 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
847 TopoDS_Compound allFacesComp;
848 b.MakeCompound( allFacesComp );
849 for ( size_t i = 0; i < fInd.size(); ++i )
850 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
852 // copy the shape to avoid spoiling its triangulation
853 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
855 // create triangulation with desired chordal error
856 BRepMesh_IncrementalMesh( allFacesCompCopy,
858 /*isRelative = */Standard_False,
859 /*theAngDeflection = */ 0.5,
860 /*isInParallel = */Standard_True);
863 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
865 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
866 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
867 if ( triangulation.IsNull() ) continue;
869 BRepAdaptor_Surface surf( face, false );
870 surfProp.SetSurface( surf );
875 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
877 Standard_Integer n1,n2,n3;
878 triangulation->Triangles()(i).Get( n1,n2,n3 );
879 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
880 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
881 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
882 uv[0] = triangulation->UVNodes()(n1).XY();
883 uv[1] = triangulation->UVNodes()(n2).XY();
884 uv[2] = triangulation->UVNodes()(n3).XY();
885 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
886 if ( !surfProp.IsCurvatureDefined() )
889 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
891 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
892 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
893 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
895 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
897 int n2 = ( n1 + 1 ) % 3;
898 double minSize = size[n1], maxSize = size[n2];
899 if ( size[n1] > size[n2] )
900 minSize = size[n2], maxSize = size[n1];
902 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
904 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
905 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
906 sizeCoef * minSize );
910 gp_XY uvVec( uv[n2] - uv[n1] );
911 double len = ( p[n1] - p[n2] ).Modulus();
912 int nb = int( len / minSize ) + 1;
913 for ( int j = 0; j <= nb; ++j )
915 double r = double( j ) / nb;
916 gp_XY uvj = uv[n1] + r * uvVec;
918 surfProp.SetParameters( uvj.X(), uvj.Y() );
919 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
920 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
922 const gp_Pnt& pj = surfProp.Value();
923 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
924 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
933 //================================================================================
935 * \brief Initialize netgen::OCCGeometry with OCCT shape
937 //================================================================================
939 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
940 const TopoDS_Shape& shape,
942 list< SMESH_subMesh* > * meshedSM,
943 NETGENPlugin_Internals* intern)
945 updateTriangulation( shape );
948 BRepBndLib::Add (shape, bb);
949 double x1,y1,z1,x2,y2,z2;
950 bb.Get (x1,y1,z1,x2,y2,z2);
951 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
952 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
953 occgeo.boundingbox = netgen::Box<3> (p1,p2);
955 occgeo.shape = shape;
958 // fill maps of shapes of occgeo with not yet meshed subshapes
960 // get root submeshes
961 list< SMESH_subMesh* > rootSM;
962 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
963 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
964 rootSM.push_back( mesh.GetSubMesh( shape ));
967 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
968 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
973 // add subshapes of empty submeshes
974 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
975 for ( ; rootIt != rootEnd; ++rootIt ) {
976 SMESH_subMesh * root = *rootIt;
977 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
978 /*complexShapeFirst=*/true);
979 // to find a right orientation of subshapes (PAL20462)
980 TopTools_IndexedMapOfShape subShapes;
981 TopExp::MapShapes(root->GetSubShape(), subShapes);
982 while ( smIt->more() )
984 SMESH_subMesh* sm = smIt->next();
985 TopoDS_Shape shape = sm->GetSubShape();
986 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
987 if ( intern && intern->isShapeToPrecompute( shape ))
989 if ( !meshedSM || sm->IsEmpty() )
991 if ( shape.ShapeType() != TopAbs_VERTEX )
992 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
993 if ( shape.Orientation() >= TopAbs_INTERNAL )
994 shape.Orientation( TopAbs_FORWARD ); // issue 0020676
995 switch ( shape.ShapeType() ) {
996 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
997 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
998 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
999 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
1003 // collect submeshes of meshed shapes
1006 const int dim = SMESH_Gen::GetShapeDim( shape );
1007 meshedSM[ dim ].push_back( sm );
1011 occgeo.facemeshstatus.SetSize (totNbFaces);
1012 occgeo.facemeshstatus = 0;
1013 occgeo.face_maxh_modified.SetSize(totNbFaces);
1014 occgeo.face_maxh_modified = 0;
1015 occgeo.face_maxh.SetSize(totNbFaces);
1016 occgeo.face_maxh = netgen::mparam.maxh;
1019 //================================================================================
1021 * \brief Return a default min size value suitable for the given geometry.
1023 //================================================================================
1025 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
1026 const double maxSize)
1028 updateTriangulation( geom );
1030 TopLoc_Location loc;
1032 const int* pi[4] = { &i1, &i2, &i3, &i1 };
1033 double minh = 1e100;
1035 TopExp_Explorer fExp( geom, TopAbs_FACE );
1036 for ( ; fExp.More(); fExp.Next() )
1038 Handle(Poly_Triangulation) triangulation =
1039 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1040 if ( triangulation.IsNull() ) continue;
1041 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1042 const TColgp_Array1OfPnt& points = triangulation->Nodes();
1043 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1044 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1046 trias(iT).Get( i1, i2, i3 );
1047 for ( int j = 0; j < 3; ++j )
1049 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1050 if ( dist2 < minh && fTol*fTol < dist2 )
1052 bb.Add( points(*pi[j]));
1056 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1058 minh = 1e-3 * sqrt( bb.SquareExtent());
1059 //cout << "BND BOX minh = " <<minh << endl;
1063 minh = sqrt( minh ); // triangulation for visualization is rather fine
1064 //cout << "TRIANGULATION minh = " <<minh << endl;
1066 if ( minh > 0.5 * maxSize )
1067 minh = maxSize / 3.;
1072 //================================================================================
1074 * \brief Restrict size of elements at a given point
1076 //================================================================================
1078 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1081 const bool overrideMinH)
1083 if ( size <= std::numeric_limits<double>::min() )
1085 if ( netgen::mparam.minh > size )
1089 ngMesh.SetMinimalH( size );
1090 netgen::mparam.minh = size;
1094 size = netgen::mparam.minh;
1097 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1098 ngMesh.RestrictLocalH( pi, size );
1101 //================================================================================
1103 * \brief fill ngMesh with nodes and elements of computed submeshes
1105 //================================================================================
1107 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1108 netgen::Mesh& ngMesh,
1109 vector<const SMDS_MeshNode*>& nodeVec,
1110 const list< SMESH_subMesh* > & meshedSM,
1111 SMESH_MesherHelper* quadHelper,
1112 SMESH_ProxyMesh::Ptr proxyMesh)
1114 TNode2IdMap nodeNgIdMap;
1115 for ( size_t i = 1; i < nodeVec.size(); ++i )
1116 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1118 TopTools_MapOfShape visitedShapes;
1119 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1120 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1122 SMESH_MesherHelper helper (*_mesh);
1123 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1125 int faceNgID = ngMesh.GetNFD();
1127 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1128 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1130 SMESH_subMesh* sm = *smIt;
1131 if ( !visitedShapes.Add( sm->GetSubShape() ))
1134 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1135 if ( !smDS ) continue;
1137 switch ( sm->GetSubShape().ShapeType() )
1139 case TopAbs_EDGE: { // EDGE
1140 // ----------------------
1141 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1142 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1143 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1145 // Add ng segments for each not meshed FACE the EDGE bounds
1146 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1147 while ( const TopoDS_Shape * anc = fIt->next() )
1149 faceNgID = occgeom.fmap.FindIndex( *anc );
1151 continue; // meshed face
1153 int faceSMDSId = meshDS->ShapeToIndex( *anc );
1154 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1155 continue; // already treated EDGE
1157 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1158 if ( face.Orientation() >= TopAbs_INTERNAL )
1159 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1161 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1162 helper.SetSubShape( face );
1163 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1164 visitedEdgeSM2Faces );
1165 if ( edges.empty() )
1166 continue; // wrong ancestor?
1168 // find out orientation of <edges> within <face>
1169 TopoDS_Edge eNotSeam = edges.front();
1170 if ( helper.HasSeam() )
1172 list< TopoDS_Edge >::iterator eIt = edges.begin();
1173 while ( helper.IsRealSeam( *eIt )) ++eIt;
1174 if ( eIt != edges.end() )
1177 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1178 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1180 // get all nodes from connected <edges>
1181 const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1182 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1183 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1184 if ( points.empty() )
1185 return false; // invalid node params?
1186 smIdType i, nbSeg = fSide.NbSegments();
1188 // remember EDGEs of fSide to treat only once
1189 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1190 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1192 double otherSeamParam = 0;
1193 bool isSeam = false;
1197 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1199 for ( i = 0; i < nbSeg; ++i )
1201 const UVPtStruct& p1 = points[ i ];
1202 const UVPtStruct& p2 = points[ i+1 ];
1204 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1207 if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1209 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1210 isSeam = helper.IsRealSeam( e );
1213 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1217 netgen::Segment seg;
1220 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1221 // node param on curve
1222 seg.epgeominfo[ 0 ].dist = p1.param;
1223 seg.epgeominfo[ 1 ].dist = p2.param;
1225 seg.epgeominfo[ 0 ].u = p1.u;
1226 seg.epgeominfo[ 0 ].v = p1.v;
1227 seg.epgeominfo[ 1 ].u = p2.u;
1228 seg.epgeominfo[ 1 ].v = p2.v;
1230 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1231 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1233 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1234 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1235 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1236 ngMesh.AddSegment (seg);
1238 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1239 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1241 #ifdef DUMP_SEGMENTS
1242 cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1243 << "\tface index: " << seg.si << endl
1244 << "\tp1: " << seg[0] << endl
1245 << "\tp2: " << seg[1] << endl
1246 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1247 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1248 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1249 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1250 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1251 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1255 if ( helper.GetPeriodicIndex() && 1 ) {
1256 seg.epgeominfo[ 0 ].u = otherSeamParam;
1257 seg.epgeominfo[ 1 ].u = otherSeamParam;
1258 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1260 seg.epgeominfo[ 0 ].v = otherSeamParam;
1261 seg.epgeominfo[ 1 ].v = otherSeamParam;
1262 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1264 swap( seg[0], seg[1] );
1265 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1266 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1267 ngMesh.AddSegment( seg );
1268 #ifdef DUMP_SEGMENTS
1269 cout << "Segment: " << seg.edgenr << endl
1270 << "\t is SEAM (reverse) of the previous. "
1271 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1272 << " = " << otherSeamParam << endl;
1275 else if ( fOri == TopAbs_INTERNAL )
1277 swap( seg[0], seg[1] );
1278 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1279 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1280 ngMesh.AddSegment( seg );
1281 #ifdef DUMP_SEGMENTS
1282 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1286 } // loop on geomEdge ancestors
1288 if ( quadHelper ) // remember medium nodes of sub-meshes
1290 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1291 while ( edges->more() )
1293 const SMDS_MeshElement* e = edges->next();
1294 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1300 } // case TopAbs_EDGE
1302 case TopAbs_FACE: { // FACE
1303 // ----------------------
1304 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1305 helper.SetSubShape( geomFace );
1306 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1308 // Find solids the geomFace bounds
1309 int solidID1 = 0, solidID2 = 0; // ng IDs
1310 int solidSMDSIDs[2] = { 0,0 }; // smds IDs
1312 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1313 while ( const TopoDS_Shape * solid = solidIt->next() )
1315 int id = occgeom.somap.FindIndex ( *solid );
1316 if ( solidID1 && id != solidID1 ) solidID2 = id;
1318 if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1321 bool isShrunk = true;
1322 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1324 // if a proxy sub-mesh contains temporary faces, then these faces
1325 // should be used to mesh only one SOLID
1326 smDS = proxyMesh->GetSubMesh( geomFace );
1327 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1328 while ( faces->more() )
1330 const SMDS_MeshElement* f = faces->next();
1331 if ( proxyMesh->IsTemporary( f ))
1334 if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1337 solidSMDSIDs[1] = 0;
1338 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1339 std::vector<const SMDS_MeshElement*> vols;
1340 if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1342 int geomID = vols[0]->GetShapeID();
1343 const TopoDS_Shape& solid = meshDS->IndexToShape( geomID );
1344 if ( !solid.IsNull() )
1345 solidID1 = occgeom.somap.FindIndex ( solid );
1351 const int fID = occgeom.fmap.FindIndex( geomFace );
1352 if ( isShrunk ) // shrunk mesh
1354 // move netgen points according to moved nodes
1355 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1356 while ( smIt->more() )
1358 SMESH_subMesh* sub = smIt->next();
1359 if ( !sub->GetSubMeshDS() ) continue;
1360 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1361 while ( nodeIt->more() )
1363 const SMDS_MeshNode* n = nodeIt->next();
1364 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1365 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1366 ngPoint(0) = n->X();
1367 ngPoint(1) = n->Y();
1368 ngPoint(2) = n->Z();
1371 // remove faces near boundary to avoid their overlapping
1372 // with shrunk faces
1373 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1375 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1376 if ( elem.GetIndex() == fID )
1378 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1379 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1381 ngMesh.DeleteSurfaceElement( i );
1387 // exclude faces generated by NETGEN from computation of 3D mesh
1391 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1392 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1394 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1395 if ( elem.GetIndex() == fID )
1396 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1402 solidSMDSIDs[1] = 0;
1404 const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 && !isShrunk );
1406 // Add ng face descriptors of meshed faces
1408 if ( hasVLOn2Sides )
1410 // viscous layers are on two sides of the FACE
1411 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1413 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1417 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1419 // if second oreder is required, even already meshed faces must be passed to NETGEN
1420 int fID = occgeom.fmap.Add( geomFace );
1421 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1422 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1423 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1425 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1426 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1427 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1429 // Problem with the second order in a quadrangular mesh remains.
1430 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1431 // by FillSMesh() (find "AddFaceDescriptor")
1432 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1433 // are on faces where quadrangles were.
1434 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1435 // of the mentioned above quadrangles and triangles
1437 // Orient the face correctly in solidID1 (issue 0020206)
1438 bool reverse = false;
1440 TopoDS_Shape solid = occgeom.somap( solidID1 );
1441 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1442 if ( faceOriInSolid >= 0 )
1444 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1447 // Add surface elements
1449 netgen::Element2d tri(3);
1450 tri.SetIndex( faceNgID );
1451 SMESH_TNodeXYZ xyz[3];
1453 #ifdef DUMP_TRIANGLES
1454 cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1455 << " internal="<<isInternalFace << endl;
1458 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1459 while ( faces->more() )
1461 const SMDS_MeshElement* f = faces->next();
1462 if ( f->NbNodes() % 3 != 0 ) // not triangle
1464 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace,*sm->GetFather(),TopAbs_SOLID);
1465 if ( const TopoDS_Shape * solid = solidIt->next() )
1466 sm = _mesh->GetSubMesh( *solid );
1467 SMESH_BadInputElements* badElems =
1468 new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1470 sm->GetComputeError().reset( badElems );
1474 if ( hasVLOn2Sides )
1475 tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1477 for ( int i = 0; i < 3; ++i )
1479 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1482 // get node UV on face
1483 int shapeID = node->GetShapeID();
1484 if ( helper.IsSeamShape( shapeID ))
1486 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1487 inFaceNode = f->GetNodeWrap( i-1 );
1489 inFaceNode = f->GetNodeWrap( i+1 );
1491 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1493 int ind = reverse ? 3-i : i+1;
1494 tri.GeomInfoPi(ind).u = uv.X();
1495 tri.GeomInfoPi(ind).v = uv.Y();
1496 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1499 // pass a triangle size to NG size-map
1500 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1501 ( xyz[1] - xyz[2] ).Modulus() +
1502 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1503 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1504 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1506 ngMesh.AddSurfaceElement (tri);
1507 #ifdef DUMP_TRIANGLES
1508 cout << tri << endl;
1511 if ( isInternalFace )
1513 swap( tri[1], tri[2] );
1514 ngMesh.AddSurfaceElement (tri);
1515 #ifdef DUMP_TRIANGLES
1516 cout << tri << endl;
1519 } // loop on sub-mesh faces
1521 if ( quadHelper ) // remember medium nodes of sub-meshes
1523 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1524 while ( faces->more() )
1526 const SMDS_MeshElement* f = faces->next();
1527 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1533 } // case TopAbs_FACE
1535 case TopAbs_VERTEX: { // VERTEX
1536 // --------------------------
1537 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1538 // else netgen removes a free node and nodeVector becomes invalid
1539 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1543 while ( const TopoDS_Shape* e = ansIt->next() )
1545 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1546 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1551 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1552 if ( nodeIt->more() )
1553 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1559 } // loop on submeshes
1562 nodeVec.resize( ngMesh.GetNP() + 1 );
1563 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1564 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1565 nodeVec[ node_NgId->second ] = node_NgId->first;
1570 //================================================================================
1572 * \brief Duplicate mesh faces on internal geom faces
1574 //================================================================================
1576 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1577 netgen::Mesh& ngMesh,
1578 NETGENPlugin_Internals& internalShapes)
1580 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1582 // find ng indices of internal faces
1584 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1586 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1587 if ( internalShapes.isInternalShape( smeshID ))
1588 ngFaceIds.insert( ngFaceID );
1590 if ( !ngFaceIds.empty() )
1593 int i, nbFaces = ngMesh.GetNSE();
1594 for ( i = 1; i <= nbFaces; ++i)
1596 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1597 if ( ngFaceIds.count( elem.GetIndex() ))
1599 swap( elem[1], elem[2] );
1600 ngMesh.AddSurfaceElement (elem);
1606 //================================================================================
1608 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1609 * meshed due to NETGEN failure
1610 * \param [in] occgeom - geometry
1611 * \param [in,out] ngMesh - the mesh to fix
1612 * \param [inout] faceID - ID of the FACE to fix the mesh on
1613 * \return bool - is mesh is or becomes OK
1615 //================================================================================
1617 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1618 netgen::Mesh& ngMesh,
1621 // we address a case where the FACE is almost fully meshed except small holes
1622 // of usually triangular shape at FACE boundary (IPAL52861)
1624 // The case appeared to be not simple: holes only look triangular but
1625 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1626 // NG points on a seam edge. But the code below is very nice, leave it for
1631 if ( occgeom.fmap.Extent() < faceID )
1633 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1635 // find free links on the FACE
1637 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1639 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1640 if ( faceID != elem.GetIndex() )
1642 int n0 = elem[ elem.GetNP() - 1 ];
1643 for ( int i = 0; i < elem.GetNP(); ++i )
1646 Link link( n0, n1 );
1647 if ( !linkMap.Add( link ))
1648 linkMap.Remove( link );
1652 // add/remove boundary links
1653 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1655 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1656 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1658 Link link( seg[1], seg[0] ); // reverse!!!
1659 if ( !linkMap.Add( link ))
1660 linkMap.Remove( link );
1662 if ( linkMap.IsEmpty() )
1664 if ( linkMap.Extent() < 3 )
1667 // make triangles of the links
1669 netgen::Element2d tri(3);
1670 tri.SetIndex ( faceID );
1672 TLinkMap::Iterator linkIt( linkMap );
1673 Link link1 = linkIt.Value();
1674 // look for a link connected to link1
1675 TLinkMap::Iterator linkIt2 = linkIt;
1676 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1678 const Link& link2 = linkIt2.Value();
1679 if ( link2.IsConnected( link1 ))
1681 // look for a link connected to both link1 and link2
1682 TLinkMap::Iterator linkIt3 = linkIt2;
1683 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1685 const Link& link3 = linkIt3.Value();
1686 if ( link3.IsConnected( link1 ) &&
1687 link3.IsConnected( link2 ) )
1692 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1693 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1695 ngMesh.AddSurfaceElement( tri );
1697 // prepare for the next tria search
1698 if ( linkMap.Extent() == 3 )
1700 linkMap.Remove( link3 );
1701 linkMap.Remove( link2 );
1703 linkMap.Remove( link1 );
1704 link1 = linkIt.Value();
1717 //================================================================================
1718 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1719 gp_XY_FunPtr(Subtracted);
1720 //gp_XY_FunPtr(Added);
1722 //================================================================================
1724 * \brief Evaluate distance between two 2d points along the surface
1726 //================================================================================
1728 double evalDist( const gp_XY& uv1,
1730 const Handle(Geom_Surface)& surf,
1731 const int stopHandler=-1)
1733 if ( stopHandler > 0 ) // continue recursion
1735 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1736 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1738 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1739 if ( stopHandler == 0 ) // stop recursion
1742 // start recursion if necessary
1743 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1744 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1745 return dist3D; // equal parametrization of a planar surface
1747 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1750 //================================================================================
1752 * \brief Data of vertex internal in geom face
1754 //================================================================================
1758 gp_XY uv; //!< UV in face parametric space
1759 int ngId; //!< ng id of corresponding node
1760 gp_XY uvClose; //!< UV of closest boundary node
1761 int ngIdClose; //!< ng id of closest boundary node
1764 //================================================================================
1766 * \brief Data of vertex internal in solid
1768 //================================================================================
1772 int ngId; //!< ng id of corresponding node
1773 int ngIdClose; //!< ng id of closest 2d mesh element
1774 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1777 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1779 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1782 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1784 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1788 //================================================================================
1790 * \brief Make netgen take internal vertices in faces into account by adding
1791 * segments including internal vertices
1793 * This function works in supposition that 1D mesh is already computed in ngMesh
1795 //================================================================================
1797 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1798 netgen::Mesh& ngMesh,
1799 vector<const SMDS_MeshNode*>& nodeVec,
1800 NETGENPlugin_Internals& internalShapes)
1802 if ((int) nodeVec.size() < ngMesh.GetNP() )
1803 nodeVec.resize( ngMesh.GetNP(), 0 );
1805 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1806 SMESH_MesherHelper helper( internalShapes.getMesh() );
1808 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1809 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1810 for ( ; f2v != face2Vert.end(); ++f2v )
1812 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1813 if ( face.IsNull() ) continue;
1814 int faceNgID = occgeom.fmap.FindIndex (face);
1815 if ( faceNgID < 0 ) continue;
1817 TopLoc_Location loc;
1818 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1820 helper.SetSubShape( face );
1821 helper.SetElementsOnShape( true );
1823 // Get data of internal vertices and add them to ngMesh
1825 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1827 int i, nbSegInit = ngMesh.GetNSeg();
1829 // boundary characteristics
1830 double totSegLen2D = 0;
1833 const list<int>& iVertices = f2v->second;
1834 list<int>::const_iterator iv = iVertices.begin();
1835 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1838 // get node on vertex
1839 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1840 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1843 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1844 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1845 nV = SMESH_Algo::VertexNode( V, meshDS );
1846 if ( !nV ) continue;
1849 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1850 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1851 vData.ngId = ngMesh.GetNP();
1852 nodeVec.push_back( nV );
1856 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1857 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1859 // loop on all segments of the face to find the node closest to vertex and to count
1860 // average segment 2d length
1861 double closeDist2 = numeric_limits<double>::max(), dist2;
1863 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1865 netgen::Segment & seg = ngMesh.LineSegment(i);
1866 if ( seg.si != faceNgID ) continue;
1868 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1870 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1871 if ( ngIdLast == seg[ iEnd ] ) continue;
1872 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1873 if ( dist2 < closeDist2 )
1874 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1875 ngIdLast = seg[ iEnd ];
1879 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1883 dist2VData.insert( make_pair( closeDist2, vData ));
1886 if ( totNbSeg == 0 ) break;
1887 double avgSegLen2d = totSegLen2D / totNbSeg;
1889 // Loop on vertices to add segments
1891 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1892 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1894 double closeDist2 = dist_vData->first, dist2;
1895 TIntVData & vData = dist_vData->second;
1897 // try to find more close node among segments added for internal vertices
1898 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1900 netgen::Segment & seg = ngMesh.LineSegment(i);
1901 if ( seg.si != faceNgID ) continue;
1903 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1905 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1906 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1907 if ( dist2 < closeDist2 )
1908 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1911 // decide whether to use the closest node as the second end of segment or to
1912 // create a new point
1913 int segEnd1 = vData.ngId;
1914 int segEnd2 = vData.ngIdClose; // to use closest node
1915 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1916 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1917 double nodeDist2D = sqrt( closeDist2 );
1918 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1919 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1920 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1921 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1922 if ( hintLenOK || avgLenOK )
1924 // create a point between the closest node and V
1927 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1928 // direction from V to closet node in 2D
1929 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1931 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1932 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1934 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1935 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1936 segEnd2 = ngMesh.GetNP();
1937 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1938 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1939 nodeVec.push_back( nP );
1941 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1944 netgen::Segment seg;
1946 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1947 seg[0] = segEnd1; // ng node id
1948 seg[1] = segEnd2; // ng node id
1949 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1952 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1953 seg.epgeominfo[ 0 ].u = uvV.X();
1954 seg.epgeominfo[ 0 ].v = uvV.Y();
1955 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1956 seg.epgeominfo[ 1 ].u = uvP.X();
1957 seg.epgeominfo[ 1 ].v = uvP.Y();
1959 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1960 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1962 ngMesh.AddSegment (seg);
1964 // add reverse segment
1965 swap( seg[0], seg[1] );
1966 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1967 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1968 ngMesh.AddSegment (seg);
1972 ngMesh.CalcSurfacesOfNode();
1975 //================================================================================
1977 * \brief Make netgen take internal vertices in solids into account by adding
1978 * faces including internal vertices
1980 * This function works in supposition that 2D mesh is already computed in ngMesh
1982 //================================================================================
1984 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1985 netgen::Mesh& ngMesh,
1986 vector<const SMDS_MeshNode*>& nodeVec,
1987 NETGENPlugin_Internals& internalShapes)
1989 #ifdef DUMP_TRIANGLES_SCRIPT
1990 // create a python script making a mesh containing triangles added for internal vertices
1991 ofstream py(DUMP_TRIANGLES_SCRIPT);
1992 py << "import SMESH"<< endl
1993 << "from salome.smesh import smeshBuilder"<<endl
1994 << "smesh = smeshBuilder.New()"<<endl
1995 << "m = smesh.Mesh(name='triangles')" << endl;
1997 if ((int) nodeVec.size() < ngMesh.GetNP() )
1998 nodeVec.resize( ngMesh.GetNP(), 0 );
2000 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
2001 SMESH_MesherHelper helper( internalShapes.getMesh() );
2003 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
2004 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
2005 for ( ; s2v != so2Vert.end(); ++s2v )
2007 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
2008 if ( solid.IsNull() ) continue;
2009 int solidNgID = occgeom.somap.FindIndex (solid);
2010 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
2012 helper.SetSubShape( solid );
2013 helper.SetElementsOnShape( true );
2015 // find ng indices of faces within the solid
2017 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
2018 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
2019 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
2020 ngFaceIds.insert( 1 );
2022 // Get data of internal vertices and add them to ngMesh
2024 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
2026 int i, nbFaceInit = ngMesh.GetNSE();
2028 // boundary characteristics
2029 double totSegLen = 0;
2032 const list<int>& iVertices = s2v->second;
2033 list<int>::const_iterator iv = iVertices.begin();
2034 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2037 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2039 // get node on vertex
2040 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2043 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2044 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2045 nV = SMESH_Algo::VertexNode( V, meshDS );
2046 if ( !nV ) continue;
2049 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2050 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2051 vData.ngId = ngMesh.GetNP();
2052 nodeVec.push_back( nV );
2054 // loop on all 2d elements to find the one closest to vertex and to count
2055 // average segment length
2056 double closeDist2 = numeric_limits<double>::max(), avgDist2;
2057 for (i = 1; i <= ngMesh.GetNSE(); ++i)
2059 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2060 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2062 multimap< double, int> dist2nID; // sort nodes of element by distance from V
2063 for ( int j = 0; j < elem.GetNP(); ++j)
2065 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2066 double d2 = dist2( mpV, mp );
2067 dist2nID.insert( make_pair( d2, elem[j] ));
2068 avgDist2 += d2 / elem.GetNP();
2070 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2072 double dist = dist2nID.begin()->first; //avgDist2;
2073 if ( dist < closeDist2 )
2074 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2076 dist2VData.insert( make_pair( closeDist2, vData ));
2079 if ( totNbSeg == 0 ) break;
2080 double avgSegLen = totSegLen / totNbSeg;
2082 // Loop on vertices to add triangles
2084 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2085 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2087 double closeDist2 = dist_vData->first;
2088 TIntVSoData & vData = dist_vData->second;
2090 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2092 // try to find more close face among ones added for internal vertices
2093 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2095 double avgDist2 = 0;
2096 multimap< double, int> dist2nID;
2097 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2098 for ( int j = 0; j < elem.GetNP(); ++j)
2100 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2101 dist2nID.insert( make_pair( d, elem[j] ));
2102 avgDist2 += d / elem.GetNP();
2103 if ( avgDist2 < closeDist2 )
2104 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2107 // sort nodes of the closest face by angle with vector from V to the closest node
2108 const double tol = numeric_limits<double>::min();
2109 map< double, int > angle2ID;
2110 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2111 netgen::MeshPoint mp[2];
2112 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2113 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2114 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2115 gp_Vec v2p1( pV, p1 );
2116 double distN1 = v2p1.Magnitude();
2117 if ( distN1 <= tol ) continue;
2119 for ( int j = 0; j < closeFace.GetNP(); ++j)
2121 mp[1] = ngMesh.Point( closeFace[j] );
2122 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2123 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2125 // get node with angle of 60 degrees or greater
2126 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2127 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2128 const double minAngle = 30. * M_PI / 180.;
2129 const double angle = angle_id->first;
2130 bool angleOK = ( angle > minAngle );
2132 // find points to create a triangle
2133 netgen::Element2d tri(3);
2135 tri[0] = vData.ngId;
2136 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2137 tri[2] = angle_id->second; // to use the node with best angle
2139 // decide whether to use the closest node and the node with best angle or to create new ones
2140 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2142 bool createNew = !angleOK; //, distOK = true;
2144 int triInd = isBestAngleN ? 2 : 1;
2145 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2150 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2151 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2153 else if ( angle < tol )
2155 v2p1.SetX( v2p1.X() + 1e-3 );
2161 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2162 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2163 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2164 createNew = (createNew || avgLenOK || hintLenOK );
2165 // we create a new node not closer than 0.5 to the closest face
2166 // in order not to clash with other close face
2167 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2168 distFromV = r * distN1;
2172 // create a new point, between the node and the vertex if angleOK
2173 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2174 gp_Vec v2p( pV, p ); v2p.Normalize();
2175 if ( isBestAngleN && !angleOK )
2176 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2178 p = pV + v2p.XYZ() * distFromV;
2180 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2182 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2183 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2184 tri[triInd] = ngMesh.GetNP();
2185 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2188 ngMesh.AddSurfaceElement (tri);
2189 swap( tri[1], tri[2] );
2190 ngMesh.AddSurfaceElement (tri);
2192 #ifdef DUMP_TRIANGLES_SCRIPT
2193 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2194 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2195 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2196 << "m.AddFace([n1,n2,n3])" << endl;
2198 } // loop on internal vertices of a solid
2200 } // loop on solids with internal vertices
2203 //================================================================================
2205 * \brief Fill netgen mesh with segments of a FACE
2206 * \param ngMesh - netgen mesh
2207 * \param geom - container of OCCT geometry to mesh
2208 * \param wires - data of nodes on FACE boundary
2209 * \param helper - mesher helper holding the FACE
2210 * \param nodeVec - vector of nodes in which node index == netgen ID
2211 * \retval SMESH_ComputeErrorPtr - error description
2213 //================================================================================
2215 SMESH_ComputeErrorPtr
2216 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2217 netgen::OCCGeometry& geom,
2218 const TSideVector& wires,
2219 SMESH_MesherHelper& helper,
2220 vector< const SMDS_MeshNode* > & nodeVec,
2221 const bool overrideMinH)
2223 // ----------------------------
2224 // Check wires and count nodes
2225 // ----------------------------
2226 smIdType nbNodes = 0;
2227 for ( size_t iW = 0; iW < wires.size(); ++iW )
2229 StdMeshers_FaceSidePtr wire = wires[ iW ];
2230 if ( wire->MissVertexNode() )
2232 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2233 // It seems that there is no reason for this limitation
2235 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2237 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2238 if ((int) uvPtVec.size() != wire->NbPoints() )
2239 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2240 SMESH_Comment("Unexpected nb of points on wire ") << iW
2241 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2242 nbNodes += wire->NbPoints();
2244 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2245 if ( nodeVec.empty() )
2246 nodeVec.push_back( 0 );
2248 // -----------------
2250 // -----------------
2252 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2253 NETGENPlugin_NETGEN_2D_ONLY */
2255 // map for nodes on vertices since they can be shared between wires
2256 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2257 map<const SMDS_MeshNode*, int > node2ngID;
2258 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2260 set< int > subIDs; // ids of sub-shapes of the FACE
2261 for ( size_t iW = 0; iW < wires.size(); ++iW )
2263 StdMeshers_FaceSidePtr wire = wires[ iW ];
2264 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2266 subIDs.insert( wire->EdgeID( iE ));
2267 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2270 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2271 if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2272 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2275 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2276 if ( ngMesh.GetNFD() < 1 )
2277 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2279 for ( size_t iW = 0; iW < wires.size(); ++iW )
2281 StdMeshers_FaceSidePtr wire = wires[ iW ];
2282 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2283 const smIdType nbSegments = wire->NbPoints() - 1;
2285 // assure the 1st node to be in node2ngID, which is needed to correctly
2286 // "close chain of segments" (see below) in case if the 1st node is not
2287 // onVertex because it is on a Viscous layer
2288 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2290 // compute length of every segment
2291 vector<double> segLen( nbSegments );
2292 for ( int i = 0; i < nbSegments; ++i )
2293 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2295 int edgeID = 1, posID = -2;
2296 bool isInternalWire = false;
2297 double vertexNormPar = 0;
2298 const int prevNbNGSeg = ngMesh.GetNSeg();
2299 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2301 // Add the first point of a segment
2303 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2304 const int posShapeID = n->GetShapeID();
2305 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2306 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2308 // skip nodes on degenerated edges
2309 if ( helper.IsDegenShape( posShapeID ) &&
2310 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2313 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2314 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2315 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2316 if ( ngID1 > ngMesh.GetNP() )
2318 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2319 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2320 nodeVec.push_back( n );
2322 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2324 ngID2 = ngMesh.GetNP() + 1;
2325 if ( i > 0 ) // prev segment belongs to same wire
2327 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2334 netgen::Segment seg;
2336 seg[0] = ngID1; // ng node id
2337 seg[1] = ngID2; // ng node id
2338 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2339 seg.si = faceID; // = geom.fmap.FindIndex (face);
2341 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2343 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2345 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2346 seg.epgeominfo[ iEnd ].u = pnt.u;
2347 seg.epgeominfo[ iEnd ].v = pnt.v;
2349 // find out edge id and node parameter on edge
2350 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2351 if ( onVertex || posShapeID != posID )
2354 double normParam = pnt.normParam;
2356 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2357 int edgeIndexInWire = wire->EdgeIndex( normParam );
2358 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2359 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2360 edgeID = geom.emap.FindIndex( edge );
2362 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2363 // if ( onVertex ) // param on curve is different on each of two edges
2364 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2366 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2369 ngMesh.AddSegment (seg);
2371 // restrict size of elements near the segment
2372 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2373 // get an average size of adjacent segments to avoid sharp change of
2374 // element size (regression on issue 0020452, note 0010898)
2375 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
2376 int iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
2377 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2378 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2379 int( segLen[ i ] > sumH / 100.) +
2380 int( segLen[ iNext ] > sumH / 100.));
2382 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2384 if ( isInternalWire )
2386 swap (seg[0], seg[1]);
2387 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2388 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2389 ngMesh.AddSegment (seg);
2391 } // loop on segments on a wire
2393 // close chain of segments
2394 if ( nbSegments > 0 )
2396 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2397 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2398 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2399 if ( lastSeg[1] > ngMesh.GetNP() )
2401 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2402 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2403 nodeVec.push_back( lastNode );
2405 if ( isInternalWire )
2407 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2408 realLastSeg[0] = lastSeg[1];
2412 #ifdef DUMP_SEGMENTS
2413 cout << "BEGIN WIRE " << iW << endl;
2414 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2416 netgen::Segment& seg = ngMesh.LineSegment( i );
2418 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2419 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2421 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2425 cout << "Segment: " << seg.edgenr << endl
2426 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2427 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2428 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2429 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2430 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2431 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2432 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2433 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2435 cout << "--END WIRE " << iW << endl;
2437 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2440 } // loop on WIREs of a FACE
2442 // add a segment instead of an internal vertex
2443 if ( wasNgMeshEmpty )
2445 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2446 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2448 ngMesh.CalcSurfacesOfNode();
2453 //================================================================================
2455 * \brief Fill SMESH mesh according to contents of netgen mesh
2456 * \param occgeo - container of OCCT geometry to mesh
2457 * \param ngMesh - netgen mesh
2458 * \param initState - bn of entities in netgen mesh before computing
2459 * \param sMesh - SMESH mesh to fill in
2460 * \param nodeVec - vector of nodes in which node index == netgen ID
2461 * \param comment - returns problem description
2462 * \param quadHelper - holder of medium nodes of sub-meshes
2463 * \retval int - error
2465 //================================================================================
2467 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2468 netgen::Mesh& ngMesh,
2469 const NETGENPlugin_ngMeshInfo& initState,
2471 std::vector<const SMDS_MeshNode*>& nodeVec,
2472 SMESH_Comment& comment,
2473 SMESH_MesherHelper* quadHelper)
2475 int nbNod = ngMesh.GetNP();
2476 int nbSeg = ngMesh.GetNSeg();
2477 int nbFac = ngMesh.GetNSE();
2478 int nbVol = ngMesh.GetNE();
2480 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2482 // quadHelper is used for either
2483 // 1) making quadratic elements when a lower dimension mesh is loaded
2484 // to SMESH before conversion to quadratic by NETGEN
2485 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2486 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2489 int ngID, nbInitNod = initState._nbNodes;
2490 if ( initState._elementsRemoved )
2492 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2493 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2494 size_t i, nodeVecSize = nodeVec.size();
2495 const double eps = std::numeric_limits<double>::min();
2496 for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
2498 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2499 gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2500 if ( ngPnt.SquareDistance( node ) < eps )
2502 nodeVec[ ngID ] = nodeVec[ i ];
2509 nodeVec.resize( ngID );
2510 nbInitNod = ngID - 1;
2512 // -------------------------------------
2513 // Create and insert nodes into nodeVec
2514 // -------------------------------------
2516 if ( nbNod > nbInitNod )
2517 nodeVec.resize( nbNod + 1 );
2518 for ( int i = nbInitNod+1; i <= nbNod; ++i )
2520 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2521 SMDS_MeshNode* node = NULL;
2522 TopoDS_Vertex aVert;
2523 // First, netgen creates nodes on vertices in occgeo.vmap,
2524 // so node index corresponds to vertex index
2525 // but (issue 0020776) netgen does not create nodes with equal coordinates
2526 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2528 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2529 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2531 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2532 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2533 if ( p.SquareDistance( pV ) > 1e-20 )
2536 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2539 if (!node) // node not found on vertex
2541 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2542 if (!aVert.IsNull())
2543 meshDS->SetNodeOnVertex(node, aVert);
2548 // -------------------------------------------
2549 // Create mesh segments along geometric edges
2550 // -------------------------------------------
2552 int nbInitSeg = initState._nbSegments;
2553 for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
2555 const netgen::Segment& seg = ngMesh.LineSegment(i);
2557 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2560 for (int j=0; j < 3; ++j)
2562 int pind = pinds[j];
2563 if (pind <= 0 || !nodeVec_ACCESS(pind))
2571 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2572 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2573 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2575 param = seg.epgeominfo[j].dist;
2578 else // middle point
2580 param = param2 * 0.5;
2582 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2584 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2589 SMDS_MeshEdge* edge = 0;
2590 if (nbp == 2) // second order ?
2592 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2594 if ( quadHelper ) // final mesh must be quadratic
2595 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2597 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2601 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2602 nodeVec_ACCESS(pinds[2])))
2604 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2605 nodeVec_ACCESS(pinds[2]));
2609 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2610 MESSAGE("Cannot create a mesh edge");
2611 nbSeg = nbFac = nbVol = 0;
2614 if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2615 meshDS->SetMeshElementOnShape(edge, aEdge);
2617 else if ( comment.empty() )
2619 comment << "Invalid netgen segment #" << i;
2623 // ----------------------------------------
2624 // Create mesh faces along geometric faces
2625 // ----------------------------------------
2627 int nbInitFac = initState._nbFaces;
2628 int quadFaceID = ngMesh.GetNFD() + 1;
2629 if ( nbInitFac < nbFac )
2630 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2631 // from computation of 3D mesh
2632 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2634 vector<const SMDS_MeshNode*> nodes;
2635 for ( int i = nbInitFac+1; i <= nbFac; ++i )
2637 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2638 const int aGeomFaceInd = elem.GetIndex();
2640 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2641 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2643 for ( int j = 1; j <= elem.GetNP(); ++j )
2645 int pind = elem.PNum(j);
2646 if ( pind < 1 || pind >= (int) nodeVec.size() )
2648 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2650 nodes.push_back( node );
2651 if (!aFace.IsNull() && node->GetShapeID() < 1)
2653 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2654 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2658 if ((int) nodes.size() != elem.GetNP() )
2660 if ( comment.empty() )
2661 comment << "Invalid netgen 2d element #" << i;
2662 continue; // bad node ids
2664 SMDS_MeshFace* face = NULL;
2665 switch (elem.GetType())
2668 if ( quadHelper ) // final mesh must be quadratic
2669 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2671 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2674 if ( quadHelper ) // final mesh must be quadratic
2675 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2677 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2678 // exclude qudrangle elements from computation of 3D mesh
2679 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2682 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2683 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2684 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2685 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2688 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2689 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2690 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2691 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2692 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2693 nodes[4],nodes[7],nodes[5],nodes[6]);
2694 // exclude qudrangle elements from computation of 3D mesh
2695 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2698 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2703 if ( comment.empty() ) comment << "Cannot create a mesh face";
2704 MESSAGE("Cannot create a mesh face");
2705 nbSeg = nbFac = nbVol = 0;
2708 if ( !aFace.IsNull() )
2709 meshDS->SetMeshElementOnShape( face, aFace );
2712 // ------------------
2713 // Create tetrahedra
2714 // ------------------
2716 for ( int i = 1; i <= nbVol; ++i )
2718 const netgen::Element& elem = ngMesh.VolumeElement(i);
2719 int aSolidInd = elem.GetIndex();
2720 TopoDS_Solid aSolid;
2721 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2722 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2724 for ( int j = 1; j <= elem.GetNP(); ++j )
2726 int pind = elem.PNum(j);
2727 if ( pind < 1 || pind >= (int)nodeVec.size() )
2729 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2731 nodes.push_back(node);
2732 if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2733 meshDS->SetNodeInVolume(node, aSolid);
2736 if ((int) nodes.size() != elem.GetNP() )
2738 if ( comment.empty() )
2739 comment << "Invalid netgen 3d element #" << i;
2742 SMDS_MeshVolume* vol = NULL;
2743 switch ( elem.GetType() )
2746 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2749 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2750 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2751 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2752 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2753 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2754 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2755 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2756 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2759 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2764 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2765 MESSAGE("Cannot create a mesh volume");
2766 nbSeg = nbFac = nbVol = 0;
2769 if (!aSolid.IsNull())
2770 meshDS->SetMeshElementOnShape(vol, aSolid);
2772 return comment.empty() ? 0 : 1;
2777 //================================================================================
2779 * \brief Convert error into text
2781 //================================================================================
2783 std::string text(int err)
2788 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2791 //================================================================================
2793 * \brief Convert exception into text
2795 //================================================================================
2797 std::string text(Standard_Failure& ex)
2799 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2800 str << " at " << netgen::multithread.task
2801 << ": " << ex.DynamicType()->Name();
2802 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2803 str << ": " << ex.GetMessageString();
2806 //================================================================================
2808 * \brief Convert exception into text
2810 //================================================================================
2812 std::string text(netgen::NgException& ex)
2814 SMESH_Comment str("NgException");
2815 if ( strlen( netgen::multithread.task ) > 0 )
2816 str << " at " << netgen::multithread.task;
2817 str << ": " << ex.What();
2821 //================================================================================
2823 * \brief Looks for triangles lying on a SOLID
2825 //================================================================================
2827 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2828 SMESH_subMesh* solidSM )
2830 TopTools_IndexedMapOfShape solidSubs;
2831 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2832 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2834 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2835 for ( ; e != elems.end(); ++e )
2837 const SMDS_MeshElement* elem = *e;
2838 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2840 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2841 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2842 while ( nIt->more() )
2844 const SMDS_MeshNode* n = nIt->next();
2845 const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() );
2846 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2847 if ( nbNodesOnSolid > 2 ||
2848 nbNodesOnSolid == nbNodes)
2855 const double edgeMeshingTime = 0.001;
2856 const double faceMeshingTime = 0.019;
2857 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2858 const double faceOptimizTime = 0.06;
2859 const double voluMeshingTime = 0.15;
2860 const double volOptimizeTime = 0.77;
2863 //=============================================================================
2865 * Here we are going to use the NETGEN mesher
2867 //=============================================================================
2869 bool NETGENPlugin_Mesher::Compute()
2871 NETGENPlugin_NetgenLibWrapper ngLib;
2873 netgen::MeshingParameters& mparams = netgen::mparam;
2875 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2876 SMESH_MesherHelper quadHelper( *_mesh );
2877 quadHelper.SetIsQuadratic( mparams.secondorder );
2879 // -------------------------
2880 // Prepare OCC geometry
2881 // -------------------------
2883 netgen::OCCGeometry occgeo;
2884 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2885 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2886 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2889 _totalTime = edgeFaceMeshingTime;
2891 _totalTime += faceOptimizTime;
2893 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2894 double doneTime = 0;
2897 _curShapeIndex = -1;
2899 // -------------------------
2900 // Generate the mesh
2901 // -------------------------
2904 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2906 SMESH_Comment comment;
2909 // vector of nodes in which node index == netgen ID
2910 vector< const SMDS_MeshNode* > nodeVec;
2918 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2919 mparams.uselocalh = false;
2920 mparams.grading = 0.8; // not limitited size growth
2922 if ( _simpleHyp->GetNumberOfSegments() )
2924 mparams.maxh = occgeo.boundingbox.Diam();
2927 mparams.maxh = _simpleHyp->GetLocalLength();
2930 if ( mparams.maxh == 0.0 )
2931 mparams.maxh = occgeo.boundingbox.Diam();
2932 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2933 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2935 // Local size on faces
2936 occgeo.face_maxh = mparams.maxh;
2938 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2939 int startWith = netgen::MESHCONST_ANALYSE;
2940 int endWith = netgen::MESHCONST_ANALYSE;
2945 err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
2947 if(netgen::multithread.terminate)
2950 comment << text(err);
2952 catch (Standard_Failure& ex)
2954 comment << text(ex);
2956 catch (netgen::NgException & ex)
2958 comment << text(ex);
2960 bool hasSizeFile = !mparams.meshsizefilename.empty();
2962 bool hasSizeFile = mparams.meshsizefilename;
2965 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2967 err = 0; //- MESHCONST_ANALYSE isn't so important step
2970 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2972 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2974 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2975 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2979 // Pass 1D simple parameters to NETGEN
2980 // --------------------------------
2981 double nbSeg = (double) _simpleHyp->GetNumberOfSegments();
2982 double segSize = _simpleHyp->GetLocalLength();
2983 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2985 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2987 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2988 setLocalSize( e, segSize, *_ngMesh );
2991 else // if ( ! _simpleHyp )
2993 // Local size on shapes
2994 SetLocalSize( occgeo, *_ngMesh );
2995 SetLocalSizeForChordalError( occgeo, *_ngMesh );
2998 // Precompute internal edges (issue 0020676) in order to
2999 // add mesh on them correctly (twice) to netgen mesh
3000 if ( !err && internals.hasInternalEdges() )
3002 // load internal shapes into OCCGeometry
3003 netgen::OCCGeometry intOccgeo;
3004 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
3005 intOccgeo.boundingbox = occgeo.boundingbox;
3006 intOccgeo.shape = occgeo.shape;
3007 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
3008 intOccgeo.face_maxh = netgen::mparam.maxh;
3009 netgen::Mesh *tmpNgMesh = NULL;
3013 // compute local H on internal shapes in the main mesh
3014 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
3016 // let netgen create a temporary mesh
3017 ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3019 if ( netgen::multithread.terminate )
3022 // copy LocalH from the main to temporary mesh
3023 initState.transferLocalH( _ngMesh, tmpNgMesh );
3025 // compute mesh on internal edges
3026 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3027 err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3029 comment << text(err);
3031 catch (Standard_Failure& ex)
3033 comment << text(ex);
3036 initState.restoreLocalH( tmpNgMesh );
3038 // fill SMESH by netgen mesh
3039 vector< const SMDS_MeshNode* > tmpNodeVec;
3040 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3041 err = ( err || !comment.empty() );
3043 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3046 // Fill _ngMesh with nodes and segments of computed submeshes
3049 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3050 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3052 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3057 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3062 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3064 if ( netgen::multithread.terminate )
3067 comment << text(err);
3069 catch (Standard_Failure& ex)
3071 comment << text(ex);
3076 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3078 mparams.uselocalh = true; // restore as it is used at surface optimization
3080 // ---------------------
3081 // compute surface mesh
3082 // ---------------------
3085 // Pass 2D simple parameters to NETGEN
3087 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3089 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3090 mparams.grading = 0.4; // moderate size growth
3093 // length from edges
3094 if ( _ngMesh->GetNSeg() ) {
3095 double edgeLength = 0;
3096 TopTools_MapOfShape visitedEdges;
3097 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3098 if( visitedEdges.Add(exp.Current()) )
3099 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3100 // we have to multiply length by 2 since for each TopoDS_Edge there
3101 // are double set of NETGEN edges, in other words, we have to
3102 // divide _ngMesh->GetNSeg() by 2.
3103 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3106 mparams.maxh = 1000;
3108 mparams.grading = 0.2; // slow size growth
3110 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3111 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3112 _ngMesh->SetGlobalH (mparams.maxh);
3113 netgen::Box<3> bb = occgeo.GetBoundingBox();
3114 bb.Increase (bb.Diam()/20);
3115 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3118 // Care of vertices internal in faces (issue 0020676)
3119 if ( internals.hasInternalVertexInFace() )
3121 // store computed segments in SMESH in order not to create SMESH
3122 // edges for ng segments added by AddIntVerticesInFaces()
3123 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3124 // add segments to faces with internal vertices
3125 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3126 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3129 // Build viscous layers
3130 if (( _isViscousLayers2D ) ||
3131 ( !occgeo.fmap.IsEmpty() &&
3132 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3134 if ( !internals.hasInternalVertexInFace() ) {
3135 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3136 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3138 SMESH_ProxyMesh::Ptr viscousMesh;
3139 SMESH_MesherHelper helper( *_mesh );
3140 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3142 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3143 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3146 if ( viscousMesh->NbProxySubMeshes() == 0 )
3148 // exclude from computation ng segments built on EDGEs of F
3149 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3151 netgen::Segment & seg = _ngMesh->LineSegment(i);
3152 if (seg.si == faceID)
3155 // add new segments to _ngMesh instead of excluded ones
3156 helper.SetSubShape( F );
3158 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3159 error, &helper, viscousMesh );
3160 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3162 if ( !error ) error = SMESH_ComputeError::New();
3164 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3167 // Let netgen compute 2D mesh
3168 startWith = netgen::MESHCONST_MESHSURFACE;
3169 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3174 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3176 if ( netgen::multithread.terminate )
3179 comment << text (err);
3181 catch (Standard_Failure& ex)
3183 comment << text(ex);
3184 //err = 1; -- try to make volumes anyway
3186 catch (netgen::NgException& exc)
3188 comment << text(exc);
3189 //err = 1; -- try to make volumes anyway
3194 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3195 _ticTime = doneTime / _totalTime / _progressTic;
3197 // ---------------------
3198 // generate volume mesh
3199 // ---------------------
3200 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3201 if ( !err && _isVolume &&
3202 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3204 // load SMESH with computed segments and faces
3205 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3207 // compute prismatic boundary volumes
3208 smIdType nbQuad = _mesh->NbQuadrangles();
3209 SMESH_ProxyMesh::Ptr viscousMesh;
3210 if ( _viscousLayersHyp )
3212 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3216 // compute pyramids on quadrangles
3217 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3219 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3221 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3222 pyramidMeshes[ iS-1 ].reset( adaptor );
3223 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3227 // add proxy faces to NG mesh
3228 list< SMESH_subMesh* > viscousSM;
3229 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3231 list< SMESH_subMesh* > quadFaceSM;
3232 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3233 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3235 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3236 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3238 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3240 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3241 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3243 if ( !quadFaceSM.empty() )
3244 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3246 if ( !viscousSM.empty() )
3247 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3249 // fill _ngMesh with faces of sub-meshes
3250 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3251 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3252 // toPython( _ngMesh )
3254 if (!err && _isVolume)
3256 // Pass 3D simple parameters to NETGEN
3257 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3258 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3260 _ngMesh->Compress();
3261 if ( double vol = simple3d->GetMaxElementVolume() ) {
3263 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3264 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3267 // length from faces
3268 mparams.maxh = _ngMesh->AverageH();
3270 _ngMesh->SetGlobalH (mparams.maxh);
3271 mparams.grading = 0.4;
3272 ngLib.CalcLocalH( ngLib._ngMesh );
3274 // Care of vertices internal in solids and internal faces (issue 0020676)
3275 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3277 // store computed faces in SMESH in order not to create SMESH
3278 // faces for ng faces added here
3279 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3280 // add ng faces to solids with internal vertices
3281 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3282 // duplicate mesh faces on internal faces
3283 FixIntFaces( occgeo, *_ngMesh, internals );
3284 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3286 // Let netgen compute 3D mesh
3287 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3292 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3294 if ( netgen::multithread.terminate )
3297 if ( comment.empty() ) // do not overwrite a previous error
3298 comment << text(err);
3300 catch (Standard_Failure& ex)
3302 if ( comment.empty() ) // do not overwrite a previous error
3303 comment << text(ex);
3306 catch (netgen::NgException& exc)
3308 if ( comment.empty() ) // do not overwrite a previous error
3309 comment << text(exc);
3312 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3314 // Let netgen optimize 3D mesh
3315 if ( !err && _optimize )
3317 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3322 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3324 if ( netgen::multithread.terminate )
3327 if ( comment.empty() ) // do not overwrite a previous error
3328 comment << text(err);
3330 catch (Standard_Failure& ex)
3332 if ( comment.empty() ) // do not overwrite a previous error
3333 comment << text(ex);
3335 catch (netgen::NgException& exc)
3337 if ( comment.empty() ) // do not overwrite a previous error
3338 comment << text(exc);
3342 if (!err && mparams.secondorder > 0)
3347 if ( !meshedSM[ MeshDim_1D ].empty() )
3349 // remove segments not attached to geometry (IPAL0052479)
3350 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3352 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3353 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3355 _ngMesh->DeleteSegment( i );
3356 initState._nbSegments--;
3359 _ngMesh->Compress();
3361 // convert to quadratic
3363 occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
3365 netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
3368 // care of elements already loaded to SMESH
3369 // if ( initState._nbSegments > 0 )
3370 // makeQuadratic( occgeo.emap, _mesh );
3371 // if ( initState._nbFaces > 0 )
3372 // makeQuadratic( occgeo.fmap, _mesh );
3374 catch (Standard_Failure& ex)
3376 if ( comment.empty() ) // do not overwrite a previous error
3377 comment << "Exception in netgen at passing to 2nd order ";
3379 catch (netgen::NgException& exc)
3381 if ( comment.empty() ) // do not overwrite a previous error
3382 comment << exc.What();
3387 _ticTime = 0.98 / _progressTic;
3389 //int nbNod = _ngMesh->GetNP();
3390 //int nbSeg = _ngMesh->GetNSeg();
3391 int nbFac = _ngMesh->GetNSE();
3392 int nbVol = _ngMesh->GetNE();
3393 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3395 // Feed back the SMESHDS with the generated Nodes and Elements
3396 if ( true /*isOK*/ ) // get whatever built
3398 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3400 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3402 for ( size_t i = 0; i < nodeVec.size(); ++i )
3403 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3405 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3408 for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3410 nodeVec.resize( i );
3415 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3416 if ( readErr && readErr->HasBadElems() )
3419 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3420 comment += readErr->myComment;
3422 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3423 error->myName = COMPERR_ALGO_FAILED;
3424 if ( !comment.empty() )
3425 error->myComment = comment;
3427 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3428 // appear if the geometry contains coincident sub-shape due
3429 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3430 const int nbMaps = 2;
3431 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3432 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3433 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3434 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3435 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3436 if ( !sm->IsMeshComputed() )
3437 sm->SetIsAlwaysComputed( true );
3439 // set bad compute error to subshapes of all failed sub-shapes
3440 if ( !error->IsOK() )
3442 bool pb2D = false, pb3D = false;
3443 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3444 int status = occgeo.facemeshstatus[i-1];
3445 if (status == netgen::FACE_MESHED_OK ) continue;
3446 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3447 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3448 if ( !smError || smError->IsOK() ) {
3449 if ( status == netgen::FACE_FAILED )
3450 smError.reset( new SMESH_ComputeError( *error ));
3452 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3453 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3454 smError->myName = COMPERR_WARNING;
3456 pb2D = pb2D || smError->IsKO();
3459 if ( !pb2D ) // all faces are OK
3460 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3461 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3463 bool smComputed = nbVol && !sm->IsEmpty();
3464 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3466 size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3467 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3468 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
3470 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3471 if ( !smComputed && ( !smError || smError->IsOK() ))
3474 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3476 smError->myName = COMPERR_WARNING;
3478 else if ( smError->HasBadElems() ) // bad surface mesh
3480 if ( !hasBadElemOnSolid
3481 ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3485 pb3D = pb3D || ( smError && smError->IsKO() );
3487 if ( !pb2D && !pb3D )
3488 err = 0; // no fatal errors, only warnings
3491 ngLib._isComputeOk = !err;
3496 //=============================================================================
3500 //=============================================================================
3501 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3503 netgen::MeshingParameters& mparams = netgen::mparam;
3506 // -------------------------
3507 // Prepare OCC geometry
3508 // -------------------------
3509 netgen::OCCGeometry occgeo;
3510 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3511 PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3513 bool tooManyElems = false;
3514 const int hugeNb = std::numeric_limits<int>::max() / 100;
3519 // pass 1D simple parameters to NETGEN
3522 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3523 mparams.uselocalh = false;
3524 mparams.grading = 0.8; // not limitited size growth
3526 if ( _simpleHyp->GetNumberOfSegments() )
3528 mparams.maxh = occgeo.boundingbox.Diam();
3531 mparams.maxh = _simpleHyp->GetLocalLength();
3534 if ( mparams.maxh == 0.0 )
3535 mparams.maxh = occgeo.boundingbox.Diam();
3536 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3537 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3539 // let netgen create _ngMesh and calculate element size on not meshed shapes
3540 NETGENPlugin_NetgenLibWrapper ngLib;
3541 netgen::Mesh *ngMesh = NULL;
3542 int startWith = netgen::MESHCONST_ANALYSE;
3543 int endWith = netgen::MESHCONST_MESHEDGES;
3544 int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
3546 if(netgen::multithread.terminate)
3549 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3551 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3552 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3555 // if ( _simpleHyp )
3557 // // Pass 1D simple parameters to NETGEN
3558 // // --------------------------------
3559 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3560 // double segSize = _simpleHyp->GetLocalLength();
3561 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3563 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3565 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3566 // setLocalSize( e, segSize, *ngMesh );
3569 // else // if ( ! _simpleHyp )
3571 // // Local size on shapes
3572 // SetLocalSize( occgeo, *ngMesh );
3574 // calculate total nb of segments and length of edges
3575 double fullLen = 0.0;
3576 smIdType fullNbSeg = 0;
3577 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3578 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3579 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3581 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3582 if( !Edge2NbSeg.Bind(E,0) )
3585 double aLen = SMESH_Algo::EdgeLength(E);
3588 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
3590 aVec.resize( SMDSEntity_Last, 0);
3592 fullNbSeg += aVec[ entity ];
3595 // store nb of segments computed by Netgen
3597 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3599 const netgen::Segment& seg = ngMesh->LineSegment(i);
3600 Link link(seg[0], seg[1]);
3601 if ( !linkMap.Add( link )) continue;
3602 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3603 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3605 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3609 // store nb of nodes on edges computed by Netgen
3610 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3611 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3613 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3614 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3615 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3617 fullNbSeg += aVec[ entity ];
3618 Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
3620 if ( fullNbSeg == 0 )
3627 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3629 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3630 mparams.grading = 0.4; // moderate size growth
3633 // length from edges
3634 mparams.maxh = fullLen / double( fullNbSeg );
3635 mparams.grading = 0.2; // slow size growth
3638 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3639 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3641 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3643 TopoDS_Face F = TopoDS::Face( exp.Current() );
3644 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3646 BRepGProp::SurfaceProperties(F,G);
3647 double anArea = G.Mass();
3648 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3650 if ( !tooManyElems )
3652 TopTools_MapOfShape edges;
3653 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3654 if ( edges.Add( exp1.Current() ))
3655 nb1d += Edge2NbSeg.Find(exp1.Current());
3657 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3658 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3660 vector<smIdType> aVec(SMDSEntity_Last, 0);
3661 if( mparams.secondorder > 0 ) {
3662 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3663 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3664 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3667 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3668 aVec[SMDSEntity_Triangle] = nbFaces;
3670 aResMap[sm].swap(aVec);
3677 // pass 3D simple parameters to NETGEN
3678 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3679 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3681 if ( double vol = simple3d->GetMaxElementVolume() ) {
3683 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3684 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3687 // using previous length from faces
3689 mparams.grading = 0.4;
3690 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3693 BRepGProp::VolumeProperties(_shape,G);
3694 double aVolume = G.Mass();
3695 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3696 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3697 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3698 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3699 vector<smIdType> aVec(SMDSEntity_Last, 0 );
3700 if ( tooManyElems ) // avoid FPE
3702 aVec[SMDSEntity_Node] = hugeNb;
3703 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3707 if( mparams.secondorder > 0 ) {
3708 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3709 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3712 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3713 aVec[SMDSEntity_Tetra] = nbVols;
3716 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3717 aResMap[sm].swap(aVec);
3723 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
3724 const int * algoProgressTic,
3725 const double * algoProgress) const
3727 ((int&) _progressTic ) = *algoProgressTic + 1;
3729 if ( !_occgeom ) return 0;
3731 double progress = -1;
3734 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3736 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3738 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3740 int doneShapeIndex = -1;
3741 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3742 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3744 if ( doneShapeIndex+1 != _curShapeIndex )
3746 ((int&) _curShapeIndex) = doneShapeIndex+1;
3747 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3748 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3749 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3750 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3751 // << " " << doneTime / _totalTime / _progressTic << endl;
3755 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3757 int curShapeIndex = _curShapeIndex;
3758 if ( _ngMesh->GetNE() > 0 )
3760 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3761 curShapeIndex = el.GetIndex();
3763 if ( curShapeIndex != _curShapeIndex )
3765 ((int&) _curShapeIndex) = curShapeIndex;
3766 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3767 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3768 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3769 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3770 // << " " << doneTime / _totalTime / _progressTic << endl;
3775 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3780 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3781 progress > voluMeshingTime )
3783 progress = voluMeshingTime;
3784 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3786 ((int&) *algoProgressTic )++;
3787 ((double&) *algoProgress) = progress;
3789 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3791 return Min( progress, 0.99 );
3794 //================================================================================
3796 * \brief Read mesh entities preventing successful computation from "test.out" file
3798 //================================================================================
3800 SMESH_ComputeErrorPtr
3801 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3803 if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3804 SMESH_BadInputElements* err =
3805 new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3806 "Some edges multiple times in surface mesh");
3807 SMESH_File file("test.out");
3809 vector<int> three1(3), three2(3);
3810 const char* badEdgeStr = " multiple times in surface mesh";
3811 const int badEdgeStrLen = (int) strlen( badEdgeStr );
3812 const int nbNodes = (int) nodeVec.size();
3814 while( !file.eof() )
3816 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3817 file.getInts( two ) &&
3818 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3819 two[0] < nbNodes && two[1] < nbNodes )
3821 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3822 file += (int) badEdgeStrLen;
3824 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3827 // openelement 18 with open element 126
3831 const char* pos = file;
3832 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3833 ok = ok && file.getInts( two );
3834 ok = ok && file.getInts( three1 );
3835 ok = ok && file.getInts( three2 );
3836 for ( int i = 0; ok && i < 3; ++i )
3837 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3838 for ( int i = 0; ok && i < 3; ++i )
3839 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3842 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3843 nodeVec[ three1[1]],
3844 nodeVec[ three1[2]]));
3845 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3846 nodeVec[ three2[1]],
3847 nodeVec[ three2[2]]));
3848 err->myComment = "Intersecting triangles";
3862 size_t nbBadElems = err->myBadElements.size();
3863 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3866 return SMESH_ComputeErrorPtr( err );
3869 //================================================================================
3871 * \brief Write a python script creating an equivalent SALOME mesh.
3872 * This is useful to see what mesh is passed as input for the next step of mesh
3873 * generation (of mesh of higher dimension)
3875 //================================================================================
3877 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3879 const char* pyFile = "/tmp/ngMesh.py";
3880 ofstream outfile( pyFile, ios::out );
3881 if ( !outfile ) return;
3883 outfile << "import salome, SMESH" << std::endl
3884 << "from salome.smesh import smeshBuilder" << std::endl
3885 << "smesh = smeshBuilder.New()" << std::endl
3886 << "mesh = smesh.Mesh()" << std::endl << std::endl;
3888 using namespace netgen;
3892 for ( int i = 1; i <= ngMesh->GetNP(); i++)
3894 const Point3d & p = ngMesh->Point(i);
3895 outfile << "mesh.AddNode( ";
3896 outfile << p.X() << ", ";
3897 outfile << p.Y() << ", ";
3898 outfile << p.Z() << ") ## "<< i << std::endl;
3901 int nbDom = ngMesh->GetNDomains();
3902 for ( int i = 0; i < nbDom; ++i )
3903 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3906 for (int i = 1; i <= ngMesh->GetNSE(); i++)
3908 outfile << "mesh.AddFace([ ";
3909 Element2d sel = ngMesh->SurfaceElement(i);
3910 for (int j = 1; j <= sel.GetNP(); j++)
3911 outfile << sel.PNum(j) << ( j < sel.GetNP() ? ", " : " ])");
3912 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3913 outfile << std::endl;
3914 nbDel += sel.IsDeleted();
3918 if ( int dom1 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainIn())
3919 outfile << "grp"<< dom1 <<".Add([ " << i - nbDel << " ])" << std::endl;
3920 if ( int dom2 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainOut())
3921 outfile << "grp"<< dom2 <<".Add([ " << i - nbDel << " ])" << std::endl;
3925 for (int i = 1; i <= ngMesh->GetNE(); i++)
3927 Element el = ngMesh->VolumeElement(i);
3928 outfile << "mesh.AddVolume([ ";
3929 for (int j = 1; j <= el.GetNP(); j++)
3930 outfile << el.PNum(j) << ( j < el.GetNP() ? ", " : " ])");
3931 outfile << std::endl;
3934 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3936 const Segment & seg = ngMesh->LineSegment (i);
3937 outfile << "mesh.AddEdge([ "
3939 << seg[1]+1 << " ])" << std::endl;
3945 for (pi = PointIndex::BASE;
3946 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3948 outfile << "mesh.AddNode( ";
3949 outfile << (*ngMesh)[pi](0) << ", ";
3950 outfile << (*ngMesh)[pi](1) << ", ";
3951 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3954 int nbDom = ngMesh->GetNDomains();
3955 for ( int i = 0; i < nbDom; ++i )
3956 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3959 SurfaceElementIndex sei;
3960 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3962 outfile << "mesh.AddFace([ ";
3963 Element2d sel = (*ngMesh)[sei];
3964 for (int j = 0; j < sel.GetNP(); j++)
3965 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3966 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3967 outfile << std::endl;
3968 nbDel += sel.IsDeleted();
3970 if ((*ngMesh)[sei].GetIndex())
3972 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3973 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3974 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3975 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3979 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3981 Element el = (*ngMesh)[ei];
3982 outfile << "mesh.AddVolume([ ";
3983 for (int j = 0; j < el.GetNP(); j++)
3984 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3985 outfile << std::endl;
3988 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3990 const Segment & seg = ngMesh->LineSegment (i);
3991 outfile << "mesh.AddEdge([ "
3993 << seg[1] << " ])" << std::endl;
3998 std::cout << "Write " << pyFile << std::endl;
4001 //================================================================================
4003 * \brief Constructor of NETGENPlugin_ngMeshInfo
4005 //================================================================================
4007 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
4008 bool checkRemovedElems):
4009 _elementsRemoved( false ), _copyOfLocalH(0)
4013 _nbNodes = ngMesh->GetNP();
4014 _nbSegments = ngMesh->GetNSeg();
4015 _nbFaces = ngMesh->GetNSE();
4016 _nbVolumes = ngMesh->GetNE();
4018 if ( checkRemovedElems )
4019 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
4020 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
4024 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
4028 //================================================================================
4030 * \brief Copy LocalH member from one netgen mesh to another
4032 //================================================================================
4034 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
4035 netgen::Mesh* toMesh )
4037 if ( !fromMesh->LocalHFunctionGenerated() ) return;
4038 if ( !toMesh->LocalHFunctionGenerated() )
4039 NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
4041 const size_t size = sizeof( netgen::LocalH );
4042 _copyOfLocalH = new char[ size ];
4043 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
4044 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
4047 //================================================================================
4049 * \brief Restore LocalH member of a netgen mesh
4051 //================================================================================
4053 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
4055 if ( _copyOfLocalH )
4057 const size_t size = sizeof( netgen::LocalH );
4058 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
4059 delete [] _copyOfLocalH;
4064 //================================================================================
4066 * \brief Find "internal" sub-shapes
4068 //================================================================================
4070 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
4071 const TopoDS_Shape& shape,
4073 : _mesh( mesh ), _is3D( is3D )
4075 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4077 TopExp_Explorer f,e;
4078 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
4080 int faceID = meshDS->ShapeToIndex( f.Current() );
4082 // find not computed internal edges
4084 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4085 if ( e.Current().Orientation() == TopAbs_INTERNAL )
4087 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4088 if ( eSM->IsEmpty() )
4090 _e2face.insert( make_pair( eSM->GetId(), faceID ));
4091 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4092 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4096 // find internal vertices in a face
4097 set<int> intVV; // issue 0020850 where same vertex is twice in a face
4098 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4099 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4101 int vID = meshDS->ShapeToIndex( fSub.Value() );
4102 if ( intVV.insert( vID ).second )
4103 _f2v[ faceID ].push_back( vID );
4108 // find internal faces and their subshapes where nodes are to be doubled
4109 // to make a crack with non-sewed borders
4111 if ( f.Current().Orientation() == TopAbs_INTERNAL )
4113 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4116 list< TopoDS_Shape > edges;
4117 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4118 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4120 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4121 edges.push_back( e.Current() );
4122 // find border faces
4123 PShapeIteratorPtr fIt =
4124 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4125 while ( const TopoDS_Shape* pFace = fIt->next() )
4126 if ( !pFace->IsSame( f.Current() ))
4127 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4130 // we consider vertex internal if it is shared by more than one internal edge
4131 list< TopoDS_Shape >::iterator edge = edges.begin();
4132 for ( ; edge != edges.end(); ++edge )
4133 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4135 set<int> internalEdges;
4136 PShapeIteratorPtr eIt =
4137 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4138 while ( const TopoDS_Shape* pEdge = eIt->next() )
4140 int edgeID = meshDS->ShapeToIndex( *pEdge );
4141 if ( isInternalShape( edgeID ))
4142 internalEdges.insert( edgeID );
4144 if ( internalEdges.size() > 1 )
4145 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4149 } // loop on geom faces
4151 // find vertices internal in solids
4154 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4156 int soID = meshDS->ShapeToIndex( so.Current() );
4157 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4158 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4159 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4164 //================================================================================
4166 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4167 * some nodes of which are to be doubled to make the second border of the "crack"
4169 //================================================================================
4171 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4173 if ( _intShapes.empty() ) return;
4175 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4176 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4178 // loop on internal geom edges
4179 set<int>::const_iterator intShapeId = _intShapes.begin();
4180 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4182 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4183 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4185 // get internal and non-internal geom faces sharing the internal edge <s>
4187 set<int>::iterator bordFace = _borderFaces.end();
4188 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4189 while ( const TopoDS_Shape* pFace = faces->next() )
4191 int faceID = meshDS->ShapeToIndex( *pFace );
4192 if ( isInternalShape( faceID ))
4195 bordFace = _borderFaces.insert( faceID ).first;
4197 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4199 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4200 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4201 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4202 int nbSuspectFaces = 0;
4203 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4204 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4205 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4206 while ( smIt->more() )
4208 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4209 if ( !sm ) continue;
4210 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4211 while ( nIt->more() )
4213 const SMDS_MeshNode* nOnEdge = nIt->next();
4214 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4215 while ( fIt->more() )
4217 const SMDS_MeshElement* f = fIt->next();
4218 const int nbNodes = f->NbCornerNodes();
4219 if ( intFaceSM->Contains( f ))
4221 for ( int i = 0; i < nbNodes; ++i )
4222 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4227 for ( int i = 0; i < nbNodes; ++i )
4228 nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4230 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4236 // suspectFaces[0] having link with same orientation as mesh faces on
4237 // the internal geom face are <borderElems>. suspectFaces[1] have
4238 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4239 // by links of <borderElems> found at the 1st and 2nd loops
4240 set< SMESH_OrientedLink > borderLinks;
4241 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4243 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4244 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4246 const SMDS_MeshElement* f = *fIt;
4247 bool isBorder = false, linkFound = false, borderLinkFound = false;
4248 list< SMESH_OrientedLink > faceLinks;
4249 int nbNodes = f->NbCornerNodes();
4250 for ( int i = 0; i < nbNodes; ++i )
4252 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4253 faceLinks.push_back( link );
4256 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4257 if ( foundLink != links.end() )
4260 isBorder = ( foundLink->_reversed == link._reversed );
4261 if ( !isBorder && !isPostponed ) break;
4262 faceLinks.pop_back();
4264 else if ( isPostponed && !borderLinkFound )
4266 foundLink = borderLinks.find( link );
4267 if ( foundLink != borderLinks.end() )
4269 borderLinkFound = true;
4270 isBorder = ( foundLink->_reversed != link._reversed );
4277 borderElems.insert( f );
4278 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4280 else if ( !linkFound && !borderLinkFound )
4282 suspectFaces[1].push_back( f );
4283 if ( nbF > 2 * nbSuspectFaces )
4284 break; // dead loop protection
4291 //================================================================================
4293 * \brief put internal shapes in maps and fill in submeshes to precompute
4295 //================================================================================
4297 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4298 TopTools_IndexedMapOfShape& emap,
4299 TopTools_IndexedMapOfShape& vmap,
4300 list< SMESH_subMesh* > smToPrecompute[])
4302 if ( !hasInternalEdges() ) return;
4303 map<int,int>::const_iterator ev_face = _e2face.begin();
4304 for ( ; ev_face != _e2face.end(); ++ev_face )
4306 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4307 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4309 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4311 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4313 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4317 //================================================================================
4319 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4321 //================================================================================
4323 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4324 TopTools_IndexedMapOfShape& emap,
4325 list< SMESH_subMesh* >& intFaceSM,
4326 list< SMESH_subMesh* >& boundarySM)
4328 if ( !hasInternalFaces() ) return;
4330 // <fmap> and <emap> are for not yet meshed shapes
4331 // <intFaceSM> is for submeshes of faces
4332 // <boundarySM> is for meshed edges and vertices
4337 set<int> shapeIDs ( _intShapes );
4338 if ( !_borderFaces.empty() )
4339 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4341 set<int>::const_iterator intS = shapeIDs.begin();
4342 for ( ; intS != shapeIDs.end(); ++intS )
4344 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4346 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4348 intFaceSM.push_back( sm );
4350 // add submeshes of not computed internal faces
4351 if ( !sm->IsEmpty() ) continue;
4353 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4354 while ( smIt->more() )
4357 const TopoDS_Shape& s = sm->GetSubShape();
4359 if ( sm->IsEmpty() )
4362 switch ( s.ShapeType() ) {
4363 case TopAbs_FACE: fmap.Add ( s ); break;
4364 case TopAbs_EDGE: emap.Add ( s ); break;
4370 if ( s.ShapeType() != TopAbs_FACE )
4371 boundarySM.push_back( sm );
4377 //================================================================================
4379 * \brief Return true if given shape is to be precomputed in order to be correctly
4380 * added to netgen mesh
4382 //================================================================================
4384 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4386 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4387 switch ( s.ShapeType() ) {
4388 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4389 case TopAbs_EDGE : return isInternalEdge( shapeID );
4390 case TopAbs_VERTEX: break;
4396 //================================================================================
4398 * \brief Return SMESH
4400 //================================================================================
4402 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4404 return const_cast<SMESH_Mesh&>( _mesh );
4407 //================================================================================
4409 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4411 //================================================================================
4413 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4415 static int theCouner = 0;
4419 //================================================================================
4421 * \brief Initialize netgen library
4423 //================================================================================
4425 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
4428 if ( instanceCounter() == 0 )
4431 if ( !netgen::testout )
4432 netgen::testout = new ofstream( "test.out" );
4435 ++instanceCounter();
4437 _isComputeOk = false;
4441 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4443 setOutputFile(getOutputFileName());
4446 setMesh( Ng_NewMesh() );
4449 //================================================================================
4451 * \brief Finish using netgen library
4453 //================================================================================
4455 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4457 --instanceCounter();
4459 Ng_DeleteMesh( ngMesh() );
4463 std::cout.rdbuf( _coutBuffer );
4470 //================================================================================
4472 * \brief Set netgen mesh to delete at destruction
4474 //================================================================================
4476 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4479 Ng_DeleteMesh( ngMesh() );
4480 _ngMesh = (netgen::Mesh*) mesh;
4483 //================================================================================
4485 * \brief Perform a step of mesh generation
4486 * \param [inout] occgeo - geometry to mesh
4487 * \param [inout] startWith - start step
4488 * \param [inout] endWith - end step
4489 * \param [inout] ngMesh - netgen mesh
4490 * \return int - is error
4492 //================================================================================
4494 int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
4495 int startWith, int endWith,
4496 netgen::Mesh* & ngMesh )
4500 ngMesh = new netgen::Mesh;
4503 // netgen::mparam.Print(std::cerr);
4507 ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
4509 netgen::mparam.perfstepsstart = startWith;
4510 netgen::mparam.perfstepsend = endWith;
4511 std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
4512 err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
4517 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
4522 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
4529 //================================================================================
4531 * \brief Create a mesh size tree
4533 //================================================================================
4535 void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
4537 #if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
4538 ngMesh->CalcLocalH(netgen::mparam.grading);
4540 ngMesh->CalcLocalH();
4544 //================================================================================
4546 * \brief Return a unique file name
4548 //================================================================================
4550 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4552 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4554 TCollection_AsciiString aGenericName = aTmpDir.c_str();
4555 aGenericName += "NETGEN_";
4557 aGenericName += getpid();
4559 aGenericName += _getpid();
4561 aGenericName += "_";
4562 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4563 aGenericName += ".out";
4565 return aGenericName.ToCString();
4567 //================================================================================
4569 * \brief Set output file name for netgen log
4571 //================================================================================
4573 void NETGENPlugin_NetgenLibWrapper::setOutputFile(std::string outputfile)
4575 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4576 _outputFileName = outputfile;
4577 _ngcout = netgen::mycout;
4578 _ngcerr = netgen::myerr;
4579 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4580 netgen::myerr = netgen::mycout;
4581 _coutBuffer = std::cout.rdbuf();
4583 std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4585 std::cout.rdbuf( netgen::mycout->rdbuf() );
4589 //================================================================================
4591 * \brief Remove "test.out" and "problemfaces" files in current directory
4593 //================================================================================
4595 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4597 bool rm = SMESH_File("test.out").remove() ;
4599 if ( rm && netgen::testout && instanceCounter() == 0 )
4601 delete netgen::testout;
4602 netgen::testout = 0;
4605 SMESH_File("problemfaces").remove();
4606 SMESH_File("occmesh.rep").remove();
4609 //================================================================================
4611 * \brief Remove file with netgen output
4613 //================================================================================
4615 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4617 if ( !_outputFileName.empty() )
4621 delete netgen::mycout;
4622 netgen::mycout = _ngcout;
4623 netgen::myerr = _ngcerr;
4626 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4627 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4628 SALOMEDS_Tool::ListOfFiles aFiles;
4630 aFiles.push_back(aFileName.c_str());
4632 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );