1 // Copyright (C) 2007-2013 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.
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_MeshElement.hxx>
36 #include <SMDS_MeshNode.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Block.hxx>
39 #include <SMESH_Comment.hxx>
40 #include <SMESH_ComputeError.hxx>
41 #include <SMESH_File.hxx>
42 #include <SMESH_Gen_i.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_MesherHelper.hxx>
45 #include <SMESH_subMesh.hxx>
46 #include <StdMeshers_QuadToTriaAdaptor.hxx>
47 #include <StdMeshers_ViscousLayers2D.hxx>
49 #include <SALOMEDS_Tool.hxx>
51 #include <utilities.h>
53 #include <BRepBuilderAPI_Copy.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Bnd_B3d.hxx>
56 #include <NCollection_Map.hxx>
57 #include <Standard_ErrorHandler.hxx>
58 #include <Standard_ProgramError.hxx>
60 #include <TopExp_Explorer.hxx>
61 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
63 #include <TopTools_DataMapOfShapeInteger.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
67 #include <OSD_File.hxx>
68 #include <OSD_Path.hxx>
70 // Netgen include files
74 #include <occgeom.hpp>
75 #include <meshing.hpp>
76 //#include <ngexception.hpp>
79 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
81 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
83 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
84 extern MeshingParameters mparam;
85 extern volatile multithreadt multithread;
94 using namespace nglib;
98 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
100 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
103 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
105 // dump elements added to ng mesh
106 //#define DUMP_SEGMENTS
107 //#define DUMP_TRIANGLES
108 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
110 TopTools_IndexedMapOfShape ShapesWithLocalSize;
111 std::map<int,double> VertexId2LocalSize;
112 std::map<int,double> EdgeId2LocalSize;
113 std::map<int,double> FaceId2LocalSize;
115 //=============================================================================
119 //=============================================================================
121 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
122 const TopoDS_Shape& aShape,
128 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
129 _isViscousLayers2D(false),
138 SetDefaultParameters();
139 ShapesWithLocalSize.Clear();
140 VertexId2LocalSize.clear();
141 EdgeId2LocalSize.clear();
142 FaceId2LocalSize.clear();
145 //================================================================================
149 //================================================================================
151 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
159 //================================================================================
161 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
162 * nullified at destruction of this
164 //================================================================================
166 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
177 //================================================================================
179 * \brief Initialize global NETGEN parameters with default values
181 //================================================================================
183 void NETGENPlugin_Mesher::SetDefaultParameters()
185 netgen::MeshingParameters& mparams = netgen::mparam;
186 // maximal mesh edge size
187 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
189 // minimal number of segments per edge
190 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
191 // rate of growth of size between elements
192 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
193 // safety factor for curvatures (elements per radius)
194 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
195 // create elements of second order
196 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder() ? 1 : 0;
197 // quad-dominated surface meshing
201 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed() ? 1 : 0;
202 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
205 //=============================================================================
209 //=============================================================================
210 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
212 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
213 if (GeomType == TopAbs_COMPOUND) {
214 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
215 SetLocalSize(it.Value(), LocalSize);
220 if (! ShapesWithLocalSize.Contains(GeomShape))
221 key = ShapesWithLocalSize.Add(GeomShape);
223 key = ShapesWithLocalSize.FindIndex(GeomShape);
224 if (GeomType == TopAbs_VERTEX) {
225 VertexId2LocalSize[key] = LocalSize;
226 } else if (GeomType == TopAbs_EDGE) {
227 EdgeId2LocalSize[key] = LocalSize;
228 } else if (GeomType == TopAbs_FACE) {
229 FaceId2LocalSize[key] = LocalSize;
233 //=============================================================================
235 * Pass parameters to NETGEN
237 //=============================================================================
238 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
242 netgen::MeshingParameters& mparams = netgen::mparam;
243 // Initialize global NETGEN parameters:
244 // maximal mesh segment size
245 mparams.maxh = hyp->GetMaxSize();
246 // maximal mesh element linear size
247 mparams.minh = hyp->GetMinSize();
248 // minimal number of segments per edge
249 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
250 // rate of growth of size between elements
251 mparams.grading = hyp->GetGrowthRate();
252 // safety factor for curvatures (elements per radius)
253 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
254 // create elements of second order
255 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
256 // quad-dominated surface meshing
257 // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
259 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
260 _optimize = hyp->GetOptimize();
261 _fineness = hyp->GetFineness();
264 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
265 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
266 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
267 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
269 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
270 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
271 for (it ; it != localSizes.end() ; it++)
273 std::string entry = (*it).first;
274 double val = (*it).second;
276 GEOM::GEOM_Object_var aGeomObj;
277 TopoDS_Shape S = TopoDS_Shape();
278 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
279 if (!aSObj->_is_nil()) {
280 CORBA::Object_var obj = aSObj->GetObject();
281 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
284 if ( !aGeomObj->_is_nil() )
285 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
287 SetLocalSize(S, val);
292 //=============================================================================
294 * Pass simple parameters to NETGEN
296 //=============================================================================
298 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
302 SetDefaultParameters();
305 //=============================================================================
307 * Link - a pair of integer numbers
309 //=============================================================================
313 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
314 Link() : n1(0), n2(0) {}
317 int HashCode(const Link& aLink, int aLimit)
319 return HashCode(aLink.n1 + aLink.n2, aLimit);
322 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
324 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
325 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
330 //================================================================================
332 * \brief return id of netgen point corresponding to SMDS node
334 //================================================================================
335 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
337 int ngNodeId( const SMDS_MeshNode* node,
338 netgen::Mesh& ngMesh,
339 TNode2IdMap& nodeNgIdMap)
341 int newNgId = ngMesh.GetNP() + 1;
343 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
345 if ( node_id->second == newNgId)
347 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
348 cout << "Ng " << newNgId << " - " << node;
350 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
351 ngMesh.AddPoint( p );
353 return node_id->second;
356 //================================================================================
358 * \brief Return computed EDGEs connected to the given one
360 //================================================================================
362 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
363 const TopoDS_Face& face,
364 const set< SMESH_subMesh* > & computedSM,
365 const SMESH_MesherHelper& helper,
366 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
369 list< TopoDS_Edge > edges;
370 list< int > nbEdgesInWire;
371 int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
373 // find <edge> within <edges>
374 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
375 for ( ; eItFwd != edges.end(); ++eItFwd )
376 if ( edge.IsSame( *eItFwd ))
378 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
380 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
382 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
383 // so treat each INTERNAL edge separately
384 TopoDS_Edge e = *eItFwd;
386 edges.push_back( e );
390 // get all computed EDGEs connected to <edge>
392 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
393 TopoDS_Vertex vCommon;
394 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
397 // put edges before <edge> to <edges> back
398 while ( edges.begin() != eItFwd )
399 edges.splice( edges.end(), edges, edges.begin() );
403 while ( ++eItFwd != edges.end() )
405 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
407 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
408 bool computed = sm->IsMeshComputed();
409 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
410 bool doubled = !eAdded.Add( *eItFwd );
411 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
412 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
413 if ( !connected || !computed || !orientOK || added || doubled )
415 // stop advancement; move edges from tail to head
416 while ( edges.back() != *ePrev )
417 edges.splice( edges.begin(), edges, --edges.end() );
423 while ( eItBack != edges.begin() )
427 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
429 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
430 bool computed = sm->IsMeshComputed();
431 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
432 bool doubled = !eAdded.Add( *eItBack );
433 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
434 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
435 if ( !connected || !computed || !orientOK || added || doubled)
438 edges.erase( edges.begin(), ePrev );
442 if ( edges.front() != edges.back() )
444 // assure that the 1st vertex is meshed
445 TopoDS_Edge eLast = edges.back();
446 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
448 edges.front() != eLast )
449 edges.splice( edges.end(), edges, edges.begin() );
454 //================================================================================
456 * \brief Make triangulation of a shape precise enough
458 //================================================================================
460 void updateTriangulation( const TopoDS_Shape& shape )
462 // static set< Poly_Triangulation* > updated;
464 // TopLoc_Location loc;
465 // TopExp_Explorer fExp( shape, TopAbs_FACE );
466 // for ( ; fExp.More(); fExp.Next() )
468 // Handle(Poly_Triangulation) triangulation =
469 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
470 // if ( triangulation.IsNull() ||
471 // updated.insert( triangulation.operator->() ).second )
473 // BRepTools::Clean (shape);
476 BRepMesh_IncrementalMesh e(shape, 0.01, true);
478 catch (Standard_Failure)
481 // updated.erase( triangulation.operator->() );
482 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
483 // updated.insert( triangulation.operator->() );
489 //================================================================================
491 * \brief Initialize netgen::OCCGeometry with OCCT shape
493 //================================================================================
495 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
496 const TopoDS_Shape& shape,
498 list< SMESH_subMesh* > * meshedSM,
499 NETGENPlugin_Internals* intern)
501 updateTriangulation( shape );
504 BRepBndLib::Add (shape, bb);
505 double x1,y1,z1,x2,y2,z2;
506 bb.Get (x1,y1,z1,x2,y2,z2);
507 MESSAGE("shape bounding box:\n" <<
508 "(" << x1 << " " << y1 << " " << z1 << ") " <<
509 "(" << x2 << " " << y2 << " " << z2 << ")");
510 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
511 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
512 occgeo.boundingbox = netgen::Box<3> (p1,p2);
514 occgeo.shape = shape;
517 // fill maps of shapes of occgeo with not yet meshed subshapes
519 // get root submeshes
520 list< SMESH_subMesh* > rootSM;
521 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
522 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
523 rootSM.push_back( mesh.GetSubMesh( shape ));
526 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
527 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
530 // add subshapes of empty submeshes
531 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
532 for ( ; rootIt != rootEnd; ++rootIt ) {
533 SMESH_subMesh * root = *rootIt;
534 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
535 /*complexShapeFirst=*/true);
536 // to find a right orientation of subshapes (PAL20462)
537 TopTools_IndexedMapOfShape subShapes;
538 TopExp::MapShapes(root->GetSubShape(), subShapes);
539 while ( smIt->more() )
541 SMESH_subMesh* sm = smIt->next();
542 TopoDS_Shape shape = sm->GetSubShape();
543 if ( intern && intern->isShapeToPrecompute( shape ))
545 if ( !meshedSM || sm->IsEmpty() )
547 if ( shape.ShapeType() != TopAbs_VERTEX )
548 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
549 if ( shape.Orientation() >= TopAbs_INTERNAL )
550 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
551 switch ( shape.ShapeType() ) {
552 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
553 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
554 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
555 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
559 // collect submeshes of meshed shapes
562 const int dim = SMESH_Gen::GetShapeDim( shape );
563 meshedSM[ dim ].push_back( sm );
567 occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
568 occgeo.facemeshstatus = 0;
569 occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
570 occgeo.face_maxh_modified = 0;
571 occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
572 occgeo.face_maxh = netgen::mparam.maxh;
575 //================================================================================
577 * \brief Return a default min size value suitable for the given geometry.
579 //================================================================================
581 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
582 const double maxSize)
584 updateTriangulation( geom );
588 const int* pi[4] = { &i1, &i2, &i3, &i1 };
591 TopExp_Explorer fExp( geom, TopAbs_FACE );
592 for ( ; fExp.More(); fExp.Next() )
594 Handle(Poly_Triangulation) triangulation =
595 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
596 if ( triangulation.IsNull() ) continue;
597 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
598 const TColgp_Array1OfPnt& points = triangulation->Nodes();
599 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
600 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
602 trias(iT).Get( i1, i2, i3 );
603 for ( int j = 0; j < 3; ++j )
605 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
606 if ( dist2 < minh && fTol*fTol < dist2 )
608 bb.Add( points(*pi[j]));
612 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
614 minh = 1e-3 * sqrt( bb.SquareExtent());
615 //cout << "BND BOX minh = " <<minh << endl;
619 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
620 //cout << "TRIANGULATION minh = " <<minh << endl;
622 if ( minh > 0.5 * maxSize )
628 //================================================================================
630 * \brief Restrict size of elements at a given point
632 //================================================================================
634 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh, const gp_XYZ& p, const double size)
636 if ( netgen::mparam.minh > size )
638 ngMesh.SetMinimalH( size );
639 netgen::mparam.minh = size;
641 netgen::Point3d pi(p.X(), p.Y(), p.Z());
642 ngMesh.RestrictLocalH( pi, size );
645 //================================================================================
647 * \brief fill ngMesh with nodes and elements of computed submeshes
649 //================================================================================
651 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
652 netgen::Mesh& ngMesh,
653 vector<const SMDS_MeshNode*>& nodeVec,
654 const list< SMESH_subMesh* > & meshedSM,
655 SMESH_ProxyMesh::Ptr proxyMesh)
657 TNode2IdMap nodeNgIdMap;
658 for ( int i = 1; i < nodeVec.size(); ++i )
659 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
661 TopTools_MapOfShape visitedShapes;
662 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
663 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
665 SMESH_MesherHelper helper (*_mesh);
667 int faceNgID = ngMesh.GetNFD();
669 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
670 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
672 SMESH_subMesh* sm = *smIt;
673 if ( !visitedShapes.Add( sm->GetSubShape() ))
676 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
677 if ( !smDS ) continue;
679 switch ( sm->GetSubShape().ShapeType() )
681 case TopAbs_EDGE: { // EDGE
682 // ----------------------
683 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
684 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
685 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
687 // Add ng segments for each not meshed FACE the EDGE bounds
688 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
689 while ( const TopoDS_Shape * anc = fIt->next() )
691 faceNgID = occgeom.fmap.FindIndex( *anc );
693 continue; // meshed face
695 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
696 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
697 continue; // already treated EDGE
699 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
700 if ( face.Orientation() >= TopAbs_INTERNAL )
701 face.Orientation( TopAbs_FORWARD ); // issue 0020676
703 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
704 helper.SetSubShape( face );
705 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
706 visitedEdgeSM2Faces );
708 continue; // wrong ancestor?
710 // find out orientation of <edges> within <face>
711 TopoDS_Edge eNotSeam = edges.front();
712 if ( helper.HasSeam() )
714 list< TopoDS_Edge >::iterator eIt = edges.begin();
715 while ( helper.IsRealSeam( *eIt )) ++eIt;
716 if ( eIt != edges.end() )
719 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
720 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
722 // get all nodes from connected <edges>
723 bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
724 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
725 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
726 int i, nbSeg = fSide.NbSegments();
728 // remember EDGEs of fSide to treat only once
729 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
730 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
732 double otherSeamParam = 0;
737 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
739 for ( i = 0; i < nbSeg; ++i )
741 const UVPtStruct& p1 = points[ i ];
742 const UVPtStruct& p2 = points[ i+1 ];
744 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
747 if ( helper.IsRealSeam( p1.node->getshapeId() ))
749 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
750 isSeam = helper.IsRealSeam( e );
753 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
760 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
761 // node param on curve
762 seg.epgeominfo[ 0 ].dist = p1.param;
763 seg.epgeominfo[ 1 ].dist = p2.param;
765 seg.epgeominfo[ 0 ].u = p1.u;
766 seg.epgeominfo[ 0 ].v = p1.v;
767 seg.epgeominfo[ 1 ].u = p2.u;
768 seg.epgeominfo[ 1 ].v = p2.v;
770 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
771 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
773 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
774 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
775 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
776 ngMesh.AddSegment (seg);
778 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
779 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
782 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
783 << "\tface index: " << seg.si << endl
784 << "\tp1: " << seg[0] << endl
785 << "\tp2: " << seg[1] << endl
786 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
787 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
788 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
789 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
790 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
791 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
795 if ( helper.GetPeriodicIndex() && 1 ) {
796 seg.epgeominfo[ 0 ].u = otherSeamParam;
797 seg.epgeominfo[ 1 ].u = otherSeamParam;
798 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
800 seg.epgeominfo[ 0 ].v = otherSeamParam;
801 seg.epgeominfo[ 1 ].v = otherSeamParam;
802 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
804 swap (seg[0], seg[1]);
805 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
806 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
807 ngMesh.AddSegment (seg);
809 cout << "Segment: " << seg.edgenr << endl
810 << "\t is SEAM (reverse) of the previous. "
811 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
812 << " = " << otherSeamParam << endl;
815 else if ( fOri == TopAbs_INTERNAL )
817 swap (seg[0], seg[1]);
818 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
819 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
820 ngMesh.AddSegment (seg);
822 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
826 } // loop on geomEdge ancestors
829 } // case TopAbs_EDGE
831 case TopAbs_FACE: { // FACE
832 // ----------------------
833 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
834 helper.SetSubShape( geomFace );
835 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
837 // Find solids the geomFace bounds
838 int solidID1 = 0, solidID2 = 0;
839 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
840 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
843 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
847 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
848 while ( const TopoDS_Shape * solid = solidIt->next() )
850 int id = occgeom.somap.FindIndex ( *solid );
851 if ( solidID1 && id != solidID1 ) solidID2 = id;
855 // Add ng face descriptors of meshed faces
857 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
859 // if second oreder is required, even already meshed faces must be passed to NETGEN
860 int fID = occgeom.fmap.Add( geomFace );
861 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
862 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
863 // Problem with the second order in a quadrangular mesh remains.
864 // 1) All quadrangles geberated by NETGEN are moved to an inexistent face
865 // by FillSMesh() (find AddFaceDescriptor)
866 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
867 // are on faces where quadrangles were.
868 // Due to these 2 points, wrong geom faces are used while conversion to qudratic
869 // of the mentioned above quadrangles and triangles
871 // Orient the face correctly in solidID1 (issue 0020206)
872 bool reverse = false;
874 TopoDS_Shape solid = occgeom.somap( solidID1 );
875 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
876 if ( faceOriInSolid >= 0 )
878 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
881 // Add surface elements
883 netgen::Element2d tri(3);
884 tri.SetIndex ( faceNgID );
887 #ifdef DUMP_TRIANGLES
888 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
889 << " internal="<<isInternalFace << endl;
892 smDS = proxyMesh->GetSubMesh( geomFace );
894 SMDS_ElemIteratorPtr faces = smDS->GetElements();
895 while ( faces->more() )
897 const SMDS_MeshElement* f = faces->next();
898 if ( f->NbNodes() % 3 != 0 ) // not triangle
900 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
901 if ( const TopoDS_Shape * solid = solidIt->next() )
902 sm = _mesh->GetSubMesh( *solid );
903 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
904 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
905 smError->myBadElements.push_back( f );
909 for ( int i = 0; i < 3; ++i )
911 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
913 // get node UV on face
914 int shapeID = node->getshapeId();
915 if ( helper.IsSeamShape( shapeID ))
916 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
917 inFaceNode = f->GetNodeWrap( i-1 );
919 inFaceNode = f->GetNodeWrap( i+1 );
920 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
922 int ind = reverse ? 3-i : i+1;
923 tri.GeomInfoPi(ind).u = uv.X();
924 tri.GeomInfoPi(ind).v = uv.Y();
925 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
928 ngMesh.AddSurfaceElement (tri);
929 #ifdef DUMP_TRIANGLES
933 if ( isInternalFace )
935 swap( tri[1], tri[2] );
936 ngMesh.AddSurfaceElement (tri);
937 #ifdef DUMP_TRIANGLES
943 } // case TopAbs_FACE
945 case TopAbs_VERTEX: { // VERTEX
946 // --------------------------
947 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
948 // else netgen removes a free node and nodeVector becomes invalid
949 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
953 while ( const TopoDS_Shape* e = ansIt->next() )
955 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
956 if (( toAdd = eSub->IsEmpty() )) break;
960 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
961 if ( nodeIt->more() )
962 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
968 } // loop on submeshes
971 nodeVec.resize( ngMesh.GetNP() + 1 );
972 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
973 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
974 nodeVec[ node_NgId->second ] = node_NgId->first;
979 //================================================================================
981 * \brief Duplicate mesh faces on internal geom faces
983 //================================================================================
985 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
986 netgen::Mesh& ngMesh,
987 NETGENPlugin_Internals& internalShapes)
989 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
991 // find ng indices of internal faces
993 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
995 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
996 if ( internalShapes.isInternalShape( smeshID ))
997 ngFaceIds.insert( ngFaceID );
999 if ( !ngFaceIds.empty() )
1002 int i, nbFaces = ngMesh.GetNSE();
1003 for (int i = 1; i <= nbFaces; ++i)
1005 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1006 if ( ngFaceIds.count( elem.GetIndex() ))
1008 swap( elem[1], elem[2] );
1009 ngMesh.AddSurfaceElement (elem);
1017 //================================================================================
1018 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1019 gp_XY_FunPtr(Subtracted);
1020 //gp_XY_FunPtr(Added);
1022 //================================================================================
1024 * \brief Evaluate distance between two 2d points along the surface
1026 //================================================================================
1028 double evalDist( const gp_XY& uv1,
1030 const Handle(Geom_Surface)& surf,
1031 const int stopHandler=-1)
1033 if ( stopHandler > 0 ) // continue recursion
1035 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1036 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1038 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1039 if ( stopHandler == 0 ) // stop recursion
1042 // start recursion if necessary
1043 double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1044 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1045 return dist3D; // equal parametrization of a planar surface
1047 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1050 //================================================================================
1052 * \brief Data of vertex internal in geom face
1054 //================================================================================
1058 gp_XY uv; //!< UV in face parametric space
1059 int ngId; //!< ng id of corrsponding node
1060 gp_XY uvClose; //!< UV of closest boundary node
1061 int ngIdClose; //!< ng id of closest boundary node
1064 //================================================================================
1066 * \brief Data of vertex internal in solid
1068 //================================================================================
1072 int ngId; //!< ng id of corresponding node
1073 int ngIdClose; //!< ng id of closest 2d mesh element
1074 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1077 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1079 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1083 //================================================================================
1085 * \brief Make netgen take internal vertices in faces into account by adding
1086 * segments including internal vertices
1088 * This function works in supposition that 1D mesh is already computed in ngMesh
1090 //================================================================================
1092 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1093 netgen::Mesh& ngMesh,
1094 vector<const SMDS_MeshNode*>& nodeVec,
1095 NETGENPlugin_Internals& internalShapes)
1097 if ( nodeVec.size() < ngMesh.GetNP() )
1098 nodeVec.resize( ngMesh.GetNP(), 0 );
1100 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1101 SMESH_MesherHelper helper( internalShapes.getMesh() );
1103 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1104 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1105 for ( ; f2v != face2Vert.end(); ++f2v )
1107 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1108 if ( face.IsNull() ) continue;
1109 int faceNgID = occgeom.fmap.FindIndex (face);
1110 if ( faceNgID < 0 ) continue;
1112 TopLoc_Location loc;
1113 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1115 helper.SetSubShape( face );
1116 helper.SetElementsOnShape( true );
1118 // Get data of internal vertices and add them to ngMesh
1120 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1122 int i, nbSegInit = ngMesh.GetNSeg();
1124 // boundary characteristics
1125 double totSegLen2D = 0;
1128 const list<int>& iVertices = f2v->second;
1129 list<int>::const_iterator iv = iVertices.begin();
1130 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1133 // get node on vertex
1134 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1135 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1138 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1139 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1140 nV = SMESH_Algo::VertexNode( V, meshDS );
1141 if ( !nV ) continue;
1144 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1145 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1146 vData.ngId = ngMesh.GetNP();
1147 nodeVec.push_back( nV );
1151 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1152 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1154 // loop on all segments of the face to find the node closest to vertex and to count
1155 // average segment 2d length
1156 double closeDist2 = numeric_limits<double>::max(), dist2;
1158 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1160 netgen::Segment & seg = ngMesh.LineSegment(i);
1161 if ( seg.si != faceNgID ) continue;
1163 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1165 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1166 if ( ngIdLast == seg[ iEnd ] ) continue;
1167 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1168 if ( dist2 < closeDist2 )
1169 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1170 ngIdLast = seg[ iEnd ];
1174 totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1178 dist2VData.insert( make_pair( closeDist2, vData ));
1181 if ( totNbSeg == 0 ) break;
1182 double avgSegLen2d = totSegLen2D / totNbSeg;
1184 // Loop on vertices to add segments
1186 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1187 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1189 double closeDist2 = dist_vData->first, dist2;
1190 TIntVData & vData = dist_vData->second;
1192 // try to find more close node among segments added for internal vertices
1193 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1195 netgen::Segment & seg = ngMesh.LineSegment(i);
1196 if ( seg.si != faceNgID ) continue;
1198 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1200 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1201 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1202 if ( dist2 < closeDist2 )
1203 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1206 // decide whether to use the closest node as the second end of segment or to
1207 // create a new point
1208 int segEnd1 = vData.ngId;
1209 int segEnd2 = vData.ngIdClose; // to use closest node
1210 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1211 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1212 double nodeDist2D = sqrt( closeDist2 );
1213 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1214 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1215 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1216 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1217 if ( hintLenOK || avgLenOK )
1219 // create a point between the closest node and V
1222 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1223 // direction from V to closet node in 2D
1224 gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1226 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1227 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1229 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1230 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1231 segEnd2 = ngMesh.GetNP();
1232 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1233 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1234 nodeVec.push_back( nP );
1236 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1239 netgen::Segment seg;
1241 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1242 seg[0] = segEnd1; // ng node id
1243 seg[1] = segEnd2; // ng node id
1244 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1247 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1248 seg.epgeominfo[ 0 ].u = uvV.X();
1249 seg.epgeominfo[ 0 ].v = uvV.Y();
1250 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1251 seg.epgeominfo[ 1 ].u = uvP.X();
1252 seg.epgeominfo[ 1 ].v = uvP.Y();
1254 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1255 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1257 ngMesh.AddSegment (seg);
1259 // add reverse segment
1260 swap (seg[0], seg[1]);
1261 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1262 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1263 ngMesh.AddSegment (seg);
1269 //================================================================================
1271 * \brief Make netgen take internal vertices in solids into account by adding
1272 * faces including internal vertices
1274 * This function works in supposition that 2D mesh is already computed in ngMesh
1276 //================================================================================
1278 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1279 netgen::Mesh& ngMesh,
1280 vector<const SMDS_MeshNode*>& nodeVec,
1281 NETGENPlugin_Internals& internalShapes)
1283 #ifdef DUMP_TRIANGLES_SCRIPT
1284 // create a python script making a mesh containing triangles added for internal vertices
1285 ofstream py(DUMP_TRIANGLES_SCRIPT);
1286 py << "import SMESH"<< endl
1287 << "from salome.smesh import smeshBuilder"<<endl
1288 << "smesh = smeshBuilder.New(salome.myStudy)"
1289 << "m = smesh.Mesh(name='triangles')" << endl;
1291 if ( nodeVec.size() < ngMesh.GetNP() )
1292 nodeVec.resize( ngMesh.GetNP(), 0 );
1294 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1295 SMESH_MesherHelper helper( internalShapes.getMesh() );
1297 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1298 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1299 for ( ; s2v != so2Vert.end(); ++s2v )
1301 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1302 if ( solid.IsNull() ) continue;
1303 int solidNgID = occgeom.somap.FindIndex (solid);
1304 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1306 helper.SetSubShape( solid );
1307 helper.SetElementsOnShape( true );
1309 // find ng indices of faces within the solid
1311 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1312 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1313 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1314 ngFaceIds.insert( 1 );
1316 // Get data of internal vertices and add them to ngMesh
1318 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1320 int i, nbFaceInit = ngMesh.GetNSE();
1322 // boundary characteristics
1323 double totSegLen = 0;
1326 const list<int>& iVertices = s2v->second;
1327 list<int>::const_iterator iv = iVertices.begin();
1328 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1331 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1333 // get node on vertex
1334 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1337 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1338 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1339 nV = SMESH_Algo::VertexNode( V, meshDS );
1340 if ( !nV ) continue;
1343 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1344 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1345 vData.ngId = ngMesh.GetNP();
1346 nodeVec.push_back( nV );
1348 // loop on all 2d elements to find the one closest to vertex and to count
1349 // average segment length
1350 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1351 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1353 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1354 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1356 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1357 for ( int j = 0; j < elem.GetNP(); ++j)
1359 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1360 double d2 = dist2( mpV, mp );
1361 dist2nID.insert( make_pair( d2, elem[j] ));
1362 avgDist2 += d2 / elem.GetNP();
1364 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1366 double dist = dist2nID.begin()->first; //avgDist2;
1367 if ( dist < closeDist2 )
1368 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1370 dist2VData.insert( make_pair( closeDist2, vData ));
1373 if ( totNbSeg == 0 ) break;
1374 double avgSegLen = totSegLen / totNbSeg;
1376 // Loop on vertices to add triangles
1378 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1379 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1381 double closeDist2 = dist_vData->first;
1382 TIntVSoData & vData = dist_vData->second;
1384 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1386 // try to find more close face among ones added for internal vertices
1387 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1389 double avgDist2 = 0;
1390 multimap< double, int> dist2nID;
1391 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1392 for ( int j = 0; j < elem.GetNP(); ++j)
1394 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1395 dist2nID.insert( make_pair( d, elem[j] ));
1396 avgDist2 += d / elem.GetNP();
1397 if ( avgDist2 < closeDist2 )
1398 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1401 // sort nodes of the closest face by angle with vector from V to the closest node
1402 const double tol = numeric_limits<double>::min();
1403 map< double, int > angle2ID;
1404 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1405 netgen::MeshPoint mp[2];
1406 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1407 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1408 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1409 gp_Vec v2p1( pV, p1 );
1410 double distN1 = v2p1.Magnitude();
1411 if ( distN1 <= tol ) continue;
1413 for ( int j = 0; j < closeFace.GetNP(); ++j)
1415 mp[1] = ngMesh.Point( closeFace[j] );
1416 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1417 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1419 // get node with angle of 60 degrees or greater
1420 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1421 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1422 const double minAngle = 30. * M_PI / 180.;
1423 const double angle = angle_id->first;
1424 bool angleOK = ( angle > minAngle );
1426 // find points to create a triangle
1427 netgen::Element2d tri(3);
1429 tri[0] = vData.ngId;
1430 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1431 tri[2] = angle_id->second; // to use the node with best angle
1433 // decide whether to use the closest node and the node with best angle or to create new ones
1434 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1436 bool createNew = !angleOK, distOK = true;
1438 int triInd = isBestAngleN ? 2 : 1;
1439 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1444 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1445 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1447 else if ( angle < tol )
1449 v2p1.SetX( v2p1.X() + 1e-3 );
1455 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1456 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1457 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1458 createNew = (createNew || avgLenOK || hintLenOK );
1459 // we create a new node not closer than 0.5 to the closest face
1460 // in order not to clash with other close face
1461 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1462 distFromV = r * distN1;
1466 // create a new point, between the node and the vertex if angleOK
1467 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1468 gp_Vec v2p( pV, p ); v2p.Normalize();
1469 if ( isBestAngleN && !angleOK )
1470 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1472 p = pV + v2p.XYZ() * distFromV;
1474 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1476 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1477 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1478 tri[triInd] = ngMesh.GetNP();
1479 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1482 ngMesh.AddSurfaceElement (tri);
1483 swap( tri[1], tri[2] );
1484 ngMesh.AddSurfaceElement (tri);
1486 #ifdef DUMP_TRIANGLES_SCRIPT
1487 py << "n1 = m.AddNode( "<< mpV.X()<<", "<< mpV.Y()<<", "<< mpV.Z()<<") "<< endl
1488 << "n2 = m.AddNode( "<< mp[0].X()<<", "<< mp[0].Y()<<", "<< mp[0].Z()<<") "<< endl
1489 << "n3 = m.AddNode( "<< mp[1].X()<<", "<< mp[1].Y()<<", "<< mp[1].Z()<<" )" << endl
1490 << "m.AddFace([n1,n2,n3])" << endl;
1492 } // loop on internal vertices of a solid
1494 } // loop on solids with internal vertices
1497 //================================================================================
1499 * \brief Fill netgen mesh with segments of a FACE
1500 * \param ngMesh - netgen mesh
1501 * \param geom - container of OCCT geometry to mesh
1502 * \param wires - data of nodes on FACE boundary
1503 * \param helper - mesher helper holding the FACE
1504 * \param nodeVec - vector of nodes in which node index == netgen ID
1505 * \retval SMESH_ComputeErrorPtr - error description
1507 //================================================================================
1509 SMESH_ComputeErrorPtr
1510 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1511 netgen::OCCGeometry& geom,
1512 const TSideVector& wires,
1513 SMESH_MesherHelper& helper,
1514 vector< const SMDS_MeshNode* > & nodeVec)
1516 // ----------------------------
1517 // Check wires and count nodes
1518 // ----------------------------
1520 for ( int iW = 0; iW < wires.size(); ++iW )
1522 StdMeshers_FaceSidePtr wire = wires[ iW ];
1523 if ( wire->MissVertexNode() )
1525 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1526 // It seems that there is no reason for this limitation
1528 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1530 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1531 if ( uvPtVec.size() != wire->NbPoints() )
1532 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1533 SMESH_Comment("Unexpected nb of points on wire ") << iW
1534 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1535 nbNodes += wire->NbPoints();
1537 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1538 if ( nodeVec.empty() )
1539 nodeVec.push_back( 0 );
1541 // -----------------
1543 // -----------------
1545 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1546 NETGENPlugin_NETGEN_2D_ONLY */
1548 // map for nodes on vertices since they can be shared between wires
1549 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1550 map<const SMDS_MeshNode*, int > node2ngID;
1551 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1553 set< int > subIDs; // ids of sub-shapes of the FACE
1554 for ( int iW = 0; iW < wires.size(); ++iW )
1556 StdMeshers_FaceSidePtr wire = wires[ iW ];
1557 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1559 subIDs.insert( wire->EdgeID( iE ));
1560 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1563 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1564 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1565 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1568 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1569 if ( ngMesh.GetNFD() < 1 )
1570 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0));
1572 for ( int iW = 0; iW < wires.size(); ++iW )
1574 StdMeshers_FaceSidePtr wire = wires[ iW ];
1575 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1576 const int nbSegments = wire->NbPoints() - 1;
1578 // assure the 1st node to be in node2ngID, which is needed to correctly
1579 // "close chain of segments" (see below) in case if the 1st node is not
1580 // onVertex because it is on a Viscous layer
1581 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1583 // compute length of every segment
1584 vector<double> segLen( nbSegments );
1585 for ( int i = 0; i < nbSegments; ++i )
1586 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1588 int edgeID = 1, posID = -2;
1589 bool isInternalWire = false;
1590 double vertexNormPar = 0;
1591 const int prevNbNGSeg = ngMesh.GetNSeg();
1592 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1594 // Add the first point of a segment
1596 const SMDS_MeshNode * n = uvPtVec[ i ].node;
1597 const int posShapeID = n->getshapeId();
1598 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1599 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
1601 // skip nodes on degenerated edges
1602 if ( helper.IsDegenShape( posShapeID ) &&
1603 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1606 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1607 if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1608 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1609 if ( ngID1 > ngMesh.GetNP() )
1611 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1612 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1613 nodeVec.push_back( n );
1615 else // n is in ngMesh already, and ngID2 in prev segment is wrong
1617 ngID2 = ngMesh.GetNP() + 1;
1618 if ( i > 0 ) // prev segment belongs to same wire
1620 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1627 netgen::Segment seg;
1629 seg[0] = ngID1; // ng node id
1630 seg[1] = ngID2; // ng node id
1631 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1632 seg.si = faceID; // = geom.fmap.FindIndex (face);
1634 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1636 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1638 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1639 seg.epgeominfo[ iEnd ].u = pnt.u;
1640 seg.epgeominfo[ iEnd ].v = pnt.v;
1642 // find out edge id and node parameter on edge
1643 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1644 if ( onVertex || posShapeID != posID )
1647 double normParam = pnt.normParam;
1649 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1650 int edgeIndexInWire = wire->EdgeIndex( normParam );
1651 vertexNormPar = wire->LastParameter( edgeIndexInWire );
1652 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1653 edgeID = geom.emap.FindIndex( edge );
1655 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1656 // if ( onVertex ) // param on curve is different on each of two edges
1657 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1659 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1662 ngMesh.AddSegment (seg);
1664 // restrict size of elements near the segment
1665 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1666 // get an average size of adjacent segments to avoid sharp change of
1667 // element size (regression on issue 0020452, note 0010898)
1668 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1669 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1670 double sunH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
1671 int nbSeg = ( segLen[ iPrev ] > sunH / 100. +
1672 segLen[ i ] > sunH / 100. +
1673 segLen[ iNext ] > sunH / 100.);
1674 double avgH = sunH / nbSeg;
1676 RestrictLocalSize( ngMesh, 0.5*(np1+np2), avgH );
1678 if ( isInternalWire )
1680 swap (seg[0], seg[1]);
1681 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1682 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1683 ngMesh.AddSegment (seg);
1685 } // loop on segments on a wire
1687 // close chain of segments
1688 if ( nbSegments > 0 )
1690 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1691 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1692 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1693 if ( lastSeg[1] > ngMesh.GetNP() )
1695 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1696 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1697 nodeVec.push_back( lastNode );
1699 if ( isInternalWire )
1701 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1702 realLastSeg[0] = lastSeg[1];
1706 #ifdef DUMP_SEGMENTS
1707 cout << "BEGIN WIRE " << iW << endl;
1708 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1710 netgen::Segment& seg = ngMesh.LineSegment( i );
1712 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1713 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1715 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1719 cout << "Segment: " << seg.edgenr << endl
1720 << "\tp1: " << seg[0] << endl
1721 << "\tp2: " << seg[1] << endl
1722 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1723 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1724 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1725 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1726 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1727 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1729 cout << "--END WIRE " << iW << endl;
1732 } // loop on WIREs of a FACE
1734 // add a segment instead of an internal vertex
1735 if ( wasNgMeshEmpty )
1737 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1738 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1740 ngMesh.CalcSurfacesOfNode();
1745 //================================================================================
1747 * \brief Fill SMESH mesh according to contents of netgen mesh
1748 * \param occgeo - container of OCCT geometry to mesh
1749 * \param ngMesh - netgen mesh
1750 * \param initState - bn of entities in netgen mesh before computing
1751 * \param sMesh - SMESH mesh to fill in
1752 * \param nodeVec - vector of nodes in which node index == netgen ID
1753 * \retval int - error
1755 //================================================================================
1757 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1758 netgen::Mesh& ngMesh,
1759 const NETGENPlugin_ngMeshInfo& initState,
1761 std::vector<const SMDS_MeshNode*>& nodeVec,
1762 SMESH_Comment& comment)
1764 int nbNod = ngMesh.GetNP();
1765 int nbSeg = ngMesh.GetNSeg();
1766 int nbFac = ngMesh.GetNSE();
1767 int nbVol = ngMesh.GetNE();
1769 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1771 // -------------------------------------
1772 // Create and insert nodes into nodeVec
1773 // -------------------------------------
1775 nodeVec.resize( nbNod + 1 );
1776 int i, nbInitNod = initState._nbNodes;
1777 for (i = nbInitNod+1; i <= nbNod; ++i )
1779 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1780 SMDS_MeshNode* node = NULL;
1781 TopoDS_Vertex aVert;
1782 // First, netgen creates nodes on vertices in occgeo.vmap,
1783 // so node index corresponds to vertex index
1784 // but (issue 0020776) netgen does not create nodes with equal coordinates
1785 if ( i-nbInitNod <= occgeo.vmap.Extent() )
1787 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1788 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1790 aVert = TopoDS::Vertex( occgeo.vmap( iV ) );
1791 gp_Pnt pV = BRep_Tool::Pnt( aVert );
1792 if ( p.SquareDistance( pV ) > 1e-20 )
1795 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1798 if (!node) // node not found on vertex
1800 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1801 if (!aVert.IsNull())
1802 meshDS->SetNodeOnVertex(node, aVert);
1807 // -------------------------------------------
1808 // Create mesh segments along geometric edges
1809 // -------------------------------------------
1811 int nbInitSeg = initState._nbSegments;
1812 for (i = nbInitSeg+1; i <= nbSeg; ++i )
1814 const netgen::Segment& seg = ngMesh.LineSegment(i);
1816 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1819 for (int j=0; j < 3; ++j)
1821 int pind = pinds[j];
1822 if (pind <= 0 || !nodeVec_ACCESS(pind))
1830 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1831 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1832 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1834 param = seg.epgeominfo[j].dist;
1837 else // middle point
1839 param = param2 * 0.5;
1841 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1843 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1848 SMDS_MeshEdge* edge = 0;
1849 if (nbp == 2) // second order ?
1851 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1853 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1857 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1858 nodeVec_ACCESS(pinds[2])))
1860 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1861 nodeVec_ACCESS(pinds[2]));
1865 if ( comment.empty() ) comment << "Cannot create a mesh edge";
1866 MESSAGE("Cannot create a mesh edge");
1867 nbSeg = nbFac = nbVol = 0;
1870 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1871 meshDS->SetMeshElementOnShape(edge, aEdge);
1873 else if ( comment.empty() )
1875 comment << "Invalid netgen segment #" << i;
1879 // ----------------------------------------
1880 // Create mesh faces along geometric faces
1881 // ----------------------------------------
1883 int nbInitFac = initState._nbFaces;
1884 int quadFaceID = ngMesh.GetNFD() + 1;
1885 if ( nbInitFac < nbFac )
1886 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1887 // from computation of 3D mesh
1888 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1890 for (i = nbInitFac+1; i <= nbFac; ++i )
1892 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1893 int aGeomFaceInd = elem.GetIndex();
1895 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
1896 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
1897 vector<SMDS_MeshNode*> nodes;
1898 for (int j=1; j <= elem.GetNP(); ++j)
1900 int pind = elem.PNum(j);
1901 if ( pind < 1 || pind >= nodeVec.size() )
1903 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
1905 nodes.push_back(node);
1906 if (!aFace.IsNull() && node->getshapeId() < 1)
1908 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
1909 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
1913 if ( nodes.size() != elem.GetNP() )
1915 if ( comment.empty() )
1916 comment << "Invalid netgen 2d element #" << i;
1917 continue; // bad node ids
1919 SMDS_MeshFace* face = NULL;
1920 switch (elem.GetType())
1923 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
1926 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
1927 // exclude qudrangle elements from computation of 3D mesh
1928 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1931 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
1934 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
1935 nodes[4],nodes[7],nodes[5],nodes[6]);
1936 // exclude qudrangle elements from computation of 3D mesh
1937 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1940 MESSAGE("NETGEN created a face of unexpected type, ignoring");
1945 if ( comment.empty() ) comment << "Cannot create a mesh face";
1946 MESSAGE("Cannot create a mesh face");
1947 nbSeg = nbFac = nbVol = 0;
1950 if (!aFace.IsNull())
1951 meshDS->SetMeshElementOnShape(face, aFace);
1954 // ------------------
1955 // Create tetrahedra
1956 // ------------------
1958 for (i = 1; i <= nbVol; ++i)
1960 const netgen::Element& elem = ngMesh.VolumeElement(i);
1961 int aSolidInd = elem.GetIndex();
1962 TopoDS_Solid aSolid;
1963 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
1964 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
1965 vector<SMDS_MeshNode*> nodes;
1966 for (int j=1; j <= elem.GetNP(); ++j)
1968 int pind = elem.PNum(j);
1969 if ( pind < 1 || pind >= nodeVec.size() )
1971 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
1973 nodes.push_back(node);
1974 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
1975 meshDS->SetNodeInVolume(node, aSolid);
1978 if ( nodes.size() != elem.GetNP() )
1980 if ( comment.empty() )
1981 comment << "Invalid netgen 3d element #" << i;
1984 SMDS_MeshVolume* vol = NULL;
1985 switch (elem.GetType())
1988 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
1991 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
1992 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
1995 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2000 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2001 MESSAGE("Cannot create a mesh volume");
2002 nbSeg = nbFac = nbVol = 0;
2005 if (!aSolid.IsNull())
2006 meshDS->SetMeshElementOnShape(vol, aSolid);
2008 return comment.empty() ? 0 : 1;
2013 //================================================================================
2015 * \brief Restrict size of elements on the given edge
2017 //================================================================================
2019 void setLocalSize(const TopoDS_Edge& edge,
2023 const int nb = 1000;
2024 Standard_Real u1, u2;
2025 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
2026 if ( curve.IsNull() )
2028 TopoDS_Iterator vIt( edge );
2029 if ( !vIt.More() ) return;
2030 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
2031 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2035 Standard_Real delta = (u2-u1)/nb;
2036 for(int i=0; i<nb; i++)
2038 Standard_Real u = u1 + delta*i;
2039 gp_Pnt p = curve->Value(u);
2040 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2041 netgen::Point3d pi(p.X(), p.Y(), p.Z());
2042 double resultSize = mesh.GetH(pi);
2043 if ( resultSize - size > 0.1*size )
2044 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2045 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2050 //================================================================================
2052 * \brief Convert error into text
2054 //================================================================================
2056 std::string text(int err)
2061 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2064 //================================================================================
2066 * \brief Convert exception into text
2068 //================================================================================
2070 std::string text(Standard_Failure& ex)
2072 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2073 str << " at " << netgen::multithread.task
2074 << ": " << ex.DynamicType()->Name();
2075 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2076 str << ": " << ex.GetMessageString();
2079 //================================================================================
2081 * \brief Convert exception into text
2083 //================================================================================
2085 std::string text(netgen::NgException& ex)
2087 SMESH_Comment str("NgException");
2088 if ( strlen( netgen::multithread.task ) > 0 )
2089 str << " at " << netgen::multithread.task;
2090 str << ": " << ex.What();
2094 const double edgeMeshingTime = 0.001;
2095 const double faceMeshingTime = 0.019;
2096 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2097 const double faceOptimizTime = 0.06;
2098 const double voluMeshingTime = 0.15;
2099 const double volOptimizeTime = 0.77;
2102 //=============================================================================
2104 * Here we are going to use the NETGEN mesher
2106 //=============================================================================
2108 bool NETGENPlugin_Mesher::Compute()
2110 NETGENPlugin_NetgenLibWrapper ngLib;
2112 netgen::MeshingParameters& mparams = netgen::mparam;
2113 MESSAGE("Compute with:\n"
2114 " max size = " << mparams.maxh << "\n"
2115 " segments per edge = " << mparams.segmentsperedge);
2117 " growth rate = " << mparams.grading << "\n"
2118 " elements per radius = " << mparams.curvaturesafety << "\n"
2119 " second order = " << mparams.secondorder << "\n"
2120 " quad allowed = " << mparams.quad);
2121 //cout << " quad allowed = " << mparams.quad<<endl;
2123 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2125 static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( ngMesh, debugFile )
2126 while debugging netgen */
2127 // -------------------------
2128 // Prepare OCC geometry
2129 // -------------------------
2131 netgen::OCCGeometry occgeo;
2132 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2133 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2134 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2137 _totalTime = edgeFaceMeshingTime;
2139 _totalTime += faceOptimizTime;
2141 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2142 double doneTime = 0;
2145 _curShapeIndex = -1;
2147 // -------------------------
2148 // Generate the mesh
2149 // -------------------------
2152 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2154 SMESH_Comment comment;
2157 // vector of nodes in which node index == netgen ID
2158 vector< const SMDS_MeshNode* > nodeVec;
2166 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2167 mparams.uselocalh = false;
2168 mparams.grading = 0.8; // not limitited size growth
2170 if ( _simpleHyp->GetNumberOfSegments() )
2172 mparams.maxh = occgeo.boundingbox.Diam();
2175 mparams.maxh = _simpleHyp->GetLocalLength();
2178 if ( mparams.maxh == 0.0 )
2179 mparams.maxh = occgeo.boundingbox.Diam();
2180 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2181 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2183 // Local size on faces
2184 occgeo.face_maxh = mparams.maxh;
2186 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2190 int startWith = netgen::MESHCONST_ANALYSE;
2191 int endWith = netgen::MESHCONST_ANALYSE;
2196 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2198 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2200 if(netgen::multithread.terminate)
2203 comment << text(err);
2205 catch (Standard_Failure& ex)
2207 comment << text(ex);
2209 err = 0; //- MESHCONST_ANALYSE isn't so important step
2212 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2214 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2218 // Pass 1D simple parameters to NETGEN
2219 // --------------------------------
2220 int nbSeg = _simpleHyp->GetNumberOfSegments();
2221 double segSize = _simpleHyp->GetLocalLength();
2222 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2224 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2226 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2227 setLocalSize( e, segSize, *_ngMesh );
2230 else // if ( ! _simpleHyp )
2232 // Local size on vertices and edges
2233 // --------------------------------
2234 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2236 int key = (*it).first;
2237 double hi = (*it).second;
2238 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2239 const TopoDS_Edge& e = TopoDS::Edge(shape);
2240 setLocalSize( e, hi, *_ngMesh );
2242 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2244 int key = (*it).first;
2245 double hi = (*it).second;
2246 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2247 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2248 gp_Pnt p = BRep_Tool::Pnt(v);
2249 NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
2251 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2252 it!=FaceId2LocalSize.end(); it++)
2254 int key = (*it).first;
2255 double val = (*it).second;
2256 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2257 int faceNgID = occgeo.fmap.FindIndex(shape);
2258 occgeo.SetFaceMaxH(faceNgID, val);
2259 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2260 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
2264 // Precompute internal edges (issue 0020676) in order to
2265 // add mesh on them correctly (twice) to netgen mesh
2266 if ( !err && internals.hasInternalEdges() )
2268 // load internal shapes into OCCGeometry
2269 netgen::OCCGeometry intOccgeo;
2270 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2271 intOccgeo.boundingbox = occgeo.boundingbox;
2272 intOccgeo.shape = occgeo.shape;
2273 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2274 intOccgeo.face_maxh = netgen::mparam.maxh;
2275 netgen::Mesh *tmpNgMesh = NULL;
2279 // compute local H on internal shapes in the main mesh
2280 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2282 // let netgen create a temporary mesh
2284 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2286 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2288 if(netgen::multithread.terminate)
2291 // copy LocalH from the main to temporary mesh
2292 initState.transferLocalH( _ngMesh, tmpNgMesh );
2294 // compute mesh on internal edges
2295 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2297 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2299 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2301 comment << text(err);
2303 catch (Standard_Failure& ex)
2305 comment << text(ex);
2308 initState.restoreLocalH( tmpNgMesh );
2310 // fill SMESH by netgen mesh
2311 vector< const SMDS_MeshNode* > tmpNodeVec;
2312 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2313 err = ( err || !comment.empty() );
2315 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2318 // Fill _ngMesh with nodes and segments of computed submeshes
2321 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2322 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
2324 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2329 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2334 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2336 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2338 if(netgen::multithread.terminate)
2341 comment << text(err);
2343 catch (Standard_Failure& ex)
2345 comment << text(ex);
2350 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2352 mparams.uselocalh = true; // restore as it is used at surface optimization
2354 // ---------------------
2355 // compute surface mesh
2356 // ---------------------
2359 // Pass 2D simple parameters to NETGEN
2361 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2363 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2364 mparams.grading = 0.4; // moderate size growth
2367 // length from edges
2368 if ( _ngMesh->GetNSeg() ) {
2369 double edgeLength = 0;
2370 TopTools_MapOfShape visitedEdges;
2371 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2372 if( visitedEdges.Add(exp.Current()) )
2373 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2374 // we have to multiply length by 2 since for each TopoDS_Edge there
2375 // are double set of NETGEN edges, in other words, we have to
2376 // divide _ngMesh->GetNSeg() by 2.
2377 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2380 mparams.maxh = 1000;
2382 mparams.grading = 0.2; // slow size growth
2384 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2385 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2386 _ngMesh->SetGlobalH (mparams.maxh);
2387 netgen::Box<3> bb = occgeo.GetBoundingBox();
2388 bb.Increase (bb.Diam()/20);
2389 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2392 // Care of vertices internal in faces (issue 0020676)
2393 if ( internals.hasInternalVertexInFace() )
2395 // store computed segments in SMESH in order not to create SMESH
2396 // edges for ng segments added by AddIntVerticesInFaces()
2397 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2398 // add segments to faces with internal vertices
2399 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2400 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2403 // Build viscous layers
2404 if ( _isViscousLayers2D )
2406 if ( !internals.hasInternalVertexInFace() ) {
2407 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2408 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2410 SMESH_ProxyMesh::Ptr viscousMesh;
2411 SMESH_MesherHelper helper( *_mesh );
2412 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2414 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2415 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2418 // exclude from computation ng segments built on EDGEs of F
2419 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2421 netgen::Segment & seg = _ngMesh->LineSegment(i);
2422 if (seg.si == faceID)
2425 // add new segments to _ngMesh instead of excluded ones
2426 helper.SetSubShape( F );
2428 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2429 error, viscousMesh );
2430 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2432 if ( !error ) error = SMESH_ComputeError::New();
2434 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2437 // Let netgen compute 2D mesh
2438 startWith = netgen::MESHCONST_MESHSURFACE;
2439 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2444 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2446 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2448 if(netgen::multithread.terminate)
2451 comment << text (err);
2453 catch (Standard_Failure& ex)
2455 comment << text(ex);
2456 //err = 1; -- try to make volumes anyway
2458 catch (netgen::NgException exc)
2460 comment << text(exc);
2461 //err = 1; -- try to make volumes anyway
2466 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2467 _ticTime = doneTime / _totalTime / _progressTic;
2469 // ---------------------
2470 // generate volume mesh
2471 // ---------------------
2472 // Fill _ngMesh with nodes and faces of computed 2D submeshes
2473 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2475 // load SMESH with computed segments and faces
2476 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2478 // compute pyramids on quadrangles
2479 SMESH_ProxyMesh::Ptr proxyMesh;
2480 if ( _mesh->NbQuadrangles() > 0 )
2481 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2483 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2484 proxyMesh.reset( Adaptor );
2486 int nbPyrams = _mesh->NbPyramids();
2487 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2488 if ( nbPyrams != _mesh->NbPyramids() )
2490 list< SMESH_subMesh* > quadFaceSM;
2491 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2492 if ( Adaptor->GetProxySubMesh( face.Current() ))
2494 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2495 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2497 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, proxyMesh);
2500 // fill _ngMesh with faces of sub-meshes
2501 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
2502 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2503 //toPython( _ngMesh, "/tmp/ngPython.py");
2505 if (!err && _isVolume)
2507 // Pass 3D simple parameters to NETGEN
2508 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2509 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2511 if ( double vol = simple3d->GetMaxElementVolume() ) {
2513 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2514 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2517 // length from faces
2518 mparams.maxh = _ngMesh->AverageH();
2520 _ngMesh->SetGlobalH (mparams.maxh);
2521 mparams.grading = 0.4;
2523 _ngMesh->CalcLocalH(mparams.grading);
2525 _ngMesh->CalcLocalH();
2528 // Care of vertices internal in solids and internal faces (issue 0020676)
2529 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2531 // store computed faces in SMESH in order not to create SMESH
2532 // faces for ng faces added here
2533 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2534 // add ng faces to solids with internal vertices
2535 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2536 // duplicate mesh faces on internal faces
2537 FixIntFaces( occgeo, *_ngMesh, internals );
2538 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2540 // Let netgen compute 3D mesh
2541 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2546 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2548 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2550 if(netgen::multithread.terminate)
2553 if ( comment.empty() ) // do not overwrite a previos error
2554 comment << text(err);
2556 catch (Standard_Failure& ex)
2558 if ( comment.empty() ) // do not overwrite a previos error
2559 comment << text(ex);
2562 catch (netgen::NgException exc)
2564 if ( comment.empty() ) // do not overwrite a previos error
2565 comment << text(exc);
2568 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2570 // Let netgen optimize 3D mesh
2571 if ( !err && _optimize )
2573 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2578 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2580 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2582 if(netgen::multithread.terminate)
2585 if ( comment.empty() ) // do not overwrite a previos error
2586 comment << text(err);
2588 catch (Standard_Failure& ex)
2590 if ( comment.empty() ) // do not overwrite a previos error
2591 comment << text(ex);
2593 catch (netgen::NgException exc)
2595 if ( comment.empty() ) // do not overwrite a previos error
2596 comment << text(exc);
2600 if (!err && mparams.secondorder > 0)
2605 netgen::OCCRefinementSurfaces ref (occgeo);
2606 ref.MakeSecondOrder (*_ngMesh);
2608 catch (Standard_Failure& ex)
2610 if ( comment.empty() ) // do not overwrite a previos error
2611 comment << "Exception in netgen at passing to 2nd order ";
2613 catch (netgen::NgException exc)
2615 if ( comment.empty() ) // do not overwrite a previos error
2616 comment << exc.What();
2621 _ticTime = 0.98 / _progressTic;
2623 int nbNod = _ngMesh->GetNP();
2624 int nbSeg = _ngMesh->GetNSeg();
2625 int nbFac = _ngMesh->GetNSE();
2626 int nbVol = _ngMesh->GetNE();
2627 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2629 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2630 ", nb nodes: " << nbNod <<
2631 ", nb segments: " << nbSeg <<
2632 ", nb faces: " << nbFac <<
2633 ", nb volumes: " << nbVol);
2635 // Feed back the SMESHDS with the generated Nodes and Elements
2636 if ( true /*isOK*/ ) // get whatever built
2637 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment ); //!<
2639 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2640 if ( readErr && !readErr->myBadElements.empty() )
2643 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2644 error->myName = COMPERR_ALGO_FAILED;
2645 if ( !comment.empty() )
2646 error->myComment = comment;
2648 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2649 // appear if the geometry contains coincident sub-shape due
2650 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2651 const int nbMaps = 2;
2652 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2653 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2654 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2655 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2656 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2657 if ( !sm->IsMeshComputed() )
2658 sm->SetIsAlwaysComputed( true );
2660 // set bad compute error to subshapes of all failed sub-shapes
2661 if ( !error->IsOK() )
2663 bool pb2D = false, pb3D = false;
2664 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2665 int status = occgeo.facemeshstatus[i-1];
2666 if (status == 1 ) continue;
2667 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2668 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2669 if ( !smError || smError->IsOK() ) {
2671 smError.reset( new SMESH_ComputeError( *error ));
2673 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2674 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2675 smError->myName = COMPERR_WARNING;
2677 pb2D = pb2D || smError->IsKO();
2680 if ( !pb2D ) // all faces are OK
2681 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2682 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2684 bool smComputed = nbVol && !sm->IsEmpty();
2685 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2687 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2688 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2689 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2691 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2692 if ( !smComputed && ( !smError || smError->IsOK() ))
2694 smError.reset( new SMESH_ComputeError( *error ));
2695 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2696 smError->myName = COMPERR_WARNING;
2698 pb3D = pb3D || ( smError && smError->IsKO() );
2700 if ( !pb2D && !pb3D )
2701 err = 0; // no fatal errors, only warnings
2704 ngLib._isComputeOk = !err;
2709 //=============================================================================
2713 //=============================================================================
2714 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2716 netgen::MeshingParameters& mparams = netgen::mparam;
2719 // -------------------------
2720 // Prepare OCC geometry
2721 // -------------------------
2722 netgen::OCCGeometry occgeo;
2723 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2724 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2725 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2727 bool tooManyElems = false;
2728 const int hugeNb = std::numeric_limits<int>::max() / 100;
2733 // pass 1D simple parameters to NETGEN
2736 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2737 mparams.uselocalh = false;
2738 mparams.grading = 0.8; // not limitited size growth
2740 if ( _simpleHyp->GetNumberOfSegments() )
2742 mparams.maxh = occgeo.boundingbox.Diam();
2745 mparams.maxh = _simpleHyp->GetLocalLength();
2748 if ( mparams.maxh == 0.0 )
2749 mparams.maxh = occgeo.boundingbox.Diam();
2750 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2751 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2753 // let netgen create _ngMesh and calculate element size on not meshed shapes
2754 NETGENPlugin_NetgenLibWrapper ngLib;
2755 netgen::Mesh *ngMesh = NULL;
2759 int startWith = netgen::MESHCONST_ANALYSE;
2760 int endWith = netgen::MESHCONST_MESHEDGES;
2762 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2764 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2767 if(netgen::multithread.terminate)
2770 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2772 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2773 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2778 // Pass 1D simple parameters to NETGEN
2779 // --------------------------------
2780 int nbSeg = _simpleHyp->GetNumberOfSegments();
2781 double segSize = _simpleHyp->GetLocalLength();
2782 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2784 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2786 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2787 setLocalSize( e, segSize, *ngMesh );
2790 else // if ( ! _simpleHyp )
2792 // Local size on vertices and edges
2793 // --------------------------------
2794 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2796 int key = (*it).first;
2797 double hi = (*it).second;
2798 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2799 const TopoDS_Edge& e = TopoDS::Edge(shape);
2800 setLocalSize( e, hi, *ngMesh );
2802 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2804 int key = (*it).first;
2805 double hi = (*it).second;
2806 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2807 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2808 gp_Pnt p = BRep_Tool::Pnt(v);
2809 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2811 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2812 it!=FaceId2LocalSize.end(); it++)
2814 int key = (*it).first;
2815 double val = (*it).second;
2816 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2817 int faceNgID = occgeo.fmap.FindIndex(shape);
2818 occgeo.SetFaceMaxH(faceNgID, val);
2819 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2820 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2823 // calculate total nb of segments and length of edges
2824 double fullLen = 0.0;
2826 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
2827 TopTools_DataMapOfShapeInteger Edge2NbSeg;
2828 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
2830 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2831 if( !Edge2NbSeg.Bind(E,0) )
2834 double aLen = SMESH_Algo::EdgeLength(E);
2837 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
2839 aVec.resize( SMDSEntity_Last, 0);
2841 fullNbSeg += aVec[ entity ];
2844 // store nb of segments computed by Netgen
2845 NCollection_Map<Link> linkMap;
2846 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
2848 const netgen::Segment& seg = ngMesh->LineSegment(i);
2849 Link link(seg[0], seg[1]);
2850 if ( !linkMap.Add( link )) continue;
2851 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
2852 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2854 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
2858 // store nb of nodes on edges computed by Netgen
2859 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
2860 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
2862 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
2863 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
2864 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
2866 fullNbSeg += aVec[ entity ];
2867 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
2869 if ( fullNbSeg == 0 )
2876 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2878 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2879 mparams.grading = 0.4; // moderate size growth
2882 // length from edges
2883 mparams.maxh = fullLen/fullNbSeg;
2884 mparams.grading = 0.2; // slow size growth
2887 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2888 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2890 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
2892 TopoDS_Face F = TopoDS::Face( exp.Current() );
2893 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
2895 BRepGProp::SurfaceProperties(F,G);
2896 double anArea = G.Mass();
2897 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
2899 if ( !tooManyElems )
2901 TopTools_MapOfShape egdes;
2902 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
2903 if ( egdes.Add( exp1.Current() ))
2904 nb1d += Edge2NbSeg.Find(exp1.Current());
2906 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
2907 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
2909 vector<int> aVec(SMDSEntity_Last, 0);
2910 if( mparams.secondorder > 0 ) {
2911 int nb1d_in = (nbFaces*3 - nb1d) / 2;
2912 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2913 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
2916 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
2917 aVec[SMDSEntity_Triangle] = nbFaces;
2919 aResMap[sm].swap(aVec);
2926 // pass 3D simple parameters to NETGEN
2927 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2928 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2930 if ( double vol = simple3d->GetMaxElementVolume() ) {
2932 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2933 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2936 // using previous length from faces
2938 mparams.grading = 0.4;
2939 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2942 BRepGProp::VolumeProperties(_shape,G);
2943 double aVolume = G.Mass();
2944 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
2945 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
2946 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
2947 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2948 vector<int> aVec(SMDSEntity_Last, 0 );
2949 if ( tooManyElems ) // avoid FPE
2951 aVec[SMDSEntity_Node] = hugeNb;
2952 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
2956 if( mparams.secondorder > 0 ) {
2957 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2958 aVec[SMDSEntity_Quad_Tetra] = nbVols;
2961 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2962 aVec[SMDSEntity_Tetra] = nbVols;
2965 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
2966 aResMap[sm].swap(aVec);
2972 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
2973 const int * algoProgressTic,
2974 const double * algoProgress) const
2976 ((int&) _progressTic ) = *algoProgressTic + 1;
2978 if ( !_occgeom ) return 0;
2980 double progress = -1;
2983 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
2985 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
2987 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
2989 int doneShapeIndex = -1;
2990 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
2991 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
2993 if ( doneShapeIndex+1 != _curShapeIndex )
2995 ((int&) _curShapeIndex) = doneShapeIndex+1;
2996 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
2997 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
2998 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
2999 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3000 // << " " << doneTime / _totalTime / _progressTic << endl;
3004 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3006 int curShapeIndex = _curShapeIndex;
3007 if ( _ngMesh->GetNE() > 0 )
3009 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3010 curShapeIndex = el.GetIndex();
3012 if ( curShapeIndex != _curShapeIndex )
3014 ((int&) _curShapeIndex) = curShapeIndex;
3015 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3016 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3017 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3018 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3019 // << " " << doneTime / _totalTime / _progressTic << endl;
3023 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3026 ((int&) *algoProgressTic )++;
3027 ((double&) *algoProgress) = progress;
3029 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3031 return Min( progress, 0.99 );
3034 //================================================================================
3036 * \brief Remove "test.out" and "problemfaces" files in current directory
3038 //================================================================================
3040 void NETGENPlugin_Mesher::RemoveTmpFiles()
3042 bool rm = SMESH_File("test.out").remove() ;
3044 if (rm && netgen::testout)
3046 delete netgen::testout;
3047 netgen::testout = 0;
3050 SMESH_File("problemfaces").remove();
3051 SMESH_File("occmesh.rep").remove();
3054 //================================================================================
3056 * \brief Read mesh entities preventing successful computation from "test.out" file
3058 //================================================================================
3060 SMESH_ComputeErrorPtr
3061 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3063 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3064 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3065 SMESH_File file("test.out");
3067 const char* badEdgeStr = " multiple times in surface mesh";
3068 const int badEdgeStrLen = strlen( badEdgeStr );
3069 while( !file.eof() )
3071 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3072 file.getInts( two ) &&
3073 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3074 two[0] < nodeVec.size() && two[1] < nodeVec.size())
3076 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3077 file += badEdgeStrLen;
3079 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3082 // openelement 18 with open element 126
3085 vector<int> three1(3), three2(3);
3087 const char* pos = file;
3088 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3089 ok = ok && file.getInts( two );
3090 ok = ok && file.getInts( three1 );
3091 ok = ok && file.getInts( three2 );
3092 for ( int i = 0; ok && i < 3; ++i )
3093 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
3094 for ( int i = 0; ok && i < 3; ++i )
3095 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
3098 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3099 nodeVec[ three1[1]],
3100 nodeVec[ three1[2]]));
3101 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3102 nodeVec[ three2[1]],
3103 nodeVec[ three2[2]]));
3104 err->myComment = "Intersecting triangles";
3119 //================================================================================
3121 * \brief Write a python script creating an equivalent SALOME mesh.
3122 * This is useful to see what mesh is passed as input for the next step of mesh
3123 * generation (of mesh of higher dimension)
3125 //================================================================================
3127 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
3128 const std::string& pyFile)
3130 ofstream outfile(pyFile.c_str(), ios::out);
3131 if ( !outfile ) return;
3133 outfile << "import SMESH" << endl
3134 << "from salome.smesh import smeshBuilder" << endl
3135 << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3136 << "mesh = smesh.Mesh()" << endl << endl;
3138 using namespace netgen;
3140 for (pi = PointIndex::BASE;
3141 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3143 outfile << "mesh.AddNode( ";
3144 outfile << (*ngMesh)[pi](0) << ", ";
3145 outfile << (*ngMesh)[pi](1) << ", ";
3146 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3149 int nbDom = ngMesh->GetNDomains();
3150 for ( int i = 0; i < nbDom; ++i )
3151 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3153 SurfaceElementIndex sei;
3154 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3156 outfile << "mesh.AddFace([ ";
3157 Element2d sel = (*ngMesh)[sei];
3158 for (int j = 0; j < sel.GetNP(); j++)
3159 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3160 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3163 if ((*ngMesh)[sei].GetIndex())
3165 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3166 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3167 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3168 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3172 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3174 Element el = (*ngMesh)[ei];
3175 outfile << "mesh.AddVolume([ ";
3176 for (int j = 0; j < el.GetNP(); j++)
3177 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3181 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3183 const Segment & seg = ngMesh->LineSegment (i);
3184 outfile << "mesh.AddEdge([ "
3186 << seg[1] << " ])" << endl;
3188 cout << "Write " << pyFile << endl;
3191 //================================================================================
3193 * \brief Constructor of NETGENPlugin_ngMeshInfo
3195 //================================================================================
3197 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3202 _nbNodes = ngMesh->GetNP();
3203 _nbSegments = ngMesh->GetNSeg();
3204 _nbFaces = ngMesh->GetNSE();
3205 _nbVolumes = ngMesh->GetNE();
3209 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3213 //================================================================================
3215 * \brief Copy LocalH member from one netgen mesh to another
3217 //================================================================================
3219 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3220 netgen::Mesh* toMesh )
3222 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3223 if ( !toMesh->LocalHFunctionGenerated() )
3225 toMesh->CalcLocalH(netgen::mparam.grading);
3227 toMesh->CalcLocalH();
3230 const size_t size = sizeof( netgen::LocalH );
3231 _copyOfLocalH = new char[ size ];
3232 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3233 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3236 //================================================================================
3238 * \brief Restore LocalH member of a netgen mesh
3240 //================================================================================
3242 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3244 if ( _copyOfLocalH )
3246 const size_t size = sizeof( netgen::LocalH );
3247 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3248 delete [] _copyOfLocalH;
3253 //================================================================================
3255 * \brief Find "internal" sub-shapes
3257 //================================================================================
3259 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3260 const TopoDS_Shape& shape,
3262 : _mesh( mesh ), _is3D( is3D )
3264 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3266 TopExp_Explorer f,e;
3267 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3269 int faceID = meshDS->ShapeToIndex( f.Current() );
3271 // find not computed internal edges
3273 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3274 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3276 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3277 if ( eSM->IsEmpty() )
3279 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3280 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3281 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3285 // find internal vertices in a face
3286 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3287 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3288 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3290 int vID = meshDS->ShapeToIndex( fSub.Value() );
3291 if ( intVV.insert( vID ).second )
3292 _f2v[ faceID ].push_back( vID );
3297 // find internal faces and their subshapes where nodes are to be doubled
3298 // to make a crack with non-sewed borders
3300 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3302 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3305 list< TopoDS_Shape > edges;
3306 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3307 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3309 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3310 edges.push_back( e.Current() );
3311 // find border faces
3312 PShapeIteratorPtr fIt =
3313 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3314 while ( const TopoDS_Shape* pFace = fIt->next() )
3315 if ( !pFace->IsSame( f.Current() ))
3316 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3319 // we consider vertex internal if it is shared by more than one internal edge
3320 list< TopoDS_Shape >::iterator edge = edges.begin();
3321 for ( ; edge != edges.end(); ++edge )
3322 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3324 set<int> internalEdges;
3325 PShapeIteratorPtr eIt =
3326 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3327 while ( const TopoDS_Shape* pEdge = eIt->next() )
3329 int edgeID = meshDS->ShapeToIndex( *pEdge );
3330 if ( isInternalShape( edgeID ))
3331 internalEdges.insert( edgeID );
3333 if ( internalEdges.size() > 1 )
3334 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3338 } // loop on geom faces
3340 // find vertices internal in solids
3343 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3345 int soID = meshDS->ShapeToIndex( so.Current() );
3346 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3347 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3348 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3353 //================================================================================
3355 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3356 * some nodes of which are to be doubled to make the second border of the "crack"
3358 //================================================================================
3360 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3362 if ( _intShapes.empty() ) return;
3364 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3365 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3367 // loop on internal geom edges
3368 set<int>::const_iterator intShapeId = _intShapes.begin();
3369 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3371 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3372 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3374 // get internal and non-internal geom faces sharing the internal edge <s>
3376 set<int>::iterator bordFace = _borderFaces.end();
3377 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3378 while ( const TopoDS_Shape* pFace = faces->next() )
3380 int faceID = meshDS->ShapeToIndex( *pFace );
3381 if ( isInternalShape( faceID ))
3384 bordFace = _borderFaces.insert( faceID ).first;
3386 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3388 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3389 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3390 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3391 int nbSuspectFaces = 0;
3392 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3393 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3394 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3395 while ( smIt->more() )
3397 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3398 if ( !sm ) continue;
3399 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3400 while ( nIt->more() )
3402 const SMDS_MeshNode* nOnEdge = nIt->next();
3403 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3404 while ( fIt->more() )
3406 const SMDS_MeshElement* f = fIt->next();
3407 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3408 if ( intFaceSM->Contains( f ))
3410 for ( int i = 0; i < nbNodes; ++i )
3411 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3416 for ( int i = 0; i < nbNodes; ++i )
3417 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3419 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3425 // suspectFaces[0] having link with same orientation as mesh faces on
3426 // the internal geom face are <borderElems>. suspectFaces[1] have
3427 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3428 // by links of <borderElems> found at the 1st and 2nd loops
3429 set< SMESH_OrientedLink > borderLinks;
3430 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3432 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3433 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3435 const SMDS_MeshElement* f = *fIt;
3436 bool isBorder = false, linkFound = false, borderLinkFound = false;
3437 list< SMESH_OrientedLink > faceLinks;
3438 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3439 for ( int i = 0; i < nbNodes; ++i )
3441 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3442 faceLinks.push_back( link );
3445 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3446 if ( foundLink != links.end() )
3449 isBorder = ( foundLink->_reversed == link._reversed );
3450 if ( !isBorder && !isPostponed ) break;
3451 faceLinks.pop_back();
3453 else if ( isPostponed && !borderLinkFound )
3455 foundLink = borderLinks.find( link );
3456 if ( foundLink != borderLinks.end() )
3458 borderLinkFound = true;
3459 isBorder = ( foundLink->_reversed != link._reversed );
3466 borderElems.insert( f );
3467 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3469 else if ( !linkFound && !borderLinkFound )
3471 suspectFaces[1].push_back( f );
3472 if ( nbF > 2 * nbSuspectFaces )
3473 break; // dead loop protection
3480 //================================================================================
3482 * \brief put internal shapes in maps and fill in submeshes to precompute
3484 //================================================================================
3486 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3487 TopTools_IndexedMapOfShape& emap,
3488 TopTools_IndexedMapOfShape& vmap,
3489 list< SMESH_subMesh* > smToPrecompute[])
3491 if ( !hasInternalEdges() ) return;
3492 map<int,int>::const_iterator ev_face = _e2face.begin();
3493 for ( ; ev_face != _e2face.end(); ++ev_face )
3495 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3496 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3498 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3500 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3502 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3506 //================================================================================
3508 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3510 //================================================================================
3512 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3513 TopTools_IndexedMapOfShape& emap,
3514 list< SMESH_subMesh* >& intFaceSM,
3515 list< SMESH_subMesh* >& boundarySM)
3517 if ( !hasInternalFaces() ) return;
3519 // <fmap> and <emap> are for not yet meshed shapes
3520 // <intFaceSM> is for submeshes of faces
3521 // <boundarySM> is for meshed edges and vertices
3526 set<int> shapeIDs ( _intShapes );
3527 if ( !_borderFaces.empty() )
3528 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3530 set<int>::const_iterator intS = shapeIDs.begin();
3531 for ( ; intS != shapeIDs.end(); ++intS )
3533 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3535 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3537 intFaceSM.push_back( sm );
3539 // add submeshes of not computed internal faces
3540 if ( !sm->IsEmpty() ) continue;
3542 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3543 while ( smIt->more() )
3546 const TopoDS_Shape& s = sm->GetSubShape();
3548 if ( sm->IsEmpty() )
3551 switch ( s.ShapeType() ) {
3552 case TopAbs_FACE: fmap.Add ( s ); break;
3553 case TopAbs_EDGE: emap.Add ( s ); break;
3559 if ( s.ShapeType() != TopAbs_FACE )
3560 boundarySM.push_back( sm );
3566 //================================================================================
3568 * \brief Return true if given shape is to be precomputed in order to be correctly
3569 * added to netgen mesh
3571 //================================================================================
3573 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3575 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3576 switch ( s.ShapeType() ) {
3577 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3578 case TopAbs_EDGE : return isInternalEdge( shapeID );
3579 case TopAbs_VERTEX: break;
3585 //================================================================================
3587 * \brief Return SMESH
3589 //================================================================================
3591 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3593 return const_cast<SMESH_Mesh&>( _mesh );
3596 //================================================================================
3598 * \brief Initialize netgen library
3600 //================================================================================
3602 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3606 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3607 _isComputeOk = false;
3608 _outputFileName = getOutputFileName();
3609 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3610 netgen::myerr = netgen::mycout;
3611 _coutBuffer = std::cout.rdbuf();
3613 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3615 std::cout.rdbuf( netgen::mycout->rdbuf() );
3617 _ngMesh = Ng_NewMesh();
3620 //================================================================================
3622 * \brief Finish using netgen library
3624 //================================================================================
3626 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3628 Ng_DeleteMesh( _ngMesh );
3630 NETGENPlugin_Mesher::RemoveTmpFiles();
3631 std::cout.rdbuf( _coutBuffer );
3638 //================================================================================
3640 * \brief Set netgen mesh to delete at destruction
3642 //================================================================================
3644 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3647 Ng_DeleteMesh( _ngMesh );
3651 //================================================================================
3653 * \brief Return a unique file name
3655 //================================================================================
3657 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3659 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3661 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3662 aGenericName += "NETGEN_";
3664 aGenericName += getpid();
3666 aGenericName += _getpid();
3668 aGenericName += "_";
3669 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3670 aGenericName += ".out";
3672 return aGenericName.ToCString();
3675 //================================================================================
3677 * \brief Remove file with netgen output
3679 //================================================================================
3681 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3683 string tmpDir = SALOMEDS_Tool::GetDirFromPath( _outputFileName );
3684 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3686 std::string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3687 aFiles[0] = aFileName.c_str();
3688 if ( netgen::mycout)
3690 delete netgen::mycout;
3695 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
3697 //cout << "NOTE: netgen output log was REMOVED " << _outputFileName << endl;