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 #ifdef WITH_SMESH_CANCEL_COMPUTE
2138 if(netgen::multithread.terminate)
2141 comment << text(err);
2143 catch (Standard_Failure& ex)
2145 comment << text(ex);
2147 err = 0; //- MESHCONST_ANALYSE isn't so important step
2150 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2152 ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2156 // Pass 1D simple parameters to NETGEN
2157 // --------------------------------
2158 int nbSeg = _simpleHyp->GetNumberOfSegments();
2159 double segSize = _simpleHyp->GetLocalLength();
2160 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2162 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2164 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2165 setLocalSize( e, segSize, *ngMesh );
2168 else // if ( ! _simpleHyp )
2170 // Local size on vertices and edges
2171 // --------------------------------
2172 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2174 int key = (*it).first;
2175 double hi = (*it).second;
2176 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2177 const TopoDS_Edge& e = TopoDS::Edge(shape);
2178 setLocalSize( e, hi, *ngMesh );
2180 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2182 int key = (*it).first;
2183 double hi = (*it).second;
2184 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2185 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2186 gp_Pnt p = BRep_Tool::Pnt(v);
2187 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2189 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2190 it!=FaceId2LocalSize.end(); it++)
2192 int key = (*it).first;
2193 double val = (*it).second;
2194 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2195 int faceNgID = occgeo.fmap.FindIndex(shape);
2196 occgeo.SetFaceMaxH(faceNgID, val);
2197 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2198 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2202 // Precompute internal edges (issue 0020676) in order to
2203 // add mesh on them correctly (twice) to netgen mesh
2204 if ( !err && internals.hasInternalEdges() )
2206 // load internal shapes into OCCGeometry
2207 netgen::OCCGeometry intOccgeo;
2208 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2209 intOccgeo.boundingbox = occgeo.boundingbox;
2210 intOccgeo.shape = occgeo.shape;
2211 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2212 intOccgeo.face_maxh = netgen::mparam.maxh;
2213 netgen::Mesh *tmpNgMesh = NULL;
2217 // compute local H on internal shapes in the main mesh
2218 //OCCSetLocalMeshSize(intOccgeo, *ngMesh); it deletes ngMesh->localH
2220 // let netgen create a temporary mesh
2222 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2224 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2226 #ifdef WITH_SMESH_CANCEL_COMPUTE
2227 if(netgen::multithread.terminate)
2230 // copy LocalH from the main to temporary mesh
2231 initState.transferLocalH( ngMesh, tmpNgMesh );
2233 // compute mesh on internal edges
2234 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2236 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2238 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2240 comment << text(err);
2242 catch (Standard_Failure& ex)
2244 comment << text(ex);
2247 initState.restoreLocalH( tmpNgMesh );
2249 // fill SMESH by netgen mesh
2250 vector< const SMDS_MeshNode* > tmpNodeVec;
2251 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2252 err = ( err || !comment.empty() );
2254 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2257 // Fill ngMesh with nodes and segments of computed submeshes
2260 err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2261 FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
2263 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2268 startWith = endWith = netgen::MESHCONST_MESHEDGES;
2273 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2275 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2277 #ifdef WITH_SMESH_CANCEL_COMPUTE
2278 if(netgen::multithread.terminate)
2281 comment << text(err);
2283 catch (Standard_Failure& ex)
2285 comment << text(ex);
2289 mparams.uselocalh = true; // restore as it is used at surface optimization
2291 // ---------------------
2292 // compute surface mesh
2293 // ---------------------
2296 // Pass 2D simple parameters to NETGEN
2298 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2300 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2301 mparams.grading = 0.4; // moderate size growth
2304 // length from edges
2305 if ( ngMesh->GetNSeg() ) {
2306 double edgeLength = 0;
2307 TopTools_MapOfShape visitedEdges;
2308 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2309 if( visitedEdges.Add(exp.Current()) )
2310 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2311 // we have to multiply length by 2 since for each TopoDS_Edge there
2312 // are double set of NETGEN edges, in other words, we have to
2313 // divide ngMesh->GetNSeg() by 2.
2314 mparams.maxh = 2*edgeLength / ngMesh->GetNSeg();
2317 mparams.maxh = 1000;
2319 mparams.grading = 0.2; // slow size growth
2321 mparams.quad = _simpleHyp->GetAllowQuadrangles();
2322 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2323 ngMesh->SetGlobalH (mparams.maxh);
2324 netgen::Box<3> bb = occgeo.GetBoundingBox();
2325 bb.Increase (bb.Diam()/20);
2326 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2329 // Care of vertices internal in faces (issue 0020676)
2330 if ( internals.hasInternalVertexInFace() )
2332 // store computed segments in SMESH in order not to create SMESH
2333 // edges for ng segments added by AddIntVerticesInFaces()
2334 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2335 // add segments to faces with internal vertices
2336 AddIntVerticesInFaces( occgeo, *ngMesh, nodeVec, internals );
2337 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2340 // Build viscous layers
2341 if ( _isViscousLayers2D )
2343 if ( !internals.hasInternalVertexInFace() ) {
2344 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2345 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2347 SMESH_ProxyMesh::Ptr viscousMesh;
2348 SMESH_MesherHelper helper( *_mesh );
2349 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2351 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2352 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2355 // exclude from computation ng segments built on EDGEs of F
2356 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
2358 netgen::Segment & seg = ngMesh->LineSegment(i);
2359 if (seg.si == faceID)
2362 // add new segments to ngMesh instead of excluded ones
2363 helper.SetSubShape( F );
2365 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2366 error, viscousMesh );
2367 error = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
2369 if ( !error ) error = SMESH_ComputeError::New();
2371 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2374 // Let netgen compute 2D mesh
2375 startWith = netgen::MESHCONST_MESHSURFACE;
2376 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2381 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2383 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2385 #ifdef WITH_SMESH_CANCEL_COMPUTE
2386 if(netgen::multithread.terminate)
2389 comment << text (err);
2391 catch (Standard_Failure& ex)
2393 comment << text(ex);
2394 //err = 1; -- try to make volumes anyway
2396 catch (netgen::NgException exc)
2398 comment << text(exc);
2399 //err = 1; -- try to make volumes anyway
2402 // ---------------------
2403 // generate volume mesh
2404 // ---------------------
2405 // Fill ngMesh with nodes and faces of computed 2D submeshes
2406 if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2408 // load SMESH with computed segments and faces
2409 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2411 // compute pyramids on quadrangles
2412 SMESH_ProxyMesh::Ptr proxyMesh;
2413 if ( _mesh->NbQuadrangles() > 0 )
2414 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2416 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2417 proxyMesh.reset( Adaptor );
2419 int nbPyrams = _mesh->NbPyramids();
2420 Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2421 if ( nbPyrams != _mesh->NbPyramids() )
2423 list< SMESH_subMesh* > quadFaceSM;
2424 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2425 if ( Adaptor->GetProxySubMesh( face.Current() ))
2427 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2428 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2430 FillNgMesh(occgeo, *ngMesh, nodeVec, quadFaceSM, proxyMesh);
2433 // fill ngMesh with faces of sub-meshes
2434 err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
2435 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2436 //toPython( ngMesh, "/tmp/ngPython.py");
2438 if (!err && _isVolume)
2440 // Pass 3D simple parameters to NETGEN
2441 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2442 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2444 if ( double vol = simple3d->GetMaxElementVolume() ) {
2446 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2447 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2450 // length from faces
2451 mparams.maxh = ngMesh->AverageH();
2453 ngMesh->SetGlobalH (mparams.maxh);
2454 mparams.grading = 0.4;
2456 ngMesh->CalcLocalH(mparams.grading);
2458 ngMesh->CalcLocalH();
2461 // Care of vertices internal in solids and internal faces (issue 0020676)
2462 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2464 // store computed faces in SMESH in order not to create SMESH
2465 // faces for ng faces added here
2466 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2467 // add ng faces to solids with internal vertices
2468 AddIntVerticesInSolids( occgeo, *ngMesh, nodeVec, internals );
2469 // duplicate mesh faces on internal faces
2470 FixIntFaces( occgeo, *ngMesh, internals );
2471 initState = NETGENPlugin_ngMeshInfo(ngMesh);
2473 // Let netgen compute 3D mesh
2474 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2479 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2481 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2483 #ifdef WITH_SMESH_CANCEL_COMPUTE
2484 if(netgen::multithread.terminate)
2487 if ( comment.empty() ) // do not overwrite a previos error
2488 comment << text(err);
2490 catch (Standard_Failure& ex)
2492 if ( comment.empty() ) // do not overwrite a previos error
2493 comment << text(ex);
2496 catch (netgen::NgException exc)
2498 if ( comment.empty() ) // do not overwrite a previos error
2499 comment << text(exc);
2502 // Let netgen optimize 3D mesh
2503 if ( !err && _optimize )
2505 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2510 err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2512 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2514 #ifdef WITH_SMESH_CANCEL_COMPUTE
2515 if(netgen::multithread.terminate)
2518 if ( comment.empty() ) // do not overwrite a previos error
2519 comment << text(err);
2521 catch (Standard_Failure& ex)
2523 if ( comment.empty() ) // do not overwrite a previos error
2524 comment << text(ex);
2526 catch (netgen::NgException exc)
2528 if ( comment.empty() ) // do not overwrite a previos error
2529 comment << text(exc);
2533 if (!err && mparams.secondorder > 0)
2538 netgen::OCCRefinementSurfaces ref (occgeo);
2539 ref.MakeSecondOrder (*ngMesh);
2541 catch (Standard_Failure& ex)
2543 if ( comment.empty() ) // do not overwrite a previos error
2544 comment << "Exception in netgen at passing to 2nd order ";
2546 catch (netgen::NgException exc)
2548 if ( comment.empty() ) // do not overwrite a previos error
2549 comment << exc.What();
2553 int nbNod = ngMesh->GetNP();
2554 int nbSeg = ngMesh->GetNSeg();
2555 int nbFac = ngMesh->GetNSE();
2556 int nbVol = ngMesh->GetNE();
2557 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2559 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2560 ", nb nodes: " << nbNod <<
2561 ", nb segments: " << nbSeg <<
2562 ", nb faces: " << nbFac <<
2563 ", nb volumes: " << nbVol);
2565 // Feed back the SMESHDS with the generated Nodes and Elements
2566 if ( true /*isOK*/ ) // get whatever built
2567 FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment ); //!<
2569 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2570 if ( readErr && !readErr->myBadElements.empty() )
2573 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2574 error->myName = COMPERR_ALGO_FAILED;
2575 if ( !comment.empty() )
2576 error->myComment = comment;
2578 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2579 // appear if the geometry contains coincident sub-shape due
2580 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2581 const int nbMaps = 2;
2582 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2583 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2584 for ( int iMap = 0; iMap < nbMaps; ++iMap )
2585 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2586 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2587 if ( !sm->IsMeshComputed() )
2588 sm->SetIsAlwaysComputed( true );
2590 // set bad compute error to subshapes of all failed sub-shapes
2591 if ( !error->IsOK() )
2593 bool pb2D = false, pb3D = false;
2594 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2595 int status = occgeo.facemeshstatus[i-1];
2596 if (status == 1 ) continue;
2597 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2598 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2599 if ( !smError || smError->IsOK() ) {
2601 smError.reset( new SMESH_ComputeError( *error ));
2603 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2604 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2605 smError->myName = COMPERR_WARNING;
2607 pb2D = pb2D || smError->IsKO();
2610 if ( !pb2D ) // all faces are OK
2611 for (int i = 1; i <= occgeo.somap.Extent(); i++)
2612 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2614 bool smComputed = nbVol && !sm->IsEmpty();
2615 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2617 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2618 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2619 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2621 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2622 if ( !smComputed && ( !smError || smError->IsOK() ))
2624 smError.reset( new SMESH_ComputeError( *error ));
2625 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2626 smError->myName = COMPERR_WARNING;
2628 pb3D = pb3D || ( smError && smError->IsKO() );
2630 if ( !pb2D && !pb3D )
2631 err = 0; // no fatal errors, only warnings
2634 ngLib._isComputeOk = !err;
2639 //=============================================================================
2643 //=============================================================================
2644 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2646 netgen::MeshingParameters& mparams = netgen::mparam;
2649 // -------------------------
2650 // Prepare OCC geometry
2651 // -------------------------
2652 netgen::OCCGeometry occgeo;
2653 list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2654 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2655 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2657 bool tooManyElems = false;
2658 const int hugeNb = std::numeric_limits<int>::max() / 100;
2663 // pass 1D simple parameters to NETGEN
2666 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2667 mparams.uselocalh = false;
2668 mparams.grading = 0.8; // not limitited size growth
2670 if ( _simpleHyp->GetNumberOfSegments() )
2672 mparams.maxh = occgeo.boundingbox.Diam();
2675 mparams.maxh = _simpleHyp->GetLocalLength();
2678 if ( mparams.maxh == 0.0 )
2679 mparams.maxh = occgeo.boundingbox.Diam();
2680 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2681 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2683 // let netgen create ngMesh and calculate element size on not meshed shapes
2684 NETGENPlugin_NetgenLibWrapper ngLib;
2685 netgen::Mesh *ngMesh = NULL;
2689 int startWith = netgen::MESHCONST_ANALYSE;
2690 int endWith = netgen::MESHCONST_MESHEDGES;
2692 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2694 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2696 #ifdef WITH_SMESH_CANCEL_COMPUTE
2697 if(netgen::multithread.terminate)
2700 ngLib.setMesh(( Ng_Mesh*) ngMesh );
2702 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2703 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2708 // Pass 1D simple parameters to NETGEN
2709 // --------------------------------
2710 int nbSeg = _simpleHyp->GetNumberOfSegments();
2711 double segSize = _simpleHyp->GetLocalLength();
2712 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2714 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2716 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2717 setLocalSize( e, segSize, *ngMesh );
2720 else // if ( ! _simpleHyp )
2722 // Local size on vertices and edges
2723 // --------------------------------
2724 for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2726 int key = (*it).first;
2727 double hi = (*it).second;
2728 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2729 const TopoDS_Edge& e = TopoDS::Edge(shape);
2730 setLocalSize( e, hi, *ngMesh );
2732 for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2734 int key = (*it).first;
2735 double hi = (*it).second;
2736 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2737 const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2738 gp_Pnt p = BRep_Tool::Pnt(v);
2739 NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2741 for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2742 it!=FaceId2LocalSize.end(); it++)
2744 int key = (*it).first;
2745 double val = (*it).second;
2746 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2747 int faceNgID = occgeo.fmap.FindIndex(shape);
2748 occgeo.SetFaceMaxH(faceNgID, val);
2749 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2750 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2753 // calculate total nb of segments and length of edges
2754 double fullLen = 0.0;
2756 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
2757 TopTools_DataMapOfShapeInteger Edge2NbSeg;
2758 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
2760 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2761 if( !Edge2NbSeg.Bind(E,0) )
2764 double aLen = SMESH_Algo::EdgeLength(E);
2767 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
2769 aVec.resize( SMDSEntity_Last, 0);
2771 fullNbSeg += aVec[ entity ];
2774 // store nb of segments computed by Netgen
2775 NCollection_Map<Link> linkMap;
2776 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
2778 const netgen::Segment& seg = ngMesh->LineSegment(i);
2779 Link link(seg[0], seg[1]);
2780 if ( !linkMap.Add( link )) continue;
2781 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
2782 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2784 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
2788 // store nb of nodes on edges computed by Netgen
2789 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
2790 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
2792 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
2793 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
2794 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
2796 fullNbSeg += aVec[ entity ];
2797 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
2799 if ( fullNbSeg == 0 )
2806 if ( double area = _simpleHyp->GetMaxElementArea() ) {
2808 mparams.maxh = sqrt(2. * area/sqrt(3.0));
2809 mparams.grading = 0.4; // moderate size growth
2812 // length from edges
2813 mparams.maxh = fullLen/fullNbSeg;
2814 mparams.grading = 0.2; // slow size growth
2817 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2818 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2820 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
2822 TopoDS_Face F = TopoDS::Face( exp.Current() );
2823 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
2825 BRepGProp::SurfaceProperties(F,G);
2826 double anArea = G.Mass();
2827 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
2829 if ( !tooManyElems )
2831 TopTools_MapOfShape egdes;
2832 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
2833 if ( egdes.Add( exp1.Current() ))
2834 nb1d += Edge2NbSeg.Find(exp1.Current());
2836 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
2837 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
2839 vector<int> aVec(SMDSEntity_Last, 0);
2840 if( mparams.secondorder > 0 ) {
2841 int nb1d_in = (nbFaces*3 - nb1d) / 2;
2842 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2843 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
2846 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
2847 aVec[SMDSEntity_Triangle] = nbFaces;
2849 aResMap[sm].swap(aVec);
2856 // pass 3D simple parameters to NETGEN
2857 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2858 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2860 if ( double vol = simple3d->GetMaxElementVolume() ) {
2862 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2863 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2866 // using previous length from faces
2868 mparams.grading = 0.4;
2869 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2872 BRepGProp::VolumeProperties(_shape,G);
2873 double aVolume = G.Mass();
2874 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
2875 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
2876 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
2877 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2878 vector<int> aVec(SMDSEntity_Last, 0 );
2879 if ( tooManyElems ) // avoid FPE
2881 aVec[SMDSEntity_Node] = hugeNb;
2882 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
2886 if( mparams.secondorder > 0 ) {
2887 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2888 aVec[SMDSEntity_Quad_Tetra] = nbVols;
2891 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2892 aVec[SMDSEntity_Tetra] = nbVols;
2895 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
2896 aResMap[sm].swap(aVec);
2902 //================================================================================
2904 * \brief Remove "test.out" and "problemfaces" files in current directory
2906 //================================================================================
2908 void NETGENPlugin_Mesher::RemoveTmpFiles()
2910 if ( SMESH_File("test.out").remove() && netgen::testout)
2912 delete netgen::testout;
2913 netgen::testout = 0;
2915 SMESH_File("problemfaces").remove();
2916 SMESH_File("occmesh.rep").remove();
2919 //================================================================================
2921 * \brief Read mesh entities preventing successful computation from "test.out" file
2923 //================================================================================
2925 SMESH_ComputeErrorPtr
2926 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
2928 SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
2929 (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
2930 SMESH_File file("test.out");
2932 const char* badEdgeStr = " multiple times in surface mesh";
2933 const int badEdgeStrLen = strlen( badEdgeStr );
2934 while( !file.eof() )
2936 if ( strncmp( file, "Edge ", 5 ) == 0 &&
2937 file.getInts( two ) &&
2938 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
2939 two[0] < nodeVec.size() && two[1] < nodeVec.size())
2941 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
2942 file += badEdgeStrLen;
2944 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
2947 // openelement 18 with open element 126
2950 vector<int> three1(3), three2(3);
2952 const char* pos = file;
2953 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
2954 ok = ok && file.getInts( two );
2955 ok = ok && file.getInts( three1 );
2956 ok = ok && file.getInts( three2 );
2957 for ( int i = 0; ok && i < 3; ++i )
2958 ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
2959 for ( int i = 0; ok && i < 3; ++i )
2960 ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
2963 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
2964 nodeVec[ three1[1]],
2965 nodeVec[ three1[2]]));
2966 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
2967 nodeVec[ three2[1]],
2968 nodeVec[ three2[2]]));
2969 err->myComment = "Intersecting triangles";
2984 //================================================================================
2986 * \brief Write a python script creating an equivalent SALOME mesh.
2987 * This is useful to see what mesh is passed as input for the next step of mesh
2988 * generation (of mesh of higher dimension)
2990 //================================================================================
2992 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
2993 const std::string& pyFile)
2995 ofstream outfile(pyFile.c_str(), ios::out);
2996 if ( !outfile ) return;
2998 outfile << "import smesh, SMESH" << endl
2999 << "mesh = smesh.Mesh()" << endl << endl;
3001 using namespace netgen;
3003 for (pi = PointIndex::BASE;
3004 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3006 outfile << "mesh.AddNode( ";
3007 outfile << (*ngMesh)[pi](0) << ", ";
3008 outfile << (*ngMesh)[pi](1) << ", ";
3009 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3012 int nbDom = ngMesh->GetNDomains();
3013 for ( int i = 0; i < nbDom; ++i )
3014 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3016 SurfaceElementIndex sei;
3017 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3019 outfile << "mesh.AddFace([ ";
3020 Element2d sel = (*ngMesh)[sei];
3021 for (int j = 0; j < sel.GetNP(); j++)
3022 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3023 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3026 if ((*ngMesh)[sei].GetIndex())
3028 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3029 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3030 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3031 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3035 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3037 Element el = (*ngMesh)[ei];
3038 outfile << "mesh.AddVolume([ ";
3039 for (int j = 0; j < el.GetNP(); j++)
3040 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3044 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3046 const Segment & seg = ngMesh->LineSegment (i);
3047 outfile << "mesh.AddEdge([ "
3049 << seg[1] << " ])" << endl;
3051 cout << "Write " << pyFile << endl;
3054 //================================================================================
3056 * \brief Constructor of NETGENPlugin_ngMeshInfo
3058 //================================================================================
3060 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3065 _nbNodes = ngMesh->GetNP();
3066 _nbSegments = ngMesh->GetNSeg();
3067 _nbFaces = ngMesh->GetNSE();
3068 _nbVolumes = ngMesh->GetNE();
3072 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3076 //================================================================================
3078 * \brief Copy LocalH member from one netgen mesh to another
3080 //================================================================================
3082 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3083 netgen::Mesh* toMesh )
3085 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3086 if ( !toMesh->LocalHFunctionGenerated() )
3088 toMesh->CalcLocalH(netgen::mparam.grading);
3090 toMesh->CalcLocalH();
3093 const size_t size = sizeof( netgen::LocalH );
3094 _copyOfLocalH = new char[ size ];
3095 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3096 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3099 //================================================================================
3101 * \brief Restore LocalH member of a netgen mesh
3103 //================================================================================
3105 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3107 if ( _copyOfLocalH )
3109 const size_t size = sizeof( netgen::LocalH );
3110 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3111 delete [] _copyOfLocalH;
3116 //================================================================================
3118 * \brief Find "internal" sub-shapes
3120 //================================================================================
3122 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
3123 const TopoDS_Shape& shape,
3125 : _mesh( mesh ), _is3D( is3D )
3127 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3129 TopExp_Explorer f,e;
3130 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3132 int faceID = meshDS->ShapeToIndex( f.Current() );
3134 // find not computed internal edges
3136 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3137 if ( e.Current().Orientation() == TopAbs_INTERNAL )
3139 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3140 if ( eSM->IsEmpty() )
3142 _e2face.insert( make_pair( eSM->GetId(), faceID ));
3143 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3144 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3148 // find internal vertices in a face
3149 set<int> intVV; // issue 0020850 where same vertex is twice in a face
3150 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3151 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3153 int vID = meshDS->ShapeToIndex( fSub.Value() );
3154 if ( intVV.insert( vID ).second )
3155 _f2v[ faceID ].push_back( vID );
3160 // find internal faces and their subshapes where nodes are to be doubled
3161 // to make a crack with non-sewed borders
3163 if ( f.Current().Orientation() == TopAbs_INTERNAL )
3165 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3168 list< TopoDS_Shape > edges;
3169 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3170 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3172 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3173 edges.push_back( e.Current() );
3174 // find border faces
3175 PShapeIteratorPtr fIt =
3176 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3177 while ( const TopoDS_Shape* pFace = fIt->next() )
3178 if ( !pFace->IsSame( f.Current() ))
3179 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3182 // we consider vertex internal if it is shared by more than one internal edge
3183 list< TopoDS_Shape >::iterator edge = edges.begin();
3184 for ( ; edge != edges.end(); ++edge )
3185 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3187 set<int> internalEdges;
3188 PShapeIteratorPtr eIt =
3189 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3190 while ( const TopoDS_Shape* pEdge = eIt->next() )
3192 int edgeID = meshDS->ShapeToIndex( *pEdge );
3193 if ( isInternalShape( edgeID ))
3194 internalEdges.insert( edgeID );
3196 if ( internalEdges.size() > 1 )
3197 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3201 } // loop on geom faces
3203 // find vertices internal in solids
3206 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3208 int soID = meshDS->ShapeToIndex( so.Current() );
3209 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3210 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3211 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3216 //================================================================================
3218 * \brief Find mesh faces on non-internal geom faces sharing internal edge
3219 * some nodes of which are to be doubled to make the second border of the "crack"
3221 //================================================================================
3223 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3225 if ( _intShapes.empty() ) return;
3227 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3228 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3230 // loop on internal geom edges
3231 set<int>::const_iterator intShapeId = _intShapes.begin();
3232 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3234 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3235 if ( s.ShapeType() != TopAbs_EDGE ) continue;
3237 // get internal and non-internal geom faces sharing the internal edge <s>
3239 set<int>::iterator bordFace = _borderFaces.end();
3240 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3241 while ( const TopoDS_Shape* pFace = faces->next() )
3243 int faceID = meshDS->ShapeToIndex( *pFace );
3244 if ( isInternalShape( faceID ))
3247 bordFace = _borderFaces.insert( faceID ).first;
3249 if ( bordFace == _borderFaces.end() || !intFace ) continue;
3251 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3252 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3253 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3254 int nbSuspectFaces = 0;
3255 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3256 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3257 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3258 while ( smIt->more() )
3260 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3261 if ( !sm ) continue;
3262 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3263 while ( nIt->more() )
3265 const SMDS_MeshNode* nOnEdge = nIt->next();
3266 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3267 while ( fIt->more() )
3269 const SMDS_MeshElement* f = fIt->next();
3270 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3271 if ( intFaceSM->Contains( f ))
3273 for ( int i = 0; i < nbNodes; ++i )
3274 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3279 for ( int i = 0; i < nbNodes; ++i )
3280 nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3282 suspectFaces[ nbDblNodes < 2 ].push_back( f );
3288 // suspectFaces[0] having link with same orientation as mesh faces on
3289 // the internal geom face are <borderElems>. suspectFaces[1] have
3290 // only one node on edge <s>, we decide on them later (at the 2nd loop)
3291 // by links of <borderElems> found at the 1st and 2nd loops
3292 set< SMESH_OrientedLink > borderLinks;
3293 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3295 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3296 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3298 const SMDS_MeshElement* f = *fIt;
3299 bool isBorder = false, linkFound = false, borderLinkFound = false;
3300 list< SMESH_OrientedLink > faceLinks;
3301 int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3302 for ( int i = 0; i < nbNodes; ++i )
3304 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3305 faceLinks.push_back( link );
3308 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3309 if ( foundLink != links.end() )
3312 isBorder = ( foundLink->_reversed == link._reversed );
3313 if ( !isBorder && !isPostponed ) break;
3314 faceLinks.pop_back();
3316 else if ( isPostponed && !borderLinkFound )
3318 foundLink = borderLinks.find( link );
3319 if ( foundLink != borderLinks.end() )
3321 borderLinkFound = true;
3322 isBorder = ( foundLink->_reversed != link._reversed );
3329 borderElems.insert( f );
3330 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3332 else if ( !linkFound && !borderLinkFound )
3334 suspectFaces[1].push_back( f );
3335 if ( nbF > 2 * nbSuspectFaces )
3336 break; // dead loop protection
3343 //================================================================================
3345 * \brief put internal shapes in maps and fill in submeshes to precompute
3347 //================================================================================
3349 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3350 TopTools_IndexedMapOfShape& emap,
3351 TopTools_IndexedMapOfShape& vmap,
3352 list< SMESH_subMesh* > smToPrecompute[])
3354 if ( !hasInternalEdges() ) return;
3355 map<int,int>::const_iterator ev_face = _e2face.begin();
3356 for ( ; ev_face != _e2face.end(); ++ev_face )
3358 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3359 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3361 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3363 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3365 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3369 //================================================================================
3371 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3373 //================================================================================
3375 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3376 TopTools_IndexedMapOfShape& emap,
3377 list< SMESH_subMesh* >& intFaceSM,
3378 list< SMESH_subMesh* >& boundarySM)
3380 if ( !hasInternalFaces() ) return;
3382 // <fmap> and <emap> are for not yet meshed shapes
3383 // <intFaceSM> is for submeshes of faces
3384 // <boundarySM> is for meshed edges and vertices
3389 set<int> shapeIDs ( _intShapes );
3390 if ( !_borderFaces.empty() )
3391 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3393 set<int>::const_iterator intS = shapeIDs.begin();
3394 for ( ; intS != shapeIDs.end(); ++intS )
3396 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3398 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3400 intFaceSM.push_back( sm );
3402 // add submeshes of not computed internal faces
3403 if ( !sm->IsEmpty() ) continue;
3405 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3406 while ( smIt->more() )
3409 const TopoDS_Shape& s = sm->GetSubShape();
3411 if ( sm->IsEmpty() )
3414 switch ( s.ShapeType() ) {
3415 case TopAbs_FACE: fmap.Add ( s ); break;
3416 case TopAbs_EDGE: emap.Add ( s ); break;
3422 if ( s.ShapeType() != TopAbs_FACE )
3423 boundarySM.push_back( sm );
3429 //================================================================================
3431 * \brief Return true if given shape is to be precomputed in order to be correctly
3432 * added to netgen mesh
3434 //================================================================================
3436 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3438 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3439 switch ( s.ShapeType() ) {
3440 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3441 case TopAbs_EDGE : return isInternalEdge( shapeID );
3442 case TopAbs_VERTEX: break;
3448 //================================================================================
3450 * \brief Return SMESH
3452 //================================================================================
3454 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3456 return const_cast<SMESH_Mesh&>( _mesh );
3459 //================================================================================
3461 * \brief Initialize netgen library
3463 //================================================================================
3465 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3469 _isComputeOk = false;
3470 _outputFileName = getOutputFileName();
3471 netgen::mycout = new ofstream ( _outputFileName.c_str() );
3472 cout << "NOTE: netgen output was redirected to file " << _outputFileName << endl;
3474 _ngMesh = Ng_NewMesh();
3477 //================================================================================
3479 * \brief Finish using netgen library
3481 //================================================================================
3483 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3485 Ng_DeleteMesh( _ngMesh );
3487 NETGENPlugin_Mesher::RemoveTmpFiles();
3492 //================================================================================
3494 * \brief Set netgen mesh to delete at destruction
3496 //================================================================================
3498 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3501 Ng_DeleteMesh( _ngMesh );
3505 //================================================================================
3507 * \brief Return a unique file name
3509 //================================================================================
3511 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3513 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3515 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3516 aGenericName += "NETGEN_";
3517 aGenericName += getpid();
3518 aGenericName += "_";
3519 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3520 aGenericName += ".out";
3522 return aGenericName.ToCString();
3525 //================================================================================
3527 * \brief Remove file with netgen output
3529 //================================================================================
3531 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3533 string tmpDir = SALOMEDS_Tool::GetDirFromPath( _outputFileName );
3534 SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3536 std::string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3537 aFiles[0] = aFileName.c_str();
3538 if ( netgen::mycout)
3540 delete netgen::mycout;
3544 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );