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;
91 using namespace nglib;
95 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
97 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
100 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
102 // dump elements added to ng mesh
103 //#define DUMP_SEGMENTS
104 //#define DUMP_TRIANGLES
105 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
107 TopTools_IndexedMapOfShape ShapesWithLocalSize;
108 std::map<int,double> VertexId2LocalSize;
109 std::map<int,double> EdgeId2LocalSize;
110 std::map<int,double> FaceId2LocalSize;
112 //=============================================================================
116 //=============================================================================
118 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
119 const TopoDS_Shape& aShape,
125 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
126 _isViscousLayers2D(false),
129 SetDefaultParameters();
130 ShapesWithLocalSize.Clear();
131 VertexId2LocalSize.clear();
132 EdgeId2LocalSize.clear();
133 FaceId2LocalSize.clear();
136 //================================================================================
138 * \brief Initialize global NETGEN parameters with default values
140 //================================================================================
142 void NETGENPlugin_Mesher::SetDefaultParameters()
144 netgen::MeshingParameters& mparams = netgen::mparam;
145 // maximal mesh edge size
146 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
148 // minimal number of segments per edge
149 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
150 // rate of growth of size between elements
151 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
152 // safety factor for curvatures (elements per radius)
153 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
154 // create elements of second order
155 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder() ? 1 : 0;
156 // quad-dominated surface meshing
160 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed() ? 1 : 0;
161 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
164 //=============================================================================
168 //=============================================================================
169 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
171 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
172 if (GeomType == TopAbs_COMPOUND) {
173 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
174 SetLocalSize(it.Value(), LocalSize);
179 if (! ShapesWithLocalSize.Contains(GeomShape))
180 key = ShapesWithLocalSize.Add(GeomShape);
182 key = ShapesWithLocalSize.FindIndex(GeomShape);
183 if (GeomType == TopAbs_VERTEX) {
184 VertexId2LocalSize[key] = LocalSize;
185 } else if (GeomType == TopAbs_EDGE) {
186 EdgeId2LocalSize[key] = LocalSize;
187 } else if (GeomType == TopAbs_FACE) {
188 FaceId2LocalSize[key] = LocalSize;
192 //=============================================================================
194 * Pass parameters to NETGEN
196 //=============================================================================
197 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
201 netgen::MeshingParameters& mparams = netgen::mparam;
202 // Initialize global NETGEN parameters:
203 // maximal mesh segment size
204 mparams.maxh = hyp->GetMaxSize();
205 // maximal mesh element linear size
206 mparams.minh = hyp->GetMinSize();
207 // minimal number of segments per edge
208 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
209 // rate of growth of size between elements
210 mparams.grading = hyp->GetGrowthRate();
211 // safety factor for curvatures (elements per radius)
212 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
213 // create elements of second order
214 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
215 // quad-dominated surface meshing
216 // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
218 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
219 _optimize = hyp->GetOptimize();
220 _fineness = hyp->GetFineness();
223 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
224 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
225 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
226 SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
228 const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
229 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
230 for (it ; it != localSizes.end() ; it++)
232 std::string entry = (*it).first;
233 double val = (*it).second;
235 GEOM::GEOM_Object_var aGeomObj;
236 TopoDS_Shape S = TopoDS_Shape();
237 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
238 if (!aSObj->_is_nil()) {
239 CORBA::Object_var obj = aSObj->GetObject();
240 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
243 if ( !aGeomObj->_is_nil() )
244 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
246 SetLocalSize(S, val);
251 //=============================================================================
253 * Pass simple parameters to NETGEN
255 //=============================================================================
257 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
261 SetDefaultParameters();
264 //=============================================================================
266 * Link - a pair of integer numbers
268 //=============================================================================
272 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
273 Link() : n1(0), n2(0) {}
276 int HashCode(const Link& aLink, int aLimit)
278 return HashCode(aLink.n1 + aLink.n2, aLimit);
281 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
283 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
284 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
289 //================================================================================
291 * \brief return id of netgen point corresponding to SMDS node
293 //================================================================================
294 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
296 int ngNodeId( const SMDS_MeshNode* node,
297 netgen::Mesh& ngMesh,
298 TNode2IdMap& nodeNgIdMap)
300 int newNgId = ngMesh.GetNP() + 1;
302 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
304 if ( node_id->second == newNgId)
306 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
307 cout << "Ng " << newNgId << " - " << node;
309 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
310 ngMesh.AddPoint( p );
312 return node_id->second;
315 //================================================================================
317 * \brief Return computed EDGEs connected to the given one
319 //================================================================================
321 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
322 const TopoDS_Face& face,
323 const set< SMESH_subMesh* > & computedSM,
324 const SMESH_MesherHelper& helper,
325 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
328 list< TopoDS_Edge > edges;
329 list< int > nbEdgesInWire;
330 int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
332 // find <edge> within <edges>
333 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
334 for ( ; eItFwd != edges.end(); ++eItFwd )
335 if ( edge.IsSame( *eItFwd ))
337 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
339 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
341 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
342 // so treat each INTERNAL edge separately
343 TopoDS_Edge e = *eItFwd;
345 edges.push_back( e );
349 // get all computed EDGEs connected to <edge>
351 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
352 TopoDS_Vertex vCommon;
353 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
356 // put edges before <edge> to <edges> back
357 while ( edges.begin() != eItFwd )
358 edges.splice( edges.end(), edges, edges.begin() );
362 while ( ++eItFwd != edges.end() )
364 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
366 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
367 bool computed = sm->IsMeshComputed();
368 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
369 bool doubled = !eAdded.Add( *eItFwd );
370 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
371 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
372 if ( !connected || !computed || !orientOK || added || doubled )
374 // stop advancement; move edges from tail to head
375 while ( edges.back() != *ePrev )
376 edges.splice( edges.begin(), edges, --edges.end() );
382 while ( eItBack != edges.begin() )
386 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
388 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
389 bool computed = sm->IsMeshComputed();
390 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
391 bool doubled = !eAdded.Add( *eItBack );
392 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
393 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
394 if ( !connected || !computed || !orientOK || added || doubled)
397 edges.erase( edges.begin(), ePrev );
401 if ( edges.front() != edges.back() )
403 // assure that the 1st vertex is meshed
404 TopoDS_Edge eLast = edges.back();
405 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
407 edges.front() != eLast )
408 edges.splice( edges.end(), edges, edges.begin() );
413 //================================================================================
415 * \brief Make triangulation of a shape precise enough
417 //================================================================================
419 void updateTriangulation( const TopoDS_Shape& shape )
421 // static set< Poly_Triangulation* > updated;
423 // TopLoc_Location loc;
424 // TopExp_Explorer fExp( shape, TopAbs_FACE );
425 // for ( ; fExp.More(); fExp.Next() )
427 // Handle(Poly_Triangulation) triangulation =
428 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
429 // if ( triangulation.IsNull() ||
430 // updated.insert( triangulation.operator->() ).second )
432 // BRepTools::Clean (shape);
434 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
437 BRepMesh_IncrementalMesh e(shape, 0.01, true);
440 catch (Standard_Failure)
443 // updated.erase( triangulation.operator->() );
444 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
445 // updated.insert( triangulation.operator->() );
451 //================================================================================
453 * \brief Initialize netgen::OCCGeometry with OCCT shape
455 //================================================================================
457 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
458 const TopoDS_Shape& shape,
460 list< SMESH_subMesh* > * meshedSM,
461 NETGENPlugin_Internals* intern)
463 updateTriangulation( shape );
466 BRepBndLib::Add (shape, bb);
467 double x1,y1,z1,x2,y2,z2;
468 bb.Get (x1,y1,z1,x2,y2,z2);
469 MESSAGE("shape bounding box:\n" <<
470 "(" << x1 << " " << y1 << " " << z1 << ") " <<
471 "(" << x2 << " " << y2 << " " << z2 << ")");
472 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
473 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
474 occgeo.boundingbox = netgen::Box<3> (p1,p2);
476 occgeo.shape = shape;
479 // fill maps of shapes of occgeo with not yet meshed subshapes
481 // get root submeshes
482 list< SMESH_subMesh* > rootSM;
483 if ( SMESH_subMesh* sm = mesh.GetSubMeshContaining( shape )) {
484 rootSM.push_back( sm );
487 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
488 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
491 // add subshapes of empty submeshes
492 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
493 for ( ; rootIt != rootEnd; ++rootIt ) {
494 SMESH_subMesh * root = *rootIt;
495 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
496 /*complexShapeFirst=*/true);
497 // to find a right orientation of subshapes (PAL20462)
498 TopTools_IndexedMapOfShape subShapes;
499 TopExp::MapShapes(root->GetSubShape(), subShapes);
500 while ( smIt->more() )
502 SMESH_subMesh* sm = smIt->next();
503 TopoDS_Shape shape = sm->GetSubShape();
504 if ( intern && intern->isShapeToPrecompute( shape ))
506 if ( !meshedSM || sm->IsEmpty() )
508 if ( shape.ShapeType() != TopAbs_VERTEX )
509 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
510 if ( shape.Orientation() >= TopAbs_INTERNAL )
511 shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
512 switch ( shape.ShapeType() ) {
513 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
514 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
515 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
516 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
520 // collect submeshes of meshed shapes
523 const int dim = SMESH_Gen::GetShapeDim( shape );
524 meshedSM[ dim ].push_back( sm );
528 occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
529 occgeo.facemeshstatus = 0;
530 occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
531 occgeo.face_maxh_modified = 0;
532 occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
533 occgeo.face_maxh = netgen::mparam.maxh;
536 //================================================================================
538 * \brief Return a default min size value suitable for the given geometry.
540 //================================================================================
542 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
543 const double maxSize)
545 updateTriangulation( geom );
549 const int* pi[4] = { &i1, &i2, &i3, &i1 };
552 TopExp_Explorer fExp( geom, TopAbs_FACE );
553 for ( ; fExp.More(); fExp.Next() )
555 Handle(Poly_Triangulation) triangulation =
556 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
557 if ( triangulation.IsNull() ) continue;
558 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
559 const TColgp_Array1OfPnt& points = triangulation->Nodes();
560 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
561 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
563 trias(iT).Get( i1, i2, i3 );
564 for ( int j = 0; j < 3; ++j )
566 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
567 if ( dist2 < minh && fTol*fTol < dist2 )
569 bb.Add( points(*pi[j]));
573 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
575 minh = 1e-3 * sqrt( bb.SquareExtent());
576 //cout << "BND BOX minh = " <<minh << endl;
580 minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
581 //cout << "TRIANGULATION minh = " <<minh << endl;
583 if ( minh > 0.5 * maxSize )
589 //================================================================================
591 * \brief Restrict size of elements at a given point
593 //================================================================================
595 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh, const gp_XYZ& p, const double size)
597 if ( netgen::mparam.minh > size )
599 ngMesh.SetMinimalH( size );
600 netgen::mparam.minh = size;
602 netgen::Point3d pi(p.X(), p.Y(), p.Z());
603 ngMesh.RestrictLocalH( pi, size );
606 //================================================================================
608 * \brief fill ngMesh with nodes and elements of computed submeshes
610 //================================================================================
612 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
613 netgen::Mesh& ngMesh,
614 vector<const SMDS_MeshNode*>& nodeVec,
615 const list< SMESH_subMesh* > & meshedSM,
616 SMESH_ProxyMesh::Ptr proxyMesh)
618 TNode2IdMap nodeNgIdMap;
619 for ( int i = 1; i < nodeVec.size(); ++i )
620 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
622 TopTools_MapOfShape visitedShapes;
623 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
624 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
626 SMESH_MesherHelper helper (*_mesh);
628 int faceNgID = ngMesh.GetNFD();
630 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
631 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
633 SMESH_subMesh* sm = *smIt;
634 if ( !visitedShapes.Add( sm->GetSubShape() ))
637 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
638 if ( !smDS ) continue;
640 switch ( sm->GetSubShape().ShapeType() )
642 case TopAbs_EDGE: { // EDGE
643 // ----------------------
644 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
645 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
646 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
648 // Add ng segments for each not meshed FACE the EDGE bounds
649 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
650 while ( const TopoDS_Shape * anc = fIt->next() )
652 faceNgID = occgeom.fmap.FindIndex( *anc );
654 continue; // meshed face
656 int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
657 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
658 continue; // already treated EDGE
660 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
661 if ( face.Orientation() >= TopAbs_INTERNAL )
662 face.Orientation( TopAbs_FORWARD ); // issue 0020676
664 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
665 helper.SetSubShape( face );
666 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
667 visitedEdgeSM2Faces );
669 continue; // wrong ancestor?
671 // find out orientation of <edges> within <face>
672 TopoDS_Edge eNotSeam = edges.front();
673 if ( helper.HasSeam() )
675 list< TopoDS_Edge >::iterator eIt = edges.begin();
676 while ( helper.IsRealSeam( *eIt )) ++eIt;
677 if ( eIt != edges.end() )
680 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
681 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
683 // get all nodes from connected <edges>
684 bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
685 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
686 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
687 int i, nbSeg = fSide.NbSegments();
689 // remember EDGEs of fSide to treat only once
690 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
691 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
693 double otherSeamParam = 0;
698 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
700 for ( i = 0; i < nbSeg; ++i )
702 const UVPtStruct& p1 = points[ i ];
703 const UVPtStruct& p2 = points[ i+1 ];
705 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
708 if ( helper.IsRealSeam( p1.node->getshapeId() ))
710 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
711 isSeam = helper.IsRealSeam( e );
714 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
721 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
722 // node param on curve
723 seg.epgeominfo[ 0 ].dist = p1.param;
724 seg.epgeominfo[ 1 ].dist = p2.param;
726 seg.epgeominfo[ 0 ].u = p1.u;
727 seg.epgeominfo[ 0 ].v = p1.v;
728 seg.epgeominfo[ 1 ].u = p2.u;
729 seg.epgeominfo[ 1 ].v = p2.v;
731 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
732 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
734 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
735 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
736 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
737 ngMesh.AddSegment (seg);
739 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
740 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
743 cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
744 << "\tface index: " << seg.si << endl
745 << "\tp1: " << seg[0] << endl
746 << "\tp2: " << seg[1] << endl
747 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
748 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
749 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
750 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
751 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
752 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
756 if ( helper.GetPeriodicIndex() && 1 ) {
757 seg.epgeominfo[ 0 ].u = otherSeamParam;
758 seg.epgeominfo[ 1 ].u = otherSeamParam;
759 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
761 seg.epgeominfo[ 0 ].v = otherSeamParam;
762 seg.epgeominfo[ 1 ].v = otherSeamParam;
763 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
765 swap (seg[0], seg[1]);
766 swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
767 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
768 ngMesh.AddSegment (seg);
770 cout << "Segment: " << seg.edgenr << endl
771 << "\t is SEAM (reverse) of the previous. "
772 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
773 << " = " << otherSeamParam << endl;
776 else if ( fOri == TopAbs_INTERNAL )
778 swap (seg[0], seg[1]);
779 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
780 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
781 ngMesh.AddSegment (seg);
783 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
787 } // loop on geomEdge ancestors
790 } // case TopAbs_EDGE
792 case TopAbs_FACE: { // FACE
793 // ----------------------
794 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
795 helper.SetSubShape( geomFace );
796 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
798 // Find solids the geomFace bounds
799 int solidID1 = 0, solidID2 = 0;
800 StdMeshers_QuadToTriaAdaptor* quadAdaptor =
801 dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
804 solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
808 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
809 while ( const TopoDS_Shape * solid = solidIt->next() )
811 int id = occgeom.somap.FindIndex ( *solid );
812 if ( solidID1 && id != solidID1 ) solidID2 = id;
816 // Add ng face descriptors of meshed faces
818 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
820 // if second oreder is required, even already meshed faces must be passed to NETGEN
821 int fID = occgeom.fmap.Add( geomFace );
822 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
823 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
824 // Problem with the second order in a quadrangular mesh remains.
825 // 1) All quadrangles geberated by NETGEN are moved to an inexistent face
826 // by FillSMesh() (find AddFaceDescriptor)
827 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
828 // are on faces where quadrangles were.
829 // Due to these 2 points, wrong geom faces are used while conversion to qudratic
830 // of the mentioned above quadrangles and triangles
832 // Orient the face correctly in solidID1 (issue 0020206)
833 bool reverse = false;
835 TopoDS_Shape solid = occgeom.somap( solidID1 );
836 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
837 if ( faceOriInSolid >= 0 )
839 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
842 // Add surface elements
844 netgen::Element2d tri(3);
845 tri.SetIndex ( faceNgID );
848 #ifdef DUMP_TRIANGLES
849 cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
850 << " internal="<<isInternalFace << endl;
853 smDS = proxyMesh->GetSubMesh( geomFace );
855 SMDS_ElemIteratorPtr faces = smDS->GetElements();
856 while ( faces->more() )
858 const SMDS_MeshElement* f = faces->next();
859 if ( f->NbNodes() % 3 != 0 ) // not triangle
861 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
862 if ( const TopoDS_Shape * solid = solidIt->next() )
863 sm = _mesh->GetSubMesh( *solid );
864 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
865 smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
866 smError->myBadElements.push_back( f );
870 for ( int i = 0; i < 3; ++i )
872 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
874 // get node UV on face
875 int shapeID = node->getshapeId();
876 if ( helper.IsSeamShape( shapeID ))
877 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
878 inFaceNode = f->GetNodeWrap( i-1 );
880 inFaceNode = f->GetNodeWrap( i+1 );
881 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
883 int ind = reverse ? 3-i : i+1;
884 tri.GeomInfoPi(ind).u = uv.X();
885 tri.GeomInfoPi(ind).v = uv.Y();
886 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
889 ngMesh.AddSurfaceElement (tri);
890 #ifdef DUMP_TRIANGLES
894 if ( isInternalFace )
896 swap( tri[1], tri[2] );
897 ngMesh.AddSurfaceElement (tri);
898 #ifdef DUMP_TRIANGLES
904 } // case TopAbs_FACE
906 case TopAbs_VERTEX: { // VERTEX
907 // --------------------------
908 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
909 // else netgen removes a free node and nodeVector becomes invalid
910 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
914 while ( const TopoDS_Shape* e = ansIt->next() )
916 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
917 if (( toAdd = eSub->IsEmpty() )) break;
921 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
922 if ( nodeIt->more() )
923 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
929 } // loop on submeshes
932 nodeVec.resize( ngMesh.GetNP() + 1 );
933 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
934 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
935 nodeVec[ node_NgId->second ] = node_NgId->first;
940 //================================================================================
942 * \brief Duplicate mesh faces on internal geom faces
944 //================================================================================
946 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
947 netgen::Mesh& ngMesh,
948 NETGENPlugin_Internals& internalShapes)
950 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
952 // find ng indices of internal faces
954 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
956 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
957 if ( internalShapes.isInternalShape( smeshID ))
958 ngFaceIds.insert( ngFaceID );
960 if ( !ngFaceIds.empty() )
963 int i, nbFaces = ngMesh.GetNSE();
964 for (int i = 1; i <= nbFaces; ++i)
966 netgen::Element2d elem = ngMesh.SurfaceElement(i);
967 if ( ngFaceIds.count( elem.GetIndex() ))
969 swap( elem[1], elem[2] );
970 ngMesh.AddSurfaceElement (elem);
978 //================================================================================
979 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
980 gp_XY_FunPtr(Subtracted);
981 //gp_XY_FunPtr(Added);
983 //================================================================================
985 * \brief Evaluate distance between two 2d points along the surface
987 //================================================================================
989 double evalDist( const gp_XY& uv1,
991 const Handle(Geom_Surface)& surf,
992 const int stopHandler=-1)
994 if ( stopHandler > 0 ) // continue recursion
996 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
997 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
999 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1000 if ( stopHandler == 0 ) // stop recursion
1003 // start recursion if necessary
1004 double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1005 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1006 return dist3D; // equal parametrization of a planar surface
1008 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1011 //================================================================================
1013 * \brief Data of vertex internal in geom face
1015 //================================================================================
1019 gp_XY uv; //!< UV in face parametric space
1020 int ngId; //!< ng id of corrsponding node
1021 gp_XY uvClose; //!< UV of closest boundary node
1022 int ngIdClose; //!< ng id of closest boundary node
1025 //================================================================================
1027 * \brief Data of vertex internal in solid
1029 //================================================================================
1033 int ngId; //!< ng id of corresponding node
1034 int ngIdClose; //!< ng id of closest 2d mesh element
1035 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1038 inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1040 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1044 //================================================================================
1046 * \brief Make netgen take internal vertices in faces into account by adding
1047 * segments including internal vertices
1049 * This function works in supposition that 1D mesh is already computed in ngMesh
1051 //================================================================================
1053 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1054 netgen::Mesh& ngMesh,
1055 vector<const SMDS_MeshNode*>& nodeVec,
1056 NETGENPlugin_Internals& internalShapes)
1058 if ( nodeVec.size() < ngMesh.GetNP() )
1059 nodeVec.resize( ngMesh.GetNP(), 0 );
1061 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1062 SMESH_MesherHelper helper( internalShapes.getMesh() );
1064 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1065 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1066 for ( ; f2v != face2Vert.end(); ++f2v )
1068 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1069 if ( face.IsNull() ) continue;
1070 int faceNgID = occgeom.fmap.FindIndex (face);
1071 if ( faceNgID < 0 ) continue;
1073 TopLoc_Location loc;
1074 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1076 helper.SetSubShape( face );
1077 helper.SetElementsOnShape( true );
1079 // Get data of internal vertices and add them to ngMesh
1081 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1083 int i, nbSegInit = ngMesh.GetNSeg();
1085 // boundary characteristics
1086 double totSegLen2D = 0;
1089 const list<int>& iVertices = f2v->second;
1090 list<int>::const_iterator iv = iVertices.begin();
1091 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1094 // get node on vertex
1095 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1096 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1099 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1100 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1101 nV = SMESH_Algo::VertexNode( V, meshDS );
1102 if ( !nV ) continue;
1105 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1106 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1107 vData.ngId = ngMesh.GetNP();
1108 nodeVec.push_back( nV );
1112 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1113 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1115 // loop on all segments of the face to find the node closest to vertex and to count
1116 // average segment 2d length
1117 double closeDist2 = numeric_limits<double>::max(), dist2;
1119 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1121 netgen::Segment & seg = ngMesh.LineSegment(i);
1122 if ( seg.si != faceNgID ) continue;
1124 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1126 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1127 if ( ngIdLast == seg[ iEnd ] ) continue;
1128 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1129 if ( dist2 < closeDist2 )
1130 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1131 ngIdLast = seg[ iEnd ];
1135 totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1139 dist2VData.insert( make_pair( closeDist2, vData ));
1142 if ( totNbSeg == 0 ) break;
1143 double avgSegLen2d = totSegLen2D / totNbSeg;
1145 // Loop on vertices to add segments
1147 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1148 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1150 double closeDist2 = dist_vData->first, dist2;
1151 TIntVData & vData = dist_vData->second;
1153 // try to find more close node among segments added for internal vertices
1154 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1156 netgen::Segment & seg = ngMesh.LineSegment(i);
1157 if ( seg.si != faceNgID ) continue;
1159 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1161 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1162 dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1163 if ( dist2 < closeDist2 )
1164 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1167 // decide whether to use the closest node as the second end of segment or to
1168 // create a new point
1169 int segEnd1 = vData.ngId;
1170 int segEnd2 = vData.ngIdClose; // to use closest node
1171 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1172 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1173 double nodeDist2D = sqrt( closeDist2 );
1174 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1175 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1176 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1177 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1178 if ( hintLenOK || avgLenOK )
1180 // create a point between the closest node and V
1183 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1184 // direction from V to closet node in 2D
1185 gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1187 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1188 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1190 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1191 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1192 segEnd2 = ngMesh.GetNP();
1193 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1194 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1195 nodeVec.push_back( nP );
1197 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1200 netgen::Segment seg;
1202 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1203 seg[0] = segEnd1; // ng node id
1204 seg[1] = segEnd2; // ng node id
1205 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1208 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1209 seg.epgeominfo[ 0 ].u = uvV.X();
1210 seg.epgeominfo[ 0 ].v = uvV.Y();
1211 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1212 seg.epgeominfo[ 1 ].u = uvP.X();
1213 seg.epgeominfo[ 1 ].v = uvP.Y();
1215 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1216 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1218 ngMesh.AddSegment (seg);
1220 // add reverse segment
1221 swap (seg[0], seg[1]);
1222 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1223 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1224 ngMesh.AddSegment (seg);
1230 //================================================================================
1232 * \brief Make netgen take internal vertices in solids into account by adding
1233 * faces including internal vertices
1235 * This function works in supposition that 2D mesh is already computed in ngMesh
1237 //================================================================================
1239 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1240 netgen::Mesh& ngMesh,
1241 vector<const SMDS_MeshNode*>& nodeVec,
1242 NETGENPlugin_Internals& internalShapes)
1244 #ifdef DUMP_TRIANGLES_SCRIPT
1245 // create a python script making a mesh containing triangles added for internal vertices
1246 ofstream py(DUMP_TRIANGLES_SCRIPT);
1247 py << "from smesh import * "<< endl
1248 << "m = Mesh(name='triangles')" << endl;
1250 if ( nodeVec.size() < ngMesh.GetNP() )
1251 nodeVec.resize( ngMesh.GetNP(), 0 );
1253 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1254 SMESH_MesherHelper helper( internalShapes.getMesh() );
1256 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1257 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1258 for ( ; s2v != so2Vert.end(); ++s2v )
1260 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1261 if ( solid.IsNull() ) continue;
1262 int solidNgID = occgeom.somap.FindIndex (solid);
1263 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1265 helper.SetSubShape( solid );
1266 helper.SetElementsOnShape( true );
1268 // find ng indices of faces within the solid
1270 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1271 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1272 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1273 ngFaceIds.insert( 1 );
1275 // Get data of internal vertices and add them to ngMesh
1277 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1279 int i, nbFaceInit = ngMesh.GetNSE();
1281 // boundary characteristics
1282 double totSegLen = 0;
1285 const list<int>& iVertices = s2v->second;
1286 list<int>::const_iterator iv = iVertices.begin();
1287 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1290 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1292 // get node on vertex
1293 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1296 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1297 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1298 nV = SMESH_Algo::VertexNode( V, meshDS );
1299 if ( !nV ) continue;
1302 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1303 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1304 vData.ngId = ngMesh.GetNP();
1305 nodeVec.push_back( nV );
1307 // loop on all 2d elements to find the one closest to vertex and to count
1308 // average segment length
1309 double closeDist2 = numeric_limits<double>::max(), avgDist2;
1310 for (i = 1; i <= ngMesh.GetNSE(); ++i)
1312 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1313 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1315 multimap< double, int> dist2nID; // sort nodes of element by distance from V
1316 for ( int j = 0; j < elem.GetNP(); ++j)
1318 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1319 double d2 = dist2( mpV, mp );
1320 dist2nID.insert( make_pair( d2, elem[j] ));
1321 avgDist2 += d2 / elem.GetNP();
1323 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1325 double dist = dist2nID.begin()->first; //avgDist2;
1326 if ( dist < closeDist2 )
1327 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1329 dist2VData.insert( make_pair( closeDist2, vData ));
1332 if ( totNbSeg == 0 ) break;
1333 double avgSegLen = totSegLen / totNbSeg;
1335 // Loop on vertices to add triangles
1337 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1338 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1340 double closeDist2 = dist_vData->first;
1341 TIntVSoData & vData = dist_vData->second;
1343 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1345 // try to find more close face among ones added for internal vertices
1346 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1348 double avgDist2 = 0;
1349 multimap< double, int> dist2nID;
1350 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1351 for ( int j = 0; j < elem.GetNP(); ++j)
1353 double d = dist2( mpV, ngMesh.Point( elem[j] ));
1354 dist2nID.insert( make_pair( d, elem[j] ));
1355 avgDist2 += d / elem.GetNP();
1356 if ( avgDist2 < closeDist2 )
1357 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1360 // sort nodes of the closest face by angle with vector from V to the closest node
1361 const double tol = numeric_limits<double>::min();
1362 map< double, int > angle2ID;
1363 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1364 netgen::MeshPoint mp[2];
1365 mp[0] = ngMesh.Point( vData.ngIdCloseN );
1366 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1367 gp_XYZ pV( NGPOINT_COORDS( mpV ));
1368 gp_Vec v2p1( pV, p1 );
1369 double distN1 = v2p1.Magnitude();
1370 if ( distN1 <= tol ) continue;
1372 for ( int j = 0; j < closeFace.GetNP(); ++j)
1374 mp[1] = ngMesh.Point( closeFace[j] );
1375 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1376 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1378 // get node with angle of 60 degrees or greater
1379 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1380 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1381 const double minAngle = 30. * M_PI / 180.;
1382 const double angle = angle_id->first;
1383 bool angleOK = ( angle > minAngle );
1385 // find points to create a triangle
1386 netgen::Element2d tri(3);
1388 tri[0] = vData.ngId;
1389 tri[1] = vData.ngIdCloseN; // to use the closest nodes
1390 tri[2] = angle_id->second; // to use the node with best angle
1392 // decide whether to use the closest node and the node with best angle or to create new ones
1393 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1395 bool createNew = !angleOK, distOK = true;
1397 int triInd = isBestAngleN ? 2 : 1;
1398 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1403 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1404 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1406 else if ( angle < tol )
1408 v2p1.SetX( v2p1.X() + 1e-3 );
1414 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1415 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
1416 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
1417 createNew = (createNew || avgLenOK || hintLenOK );
1418 // we create a new node not closer than 0.5 to the closest face
1419 // in order not to clash with other close face
1420 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1421 distFromV = r * distN1;
1425 // create a new point, between the node and the vertex if angleOK
1426 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1427 gp_Vec v2p( pV, p ); v2p.Normalize();
1428 if ( isBestAngleN && !angleOK )
1429 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1431 p = pV + v2p.XYZ() * distFromV;
1433 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1435 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1436 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1437 tri[triInd] = ngMesh.GetNP();
1438 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1441 ngMesh.AddSurfaceElement (tri);
1442 swap( tri[1], tri[2] );
1443 ngMesh.AddSurfaceElement (tri);
1445 #ifdef DUMP_TRIANGLES_SCRIPT
1446 py << "n1 = m.AddNode( "<< mpV.X()<<", "<< mpV.Y()<<", "<< mpV.Z()<<") "<< endl
1447 << "n2 = m.AddNode( "<< mp[0].X()<<", "<< mp[0].Y()<<", "<< mp[0].Z()<<") "<< endl
1448 << "n3 = m.AddNode( "<< mp[1].X()<<", "<< mp[1].Y()<<", "<< mp[1].Z()<<" )" << endl
1449 << "m.AddFace([n1,n2,n3])" << endl;
1451 } // loop on internal vertices of a solid
1453 } // loop on solids with internal vertices
1456 //================================================================================
1458 * \brief Fill netgen mesh with segments of a FACE
1459 * \param ngMesh - netgen mesh
1460 * \param geom - container of OCCT geometry to mesh
1461 * \param wires - data of nodes on FACE boundary
1462 * \param helper - mesher helper holding the FACE
1463 * \param nodeVec - vector of nodes in which node index == netgen ID
1464 * \retval SMESH_ComputeErrorPtr - error description
1466 //================================================================================
1468 SMESH_ComputeErrorPtr
1469 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
1470 netgen::OCCGeometry& geom,
1471 const TSideVector& wires,
1472 SMESH_MesherHelper& helper,
1473 vector< const SMDS_MeshNode* > & nodeVec)
1475 // ----------------------------
1476 // Check wires and count nodes
1477 // ----------------------------
1479 for ( int iW = 0; iW < wires.size(); ++iW )
1481 StdMeshers_FaceSidePtr wire = wires[ iW ];
1482 if ( wire->MissVertexNode() )
1484 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1485 // It seems that there is no reason for this limitation
1487 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1489 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1490 if ( uvPtVec.size() != wire->NbPoints() )
1491 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1492 SMESH_Comment("Unexpected nb of points on wire ") << iW
1493 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1494 nbNodes += wire->NbPoints();
1496 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1497 if ( nodeVec.empty() )
1498 nodeVec.push_back( 0 );
1500 // -----------------
1502 // -----------------
1504 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1505 NETGENPlugin_NETGEN_2D_ONLY */
1507 // map for nodes on vertices since they can be shared between wires
1508 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1509 map<const SMDS_MeshNode*, int > node2ngID;
1510 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1512 set< int > subIDs; // ids of sub-shapes of the FACE
1513 for ( int iW = 0; iW < wires.size(); ++iW )
1515 StdMeshers_FaceSidePtr wire = wires[ iW ];
1516 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1518 subIDs.insert( wire->EdgeID( iE ));
1519 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1522 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1523 if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1524 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1527 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1528 if ( ngMesh.GetNFD() < 1 )
1529 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0));
1531 for ( int iW = 0; iW < wires.size(); ++iW )
1533 StdMeshers_FaceSidePtr wire = wires[ iW ];
1534 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1535 const int nbSegments = wire->NbPoints() - 1;
1537 // assure the 1st node to be in node2ngID, which is needed to correctly
1538 // "close chain of segments" (see below) in case if the 1st node is not
1539 // onVertex because it is on a Viscous layer
1540 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1542 // compute length of every segment
1543 vector<double> segLen( nbSegments );
1544 for ( int i = 0; i < nbSegments; ++i )
1545 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1547 int edgeID = 1, posID = -2;
1548 bool isInternalWire = false;
1549 double vertexNormPar = 0;
1550 const int prevNbNGSeg = ngMesh.GetNSeg();
1551 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1553 // Add the first point of a segment
1555 const SMDS_MeshNode * n = uvPtVec[ i ].node;
1556 const int posShapeID = n->getshapeId();
1557 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1558 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
1560 // skip nodes on degenerated edges
1561 if ( helper.IsDegenShape( posShapeID ) &&
1562 helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1565 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1566 if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1567 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1568 if ( ngID1 > ngMesh.GetNP() )
1570 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1571 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1572 nodeVec.push_back( n );
1574 else // n is in ngMesh already, and ngID2 in prev segment is wrong
1576 ngID2 = ngMesh.GetNP() + 1;
1577 if ( i > 0 ) // prev segment belongs to same wire
1579 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1586 netgen::Segment seg;
1588 seg[0] = ngID1; // ng node id
1589 seg[1] = ngID2; // ng node id
1590 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1591 seg.si = faceID; // = geom.fmap.FindIndex (face);
1593 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1595 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1597 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1598 seg.epgeominfo[ iEnd ].u = pnt.u;
1599 seg.epgeominfo[ iEnd ].v = pnt.v;
1601 // find out edge id and node parameter on edge
1602 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1603 if ( onVertex || posShapeID != posID )
1606 double normParam = pnt.normParam;
1608 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1609 int edgeIndexInWire = wire->EdgeIndex( normParam );
1610 vertexNormPar = wire->LastParameter( edgeIndexInWire );
1611 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1612 edgeID = geom.emap.FindIndex( edge );
1614 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1615 // if ( onVertex ) // param on curve is different on each of two edges
1616 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1618 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1621 ngMesh.AddSegment (seg);
1623 // restrict size of elements near the segment
1624 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1625 // get an average size of adjacent segments to avoid sharp change of
1626 // element size (regression on issue 0020452, note 0010898)
1627 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1628 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1629 double avgH = ( segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ]) / 3;
1631 RestrictLocalSize( ngMesh, 0.5*(np1+np2), avgH );
1633 if ( isInternalWire )
1635 swap (seg[0], seg[1]);
1636 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1637 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1638 ngMesh.AddSegment (seg);
1640 } // loop on segments on a wire
1642 // close chain of segments
1643 if ( nbSegments > 0 )
1645 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1646 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1647 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1648 if ( lastSeg[1] > ngMesh.GetNP() )
1650 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1651 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1652 nodeVec.push_back( lastNode );
1654 if ( isInternalWire )
1656 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1657 realLastSeg[0] = lastSeg[1];
1661 #ifdef DUMP_SEGMENTS
1662 cout << "BEGIN WIRE " << iW << endl;
1663 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1665 netgen::Segment& seg = ngMesh.LineSegment( i );
1667 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1668 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1670 cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1674 cout << "Segment: " << seg.edgenr << endl
1675 << "\tp1: " << seg[0] << endl
1676 << "\tp2: " << seg[1] << endl
1677 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1678 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1679 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1680 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1681 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1682 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1684 cout << "--END WIRE " << iW << endl;
1687 } // loop on WIREs of a FACE
1689 // add a segment instead of an internal vertex
1690 if ( wasNgMeshEmpty )
1692 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1693 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1695 ngMesh.CalcSurfacesOfNode();
1700 //================================================================================
1702 * \brief Fill SMESH mesh according to contents of netgen mesh
1703 * \param occgeo - container of OCCT geometry to mesh
1704 * \param ngMesh - netgen mesh
1705 * \param initState - bn of entities in netgen mesh before computing
1706 * \param sMesh - SMESH mesh to fill in
1707 * \param nodeVec - vector of nodes in which node index == netgen ID
1708 * \retval int - error
1710 //================================================================================
1712 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
1713 netgen::Mesh& ngMesh,
1714 const NETGENPlugin_ngMeshInfo& initState,
1716 std::vector<const SMDS_MeshNode*>& nodeVec,
1717 SMESH_Comment& comment)
1719 int nbNod = ngMesh.GetNP();
1720 int nbSeg = ngMesh.GetNSeg();
1721 int nbFac = ngMesh.GetNSE();
1722 int nbVol = ngMesh.GetNE();
1724 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1726 // -------------------------------------
1727 // Create and insert nodes into nodeVec
1728 // -------------------------------------
1730 nodeVec.resize( nbNod + 1 );
1731 int i, nbInitNod = initState._nbNodes;
1732 for (i = nbInitNod+1; i <= nbNod; ++i )
1734 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1735 SMDS_MeshNode* node = NULL;
1736 TopoDS_Vertex aVert;
1737 // First, netgen creates nodes on vertices in occgeo.vmap,
1738 // so node index corresponds to vertex index
1739 // but (issue 0020776) netgen does not create nodes with equal coordinates
1740 if ( i-nbInitNod <= occgeo.vmap.Extent() )
1742 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1743 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1745 aVert = TopoDS::Vertex( occgeo.vmap( iV ) );
1746 gp_Pnt pV = BRep_Tool::Pnt( aVert );
1747 if ( p.SquareDistance( pV ) > 1e-20 )
1750 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1753 if (!node) // node not found on vertex
1755 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1756 if (!aVert.IsNull())
1757 meshDS->SetNodeOnVertex(node, aVert);
1762 // -------------------------------------------
1763 // Create mesh segments along geometric edges
1764 // -------------------------------------------
1766 int nbInitSeg = initState._nbSegments;
1767 for (i = nbInitSeg+1; i <= nbSeg; ++i )
1769 const netgen::Segment& seg = ngMesh.LineSegment(i);
1771 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1774 for (int j=0; j < 3; ++j)
1776 int pind = pinds[j];
1777 if (pind <= 0 || !nodeVec_ACCESS(pind))
1785 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1786 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1787 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1789 param = seg.epgeominfo[j].dist;
1792 else // middle point
1794 param = param2 * 0.5;
1796 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1798 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1803 SMDS_MeshEdge* edge = 0;
1804 if (nbp == 2) // second order ?
1806 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1808 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1812 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1813 nodeVec_ACCESS(pinds[2])))
1815 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1816 nodeVec_ACCESS(pinds[2]));
1820 if ( comment.empty() ) comment << "Cannot create a mesh edge";
1821 MESSAGE("Cannot create a mesh edge");
1822 nbSeg = nbFac = nbVol = 0;
1825 if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1826 meshDS->SetMeshElementOnShape(edge, aEdge);
1828 else if ( comment.empty() )
1830 comment << "Invalid netgen segment #" << i;
1834 // ----------------------------------------
1835 // Create mesh faces along geometric faces
1836 // ----------------------------------------
1838 int nbInitFac = initState._nbFaces;
1839 int quadFaceID = ngMesh.GetNFD() + 1;
1840 if ( nbInitFac < nbFac )
1841 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1842 // from computation of 3D mesh
1843 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1845 for (i = nbInitFac+1; i <= nbFac; ++i )
1847 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1848 int aGeomFaceInd = elem.GetIndex();
1850 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
1851 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
1852 vector<SMDS_MeshNode*> nodes;
1853 for (int j=1; j <= elem.GetNP(); ++j)
1855 int pind = elem.PNum(j);
1856 if ( pind < 1 || pind >= nodeVec.size() )
1858 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
1860 nodes.push_back(node);
1861 if (!aFace.IsNull() && node->getshapeId() < 1)
1863 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
1864 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
1868 if ( nodes.size() != elem.GetNP() )
1870 if ( comment.empty() )
1871 comment << "Invalid netgen 2d element #" << i;
1872 continue; // bad node ids
1874 SMDS_MeshFace* face = NULL;
1875 switch (elem.GetType())
1878 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
1881 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
1882 // exclude qudrangle elements from computation of 3D mesh
1883 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1886 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
1889 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
1890 nodes[4],nodes[7],nodes[5],nodes[6]);
1891 // exclude qudrangle elements from computation of 3D mesh
1892 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1895 MESSAGE("NETGEN created a face of unexpected type, ignoring");
1900 if ( comment.empty() ) comment << "Cannot create a mesh face";
1901 MESSAGE("Cannot create a mesh face");
1902 nbSeg = nbFac = nbVol = 0;
1905 if (!aFace.IsNull())
1906 meshDS->SetMeshElementOnShape(face, aFace);
1909 // ------------------
1910 // Create tetrahedra
1911 // ------------------
1913 for (i = 1; i <= nbVol; ++i)
1915 const netgen::Element& elem = ngMesh.VolumeElement(i);
1916 int aSolidInd = elem.GetIndex();
1917 TopoDS_Solid aSolid;
1918 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
1919 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
1920 vector<SMDS_MeshNode*> nodes;
1921 for (int j=1; j <= elem.GetNP(); ++j)
1923 int pind = elem.PNum(j);
1924 if ( pind < 1 || pind >= nodeVec.size() )
1926 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
1928 nodes.push_back(node);
1929 if ( !aSolid.IsNull() && node->getshapeId() < 1 )
1930 meshDS->SetNodeInVolume(node, aSolid);
1933 if ( nodes.size() != elem.GetNP() )
1935 if ( comment.empty() )
1936 comment << "Invalid netgen 3d element #" << i;
1939 SMDS_MeshVolume* vol = NULL;
1940 switch (elem.GetType())
1943 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
1946 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
1947 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
1950 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
1955 if ( comment.empty() ) comment << "Cannot create a mesh volume";
1956 MESSAGE("Cannot create a mesh volume");
1957 nbSeg = nbFac = nbVol = 0;
1960 if (!aSolid.IsNull())
1961 meshDS->SetMeshElementOnShape(vol, aSolid);
1963 return comment.empty() ? 0 : 1;
1968 //================================================================================
1970 * \brief Restrict size of elements on the given edge
1972 //================================================================================
1974 void setLocalSize(const TopoDS_Edge& edge,
1978 const int nb = 1000;
1979 Standard_Real u1, u2;
1980 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
1981 if ( curve.IsNull() )
1983 TopoDS_Iterator vIt( edge );
1984 if ( !vIt.More() ) return;
1985 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
1986 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
1990 Standard_Real delta = (u2-u1)/nb;
1991 for(int i=0; i<nb; i++)
1993 Standard_Real u = u1 + delta*i;
1994 gp_Pnt p = curve->Value(u);
1995 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
1996 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1997 double resultSize = mesh.GetH(pi);
1998 if ( resultSize - size > 0.1*size )
1999 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2000 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2005 //================================================================================
2007 * \brief Convert error into text
2009 //================================================================================
2011 std::string text(int err)
2016 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2019 //================================================================================
2021 * \brief Convert exception into text
2023 //================================================================================
2025 std::string text(Standard_Failure& ex)
2027 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2028 str << " at " << netgen::multithread.task
2029 << ": " << ex.DynamicType()->Name();
2030 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2031 str << ": " << ex.GetMessageString();
2034 //================================================================================
2036 * \brief Convert exception into text
2038 //================================================================================
2040 std::string text(netgen::NgException& ex)
2042 SMESH_Comment str("NgException");
2043 if ( strlen( netgen::multithread.task ) > 0 )
2044 str << " at " << netgen::multithread.task;
2045 str << ": " << ex.What();
2050 //=============================================================================
2052 * Here we are going to use the NETGEN mesher
2054 //=============================================================================
2056 bool NETGENPlugin_Mesher::Compute()
2058 NETGENPlugin_NetgenLibWrapper ngLib;
2060 netgen::MeshingParameters& mparams = netgen::mparam;
2061 MESSAGE("Compute with:\n"
2062 " max size = " << mparams.maxh << "\n"
2063 " segments per edge = " << mparams.segmentsperedge);
2065 " growth rate = " << mparams.grading << "\n"
2066 " elements per radius = " << mparams.curvaturesafety << "\n"
2067 " second order = " << mparams.secondorder << "\n"
2068 " quad allowed = " << mparams.quad);
2069 //cout << " quad allowed = " << mparams.quad<<endl;
2071 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2073 static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( ngMesh, debugFile )
2074 while debugging netgen */
2075 // -------------------------
2076 // Prepare OCC geometry
2077 // -------------------------
2079 netgen::OCCGeometry occgeo;
2080 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2081 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2082 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2084 // -------------------------
2085 // Generate the mesh
2086 // -------------------------
2088 netgen::Mesh *ngMesh = NULL;
2089 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2091 SMESH_Comment comment;
2094 // vector of nodes in which node index == netgen ID
2095 vector< const SMDS_MeshNode* > nodeVec;
2103 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2104 mparams.uselocalh = false;
2105 mparams.grading = 0.8; // not limitited size growth
2107 if ( _simpleHyp->GetNumberOfSegments() )
2109 mparams.maxh = occgeo.boundingbox.Diam();
2112 mparams.maxh = _simpleHyp->GetLocalLength();
2115 if ( mparams.maxh == 0.0 )
2116 mparams.maxh = occgeo.boundingbox.Diam();
2117 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2118 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2120 // Local size on faces
2121 occgeo.face_maxh = mparams.maxh;
2123 // Let netgen create ngMesh and calculate element size on not meshed shapes
2127 int startWith = netgen::MESHCONST_ANALYSE;
2128 int endWith = netgen::MESHCONST_ANALYSE;
2133 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2135 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2137 if(netgen::multithread.terminate)
2140 comment << text(err);
2142 catch (Standard_Failure& ex)
2144 comment << text(ex);
2146 err = 0; //- MESHCONST_ANALYSE isn't so important step
2149 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2151 ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2155 // Pass 1D simple parameters to NETGEN
2156 // --------------------------------
2157 int nbSeg = _simpleHyp->GetNumberOfSegments();
2158 double segSize = _simpleHyp->GetLocalLength();
2159 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2161 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2163 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2164 setLocalSize( e, segSize, *ngMesh );
2167 else // if ( ! _simpleHyp )
2169 // Local size on vertices and edges
2170 // --------------------------------
2171 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2173 int key = (*it).first;
2174 double hi = (*it).second;
2175 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2176 const TopoDS_Edge& e = TopoDS::Edge(shape);
2177 setLocalSize( e, hi, *ngMesh );
2179 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2181 int key = (*it).first;
2182 double hi = (*it).second;
2183 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2184 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2185 gp_Pnt p = BRep_Tool::Pnt(v);
2186 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2188 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2189 it!=FaceId2LocalSize.end(); it++)
2191 int key = (*it).first;
2192 double val = (*it).second;
2193 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2194 int faceNgID = occgeo.fmap.FindIndex(shape);
2195 occgeo.SetFaceMaxH(faceNgID, val);
2196 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2197 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2201 // Precompute internal edges (issue 0020676) in order to
2202 // add mesh on them correctly (twice) to netgen mesh
2203 if ( !err && internals.hasInternalEdges() )
2205 // load internal shapes into OCCGeometry
2206 netgen::OCCGeometry intOccgeo;
2207 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2208 intOccgeo.boundingbox = occgeo.boundingbox;
2209 intOccgeo.shape = occgeo.shape;
2210 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2211 intOccgeo.face_maxh = netgen::mparam.maxh;
2212 netgen::Mesh *tmpNgMesh = NULL;
2216 // compute local H on internal shapes in the main mesh
2217 //OCCSetLocalMeshSize(intOccgeo, *ngMesh); it deletes ngMesh->localH
2219 // let netgen create a temporary mesh
2221 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2223 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2225 if(netgen::multithread.terminate)
2228 // copy LocalH from the main to temporary mesh
2229 initState.transferLocalH( ngMesh, tmpNgMesh );
2231 // compute mesh on internal edges
2232 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2234 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2236 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2238 comment << text(err);
2240 catch (Standard_Failure& ex)
2242 comment << text(ex);
2245 initState.restoreLocalH( tmpNgMesh );
2247 // fill SMESH by netgen mesh
2248 vector< const SMDS_MeshNode* > tmpNodeVec;
2249 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2250 err = ( err || !comment.empty() );
2252 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2255 // Fill ngMesh with nodes and segments of computed submeshes
2258 err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2259 FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
2261 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2266 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2271 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2273 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2275 if(netgen::multithread.terminate)
2278 comment << text(err);
2280 catch (Standard_Failure& ex)
2282 comment << text(ex);
2286 mparams.uselocalh = true; // restore as it is used at surface optimization
2288 // ---------------------
2289 // compute surface mesh
2290 // ---------------------
2293 // Pass 2D simple parameters to NETGEN
2295 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2297 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2298 mparams.grading = 0.4; // moderate size growth
2301 // length from edges
2302 if ( ngMesh->GetNSeg() ) {
2303 double edgeLength = 0;
2304 TopTools_MapOfShape visitedEdges;
2305 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2306 if( visitedEdges.Add(exp.Current()) )
2307 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2308 // we have to multiply length by 2 since for each TopoDS_Edge there
2309 // are double set of NETGEN edges, in other words, we have to
2310 // divide ngMesh->GetNSeg() by 2.
2311 mparams.maxh = 2*edgeLength / ngMesh->GetNSeg();
2314 mparams.maxh = 1000;
2316 mparams.grading = 0.2; // slow size growth
2318 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2319 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2320 ngMesh->SetGlobalH (mparams.maxh);
2321 netgen::Box<3> bb = occgeo.GetBoundingBox();
2322 bb.Increase (bb.Diam()/20);
2323 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2326 // Care of vertices internal in faces (issue 0020676)
2327 if ( internals.hasInternalVertexInFace() )
2329 // store computed segments in SMESH in order not to create SMESH
2330 // edges for ng segments added by AddIntVerticesInFaces()
2331 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2332 // add segments to faces with internal vertices
2333 AddIntVerticesInFaces( occgeo, *ngMesh, nodeVec, internals );
2334 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2337 // Build viscous layers
2338 if ( _isViscousLayers2D )
2340 if ( !internals.hasInternalVertexInFace() ) {
2341 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2342 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2344 SMESH_ProxyMesh::Ptr viscousMesh;
2345 SMESH_MesherHelper helper( *_mesh );
2346 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2348 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2349 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2352 // exclude from computation ng segments built on EDGEs of F
2353 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
2355 netgen::Segment & seg = ngMesh->LineSegment(i);
2356 if (seg.si == faceID)
2359 // add new segments to ngMesh instead of excluded ones
2360 helper.SetSubShape( F );
2362 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2363 error, viscousMesh );
2364 error = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
2366 if ( !error ) error = SMESH_ComputeError::New();
2368 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2371 // Let netgen compute 2D mesh
2372 startWith = netgen::MESHCONST_MESHSURFACE;
2373 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2378 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2380 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2382 if(netgen::multithread.terminate)
2385 comment << text (err);
2387 catch (Standard_Failure& ex)
2389 comment << text(ex);
2390 //err = 1; -- try to make volumes anyway
2392 catch (netgen::NgException exc)
2394 comment << text(exc);
2395 //err = 1; -- try to make volumes anyway
2398 // ---------------------
2399 // generate volume mesh
2400 // ---------------------
2401 // Fill ngMesh with nodes and faces of computed 2D submeshes
2402 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2404 // load SMESH with computed segments and faces
2405 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2407 // compute pyramids on quadrangles
2408 SMESH_ProxyMesh::Ptr proxyMesh;
2409 if ( _mesh->NbQuadrangles() > 0 )
2410 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2412 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2413 proxyMesh.reset( Adaptor );
2415 int nbPyrams = _mesh->NbPyramids();
2416 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2417 if ( nbPyrams != _mesh->NbPyramids() )
2419 list< SMESH_subMesh* > quadFaceSM;
2420 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2421 if ( Adaptor->GetProxySubMesh( face.Current() ))
2423 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2424 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2426 FillNgMesh(occgeo, *ngMesh, nodeVec, quadFaceSM, proxyMesh);
2429 // fill ngMesh with faces of sub-meshes
2430 err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
2431 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2432 //toPython( ngMesh, "/tmp/ngPython.py");
2434 if (!err && _isVolume)
2436 // Pass 3D simple parameters to NETGEN
2437 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2438 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2440 if ( double vol = simple3d->GetMaxElementVolume() ) {
2442 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2443 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2446 // length from faces
2447 mparams.maxh = ngMesh->AverageH();
2449 ngMesh->SetGlobalH (mparams.maxh);
2450 mparams.grading = 0.4;
2452 ngMesh->CalcLocalH(mparams.grading);
2454 ngMesh->CalcLocalH();
2457 // Care of vertices internal in solids and internal faces (issue 0020676)
2458 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2460 // store computed faces in SMESH in order not to create SMESH
2461 // faces for ng faces added here
2462 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2463 // add ng faces to solids with internal vertices
2464 AddIntVerticesInSolids( occgeo, *ngMesh, nodeVec, internals );
2465 // duplicate mesh faces on internal faces
2466 FixIntFaces( occgeo, *ngMesh, internals );
2467 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2469 // Let netgen compute 3D mesh
2470 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2475 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2477 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2479 if(netgen::multithread.terminate)
2482 if ( comment.empty() ) // do not overwrite a previos error
2483 comment << text(err);
2485 catch (Standard_Failure& ex)
2487 if ( comment.empty() ) // do not overwrite a previos error
2488 comment << text(ex);
2491 catch (netgen::NgException exc)
2493 if ( comment.empty() ) // do not overwrite a previos error
2494 comment << text(exc);
2497 // Let netgen optimize 3D mesh
2498 if ( !err && _optimize )
2500 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2505 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2507 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2509 if(netgen::multithread.terminate)
2512 if ( comment.empty() ) // do not overwrite a previos error
2513 comment << text(err);
2515 catch (Standard_Failure& ex)
2517 if ( comment.empty() ) // do not overwrite a previos error
2518 comment << text(ex);
2520 catch (netgen::NgException exc)
2522 if ( comment.empty() ) // do not overwrite a previos error
2523 comment << text(exc);
2527 if (!err && mparams.secondorder > 0)
2532 netgen::OCCRefinementSurfaces ref (occgeo);
2533 ref.MakeSecondOrder (*ngMesh);
2535 catch (Standard_Failure& ex)
2537 if ( comment.empty() ) // do not overwrite a previos error
2538 comment << "Exception in netgen at passing to 2nd order ";
2540 catch (netgen::NgException exc)
2542 if ( comment.empty() ) // do not overwrite a previos error
2543 comment << exc.What();
2547 int nbNod = ngMesh->GetNP();
2548 int nbSeg = ngMesh->GetNSeg();
2549 int nbFac = ngMesh->GetNSE();
2550 int nbVol = ngMesh->GetNE();
2551 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2553 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2554 ", nb nodes: " << nbNod <<
2555 ", nb segments: " << nbSeg <<
2556 ", nb faces: " << nbFac <<
2557 ", nb volumes: " << nbVol);
2559 // Feed back the SMESHDS with the generated Nodes and Elements
2560 if ( true /*isOK*/ ) // get whatever built
2561 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment ); //!<
2563 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2564 if ( readErr && !readErr->myBadElements.empty() )
2567 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2568 error->myName = COMPERR_ALGO_FAILED;
2569 if ( !comment.empty() )
2570 error->myComment = comment;
2572 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2573 // appear if the geometry contains coincident sub-shape due
2574 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2575 const int nbMaps = 2;
2576 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2577 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2578 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2579 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2580 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2581 if ( !sm->IsMeshComputed() )
2582 sm->SetIsAlwaysComputed( true );
2584 // set bad compute error to subshapes of all failed sub-shapes
2585 if ( !error->IsOK() )
2587 bool pb2D = false, pb3D = false;
2588 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2589 int status = occgeo.facemeshstatus[i-1];
2590 if (status == 1 ) continue;
2591 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2592 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2593 if ( !smError || smError->IsOK() ) {
2595 smError.reset( new SMESH_ComputeError( *error ));
2597 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2598 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2599 smError->myName = COMPERR_WARNING;
2601 pb2D = pb2D || smError->IsKO();
2604 if ( !pb2D ) // all faces are OK
2605 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2606 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2608 bool smComputed = nbVol && !sm->IsEmpty();
2609 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2611 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2612 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2613 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2615 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2616 if ( !smComputed && ( !smError || smError->IsOK() ))
2618 smError.reset( new SMESH_ComputeError( *error ));
2619 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2620 smError->myName = COMPERR_WARNING;
2622 pb3D = pb3D || ( smError && smError->IsKO() );
2624 if ( !pb2D && !pb3D )
2625 err = 0; // no fatal errors, only warnings
2628 ngLib._isComputeOk = !err;
2633 //=============================================================================
2637 //=============================================================================
2638 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2640 netgen::MeshingParameters& mparams = netgen::mparam;
2643 // -------------------------
2644 // Prepare OCC geometry
2645 // -------------------------
2646 netgen::OCCGeometry occgeo;
2647 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2648 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2649 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2651 bool tooManyElems = false;
2652 const int hugeNb = std::numeric_limits<int>::max() / 100;
2657 // pass 1D simple parameters to NETGEN
2660 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2661 mparams.uselocalh = false;
2662 mparams.grading = 0.8; // not limitited size growth
2664 if ( _simpleHyp->GetNumberOfSegments() )
2666 mparams.maxh = occgeo.boundingbox.Diam();
2669 mparams.maxh = _simpleHyp->GetLocalLength();
2672 if ( mparams.maxh == 0.0 )
2673 mparams.maxh = occgeo.boundingbox.Diam();
2674 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2675 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2677 // let netgen create ngMesh and calculate element size on not meshed shapes
2678 NETGENPlugin_NetgenLibWrapper ngLib;
2679 netgen::Mesh *ngMesh = NULL;
2683 int startWith = netgen::MESHCONST_ANALYSE;
2684 int endWith = netgen::MESHCONST_MESHEDGES;
2686 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2688 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2691 if(netgen::multithread.terminate)
2694 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2696 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2697 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2702 // Pass 1D simple parameters to NETGEN
2703 // --------------------------------
2704 int nbSeg = _simpleHyp->GetNumberOfSegments();
2705 double segSize = _simpleHyp->GetLocalLength();
2706 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2708 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2710 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2711 setLocalSize( e, segSize, *ngMesh );
2714 else // if ( ! _simpleHyp )
2716 // Local size on vertices and edges
2717 // --------------------------------
2718 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2720 int key = (*it).first;
2721 double hi = (*it).second;
2722 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2723 const TopoDS_Edge& e = TopoDS::Edge(shape);
2724 setLocalSize( e, hi, *ngMesh );
2726 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2728 int key = (*it).first;
2729 double hi = (*it).second;
2730 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2731 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2732 gp_Pnt p = BRep_Tool::Pnt(v);
2733 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2735 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2736 it!=FaceId2LocalSize.end(); it++)
2738 int key = (*it).first;
2739 double val = (*it).second;
2740 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2741 int faceNgID = occgeo.fmap.FindIndex(shape);
2742 occgeo.SetFaceMaxH(faceNgID, val);
2743 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2744 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2747 // calculate total nb of segments and length of edges
2748 double fullLen = 0.0;
2750 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
2751 TopTools_DataMapOfShapeInteger Edge2NbSeg;
2752 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
2754 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2755 if( !Edge2NbSeg.Bind(E,0) )
2758 double aLen = SMESH_Algo::EdgeLength(E);
2761 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
2763 aVec.resize( SMDSEntity_Last, 0);
2765 fullNbSeg += aVec[ entity ];
2768 // store nb of segments computed by Netgen
2769 NCollection_Map<Link> linkMap;
2770 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
2772 const netgen::Segment& seg = ngMesh->LineSegment(i);
2773 Link link(seg[0], seg[1]);
2774 if ( !linkMap.Add( link )) continue;
2775 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
2776 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2778 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
2782 // store nb of nodes on edges computed by Netgen
2783 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
2784 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
2786 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
2787 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
2788 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
2790 fullNbSeg += aVec[ entity ];
2791 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
2793 if ( fullNbSeg == 0 )
2800 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2802 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2803 mparams.grading = 0.4; // moderate size growth
2806 // length from edges
2807 mparams.maxh = fullLen/fullNbSeg;
2808 mparams.grading = 0.2; // slow size growth
2811 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2812 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2814 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
2816 TopoDS_Face F = TopoDS::Face( exp.Current() );
2817 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
2819 BRepGProp::SurfaceProperties(F,G);
2820 double anArea = G.Mass();
2821 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
2823 if ( !tooManyElems )
2825 TopTools_MapOfShape egdes;
2826 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
2827 if ( egdes.Add( exp1.Current() ))
2828 nb1d += Edge2NbSeg.Find(exp1.Current());
2830 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
2831 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
2833 vector<int> aVec(SMDSEntity_Last, 0);
2834 if( mparams.secondorder > 0 ) {
2835 int nb1d_in = (nbFaces*3 - nb1d) / 2;
2836 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2837 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
2840 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
2841 aVec[SMDSEntity_Triangle] = nbFaces;
2843 aResMap[sm].swap(aVec);
2850 // pass 3D simple parameters to NETGEN
2851 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2852 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2854 if ( double vol = simple3d->GetMaxElementVolume() ) {
2856 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2857 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2860 // using previous length from faces
2862 mparams.grading = 0.4;
2863 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2866 BRepGProp::VolumeProperties(_shape,G);
2867 double aVolume = G.Mass();
2868 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
2869 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
2870 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
2871 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2872 vector<int> aVec(SMDSEntity_Last, 0 );
2873 if ( tooManyElems ) // avoid FPE
2875 aVec[SMDSEntity_Node] = hugeNb;
2876 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
2880 if( mparams.secondorder > 0 ) {
2881 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2882 aVec[SMDSEntity_Quad_Tetra] = nbVols;
2885 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2886 aVec[SMDSEntity_Tetra] = nbVols;
2889 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
2890 aResMap[sm].swap(aVec);
2896 //================================================================================
2898 * \brief Remove "test.out" and "problemfaces" files in current directory
2900 //================================================================================
2902 void NETGENPlugin_Mesher::RemoveTmpFiles()
2904 if ( SMESH_File("test.out").remove() && netgen::testout)
2906 delete netgen::testout;
2907 netgen::testout = 0;
2909 SMESH_File("problemfaces").remove();
2910 SMESH_File("occmesh.rep").remove();
2913 //================================================================================
2915 * \brief Read mesh entities preventing successful computation from "test.out" file
2917 //================================================================================
2919 SMESH_ComputeErrorPtr
2920 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
2922 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
2923 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
2924 SMESH_File file("test.out");
2926 const char* badEdgeStr = " multiple times in surface mesh";
2927 const int badEdgeStrLen = strlen( badEdgeStr );
2928 while( !file.eof() )
2930 if ( strncmp( file, "Edge ", 5 ) == 0 &&
2931 file.getInts( two ) &&
2932 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
2933 two[0] < nodeVec.size() && two[1] < nodeVec.size())
2935 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
2936 file += badEdgeStrLen;
2938 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
2941 // openelement 18 with open element 126
2944 vector<int> three1(3), three2(3);
2946 const char* pos = file;
2947 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
2948 ok = ok && file.getInts( two );
2949 ok = ok && file.getInts( three1 );
2950 ok = ok && file.getInts( three2 );
2951 for ( int i = 0; ok && i < 3; ++i )
2952 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
2953 for ( int i = 0; ok && i < 3; ++i )
2954 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
2957 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
2958 nodeVec[ three1[1]],
2959 nodeVec[ three1[2]]));
2960 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
2961 nodeVec[ three2[1]],
2962 nodeVec[ three2[2]]));
2963 err->myComment = "Intersecting triangles";
2978 //================================================================================
2980 * \brief Write a python script creating an equivalent SALOME mesh.
2981 * This is useful to see what mesh is passed as input for the next step of mesh
2982 * generation (of mesh of higher dimension)
2984 //================================================================================
2986 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
2987 const std::string& pyFile)
2989 ofstream outfile(pyFile.c_str(), ios::out);
2990 if ( !outfile ) return;
2992 outfile << "import smesh, SMESH" << endl
2993 << "mesh = smesh.Mesh()" << endl << endl;
2995 using namespace netgen;
2997 for (pi = PointIndex::BASE;
2998 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3000 outfile << "mesh.AddNode( ";
3001 outfile << (*ngMesh)[pi](0) << ", ";
3002 outfile << (*ngMesh)[pi](1) << ", ";
3003 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3006 int nbDom = ngMesh->GetNDomains();
3007 for ( int i = 0; i < nbDom; ++i )
3008 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3010 SurfaceElementIndex sei;
3011 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3013 outfile << "mesh.AddFace([ ";
3014 Element2d sel = (*ngMesh)[sei];
3015 for (int j = 0; j < sel.GetNP(); j++)
3016 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3017 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3020 if ((*ngMesh)[sei].GetIndex())
3022 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3023 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3024 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3025 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3029 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3031 Element el = (*ngMesh)[ei];
3032 outfile << "mesh.AddVolume([ ";
3033 for (int j = 0; j < el.GetNP(); j++)
3034 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3038 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3040 const Segment & seg = ngMesh->LineSegment (i);
3041 outfile << "mesh.AddEdge([ "
3043 << seg[1] << " ])" << endl;
3045 cout << "Write " << pyFile << endl;
3048 //================================================================================
3050 * \brief Constructor of NETGENPlugin_ngMeshInfo
3052 //================================================================================
3054 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3059 _nbNodes = ngMesh->GetNP();
3060 _nbSegments = ngMesh->GetNSeg();
3061 _nbFaces = ngMesh->GetNSE();
3062 _nbVolumes = ngMesh->GetNE();
3066 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3070 //================================================================================
3072 * \brief Copy LocalH member from one netgen mesh to another
3074 //================================================================================
3076 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3077 netgen::Mesh* toMesh )
3079 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3080 if ( !toMesh->LocalHFunctionGenerated() )
3082 toMesh->CalcLocalH(netgen::mparam.grading);
3084 toMesh->CalcLocalH();
3087 const size_t size = sizeof( netgen::LocalH );
3088 _copyOfLocalH = new char[ size ];
3089 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3090 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3093 //================================================================================
3095 * \brief Restore LocalH member of a netgen mesh
3097 //================================================================================
3099 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3101 if ( _copyOfLocalH )
3103 const size_t size = sizeof( netgen::LocalH );
3104 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3105 delete [] _copyOfLocalH;
3110 //================================================================================
3112 * \brief Find "internal" sub-shapes
3114 //================================================================================
3116 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3117 const TopoDS_Shape& shape,
3119 : _mesh( mesh ), _is3D( is3D )
3121 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3123 TopExp_Explorer f,e;
3124 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3126 int faceID = meshDS->ShapeToIndex( f.Current() );
3128 // find not computed internal edges
3130 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3131 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3133 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3134 if ( eSM->IsEmpty() )
3136 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3137 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3138 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3142 // find internal vertices in a face
3143 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3144 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3145 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3147 int vID = meshDS->ShapeToIndex( fSub.Value() );
3148 if ( intVV.insert( vID ).second )
3149 _f2v[ faceID ].push_back( vID );
3154 // find internal faces and their subshapes where nodes are to be doubled
3155 // to make a crack with non-sewed borders
3157 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3159 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3162 list< TopoDS_Shape > edges;
3163 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3164 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3166 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3167 edges.push_back( e.Current() );
3168 // find border faces
3169 PShapeIteratorPtr fIt =
3170 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3171 while ( const TopoDS_Shape* pFace = fIt->next() )
3172 if ( !pFace->IsSame( f.Current() ))
3173 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3176 // we consider vertex internal if it is shared by more than one internal edge
3177 list< TopoDS_Shape >::iterator edge = edges.begin();
3178 for ( ; edge != edges.end(); ++edge )
3179 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3181 set<int> internalEdges;
3182 PShapeIteratorPtr eIt =
3183 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3184 while ( const TopoDS_Shape* pEdge = eIt->next() )
3186 int edgeID = meshDS->ShapeToIndex( *pEdge );
3187 if ( isInternalShape( edgeID ))
3188 internalEdges.insert( edgeID );
3190 if ( internalEdges.size() > 1 )
3191 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3195 } // loop on geom faces
3197 // find vertices internal in solids
3200 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3202 int soID = meshDS->ShapeToIndex( so.Current() );
3203 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3204 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3205 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3210 //================================================================================
3212 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3213 * some nodes of which are to be doubled to make the second border of the "crack"
3215 //================================================================================
3217 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3219 if ( _intShapes.empty() ) return;
3221 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3222 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3224 // loop on internal geom edges
3225 set<int>::const_iterator intShapeId = _intShapes.begin();
3226 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3228 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3229 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3231 // get internal and non-internal geom faces sharing the internal edge <s>
3233 set<int>::iterator bordFace = _borderFaces.end();
3234 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3235 while ( const TopoDS_Shape* pFace = faces->next() )
3237 int faceID = meshDS->ShapeToIndex( *pFace );
3238 if ( isInternalShape( faceID ))
3241 bordFace = _borderFaces.insert( faceID ).first;
3243 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3245 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3246 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3247 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3248 int nbSuspectFaces = 0;
3249 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3250 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3251 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3252 while ( smIt->more() )
3254 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3255 if ( !sm ) continue;
3256 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3257 while ( nIt->more() )
3259 const SMDS_MeshNode* nOnEdge = nIt->next();
3260 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3261 while ( fIt->more() )
3263 const SMDS_MeshElement* f = fIt->next();
3264 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3265 if ( intFaceSM->Contains( f ))
3267 for ( int i = 0; i < nbNodes; ++i )
3268 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3273 for ( int i = 0; i < nbNodes; ++i )
3274 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3276 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3282 // suspectFaces[0] having link with same orientation as mesh faces on
3283 // the internal geom face are <borderElems>. suspectFaces[1] have
3284 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3285 // by links of <borderElems> found at the 1st and 2nd loops
3286 set< SMESH_OrientedLink > borderLinks;
3287 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3289 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3290 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3292 const SMDS_MeshElement* f = *fIt;
3293 bool isBorder = false, linkFound = false, borderLinkFound = false;
3294 list< SMESH_OrientedLink > faceLinks;
3295 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3296 for ( int i = 0; i < nbNodes; ++i )
3298 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3299 faceLinks.push_back( link );
3302 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3303 if ( foundLink != links.end() )
3306 isBorder = ( foundLink->_reversed == link._reversed );
3307 if ( !isBorder && !isPostponed ) break;
3308 faceLinks.pop_back();
3310 else if ( isPostponed && !borderLinkFound )
3312 foundLink = borderLinks.find( link );
3313 if ( foundLink != borderLinks.end() )
3315 borderLinkFound = true;
3316 isBorder = ( foundLink->_reversed != link._reversed );
3323 borderElems.insert( f );
3324 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3326 else if ( !linkFound && !borderLinkFound )
3328 suspectFaces[1].push_back( f );
3329 if ( nbF > 2 * nbSuspectFaces )
3330 break; // dead loop protection
3337 //================================================================================
3339 * \brief put internal shapes in maps and fill in submeshes to precompute
3341 //================================================================================
3343 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3344 TopTools_IndexedMapOfShape& emap,
3345 TopTools_IndexedMapOfShape& vmap,
3346 list< SMESH_subMesh* > smToPrecompute[])
3348 if ( !hasInternalEdges() ) return;
3349 map<int,int>::const_iterator ev_face = _e2face.begin();
3350 for ( ; ev_face != _e2face.end(); ++ev_face )
3352 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3353 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3355 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3357 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3359 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3363 //================================================================================
3365 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3367 //================================================================================
3369 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3370 TopTools_IndexedMapOfShape& emap,
3371 list< SMESH_subMesh* >& intFaceSM,
3372 list< SMESH_subMesh* >& boundarySM)
3374 if ( !hasInternalFaces() ) return;
3376 // <fmap> and <emap> are for not yet meshed shapes
3377 // <intFaceSM> is for submeshes of faces
3378 // <boundarySM> is for meshed edges and vertices
3383 set<int> shapeIDs ( _intShapes );
3384 if ( !_borderFaces.empty() )
3385 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3387 set<int>::const_iterator intS = shapeIDs.begin();
3388 for ( ; intS != shapeIDs.end(); ++intS )
3390 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3392 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3394 intFaceSM.push_back( sm );
3396 // add submeshes of not computed internal faces
3397 if ( !sm->IsEmpty() ) continue;
3399 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3400 while ( smIt->more() )
3403 const TopoDS_Shape& s = sm->GetSubShape();
3405 if ( sm->IsEmpty() )
3408 switch ( s.ShapeType() ) {
3409 case TopAbs_FACE: fmap.Add ( s ); break;
3410 case TopAbs_EDGE: emap.Add ( s ); break;
3416 if ( s.ShapeType() != TopAbs_FACE )
3417 boundarySM.push_back( sm );
3423 //================================================================================
3425 * \brief Return true if given shape is to be precomputed in order to be correctly
3426 * added to netgen mesh
3428 //================================================================================
3430 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3432 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3433 switch ( s.ShapeType() ) {
3434 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3435 case TopAbs_EDGE : return isInternalEdge( shapeID );
3436 case TopAbs_VERTEX: break;
3442 //================================================================================
3444 * \brief Return SMESH
3446 //================================================================================
3448 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3450 return const_cast<SMESH_Mesh&>( _mesh );
3453 //================================================================================
3455 * \brief Initialize netgen library
3457 //================================================================================
3459 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3463 _isComputeOk = false;
3464 _outputFileName = getOutputFileName();
3465 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3466 netgen::myerr = netgen::mycout;
3467 cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3469 _ngMesh = Ng_NewMesh();
3472 //================================================================================
3474 * \brief Finish using netgen library
3476 //================================================================================
3478 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3480 Ng_DeleteMesh( _ngMesh );
3482 NETGENPlugin_Mesher::RemoveTmpFiles();
3487 //================================================================================
3489 * \brief Set netgen mesh to delete at destruction
3491 //================================================================================
3493 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3496 Ng_DeleteMesh( _ngMesh );
3500 //================================================================================
3502 * \brief Return a unique file name
3504 //================================================================================
3506 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3508 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3510 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3511 aGenericName += "NETGEN_";
3512 aGenericName += getpid();
3513 aGenericName += "_";
3514 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3515 aGenericName += ".out";
3517 return aGenericName.ToCString();
3520 //================================================================================
3522 * \brief Remove file with netgen output
3524 //================================================================================
3526 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3528 string tmpDir = SALOMEDS_Tool::GetDirFromPath( _outputFileName );
3529 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3531 std::string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3532 aFiles[0] = aFileName.c_str();
3533 if ( netgen::mycout)
3535 delete netgen::mycout;
3540 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
3541 cout << "NOTE: netgen output log was REMOVED " << _outputFileName << endl;