1 // NETGENPlugin : C++ implementation
3 // Copyright (C) 2006 OPEN CASCADE, CEA/DEN, EDF R&D
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : NETGENPlugin_Mesher.cxx
23 // Author : Michael Sazonov (OCN)
27 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
33 #include <SMESH_Mesh.hxx>
34 #include <SMESH_Comment.hxx>
35 #include <SMESH_ComputeError.hxx>
36 #include <SMESH_subMesh.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMDS_MeshElement.hxx>
39 #include <SMDS_MeshNode.hxx>
40 #include <utilities.h>
44 #include <BRep_Tool.hxx>
46 #include <TopExp_Explorer.hxx>
48 #include <NCollection_Map.hxx>
49 #include <OSD_Path.hxx>
50 #include <OSD_File.hxx>
51 #include <TCollection_AsciiString.hxx>
53 // Netgen include files
58 #include <occgeom.hpp>
59 #include <meshing.hpp>
60 //#include <ngexception.hpp>
62 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
63 extern MeshingParameters mparam;
66 //=============================================================================
70 //=============================================================================
72 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
73 const TopoDS_Shape& aShape,
80 // Initialize global NETGEN parameters by default values:
81 // maximal mesh edge size
82 netgen::mparam.maxh = NETGENPlugin_Hypothesis::GetDefaultMaxSize();
83 // minimal number of segments per edge
84 netgen::mparam.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
85 // rate of growth of size between elements
86 netgen::mparam.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
87 // safety factor for curvatures (elements per radius)
88 netgen::mparam.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
89 // create elements of second order
90 netgen::mparam.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder() ? 1 : 0;
91 // quad-dominated surface meshing
93 netgen::mparam.quad = 0;
95 netgen::mparam.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed() ? 1 : 0;
98 //=============================================================================
100 * Pass parameters to NETGEN
102 //=============================================================================
103 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
107 // Initialize global NETGEN parameters:
108 // maximal mesh segment size
109 netgen::mparam.maxh = hyp->GetMaxSize();
110 // minimal number of segments per edge
111 netgen::mparam.segmentsperedge = hyp->GetNbSegPerEdge();
112 // rate of growth of size between elements
113 netgen::mparam.grading = hyp->GetGrowthRate();
114 // safety factor for curvatures (elements per radius)
115 netgen::mparam.curvaturesafety = hyp->GetNbSegPerRadius();
116 // create elements of second order
117 netgen::mparam.secondorder = hyp->GetSecondOrder() ? 1 : 0;
118 // quad-dominated surface meshing
119 // only triangles are allowed for volumic mesh
121 netgen::mparam.quad = static_cast<const NETGENPlugin_Hypothesis_2D*>
122 (hyp)->GetQuadAllowed() ? 1 : 0;
123 _optimize = hyp->GetOptimize();
127 //=============================================================================
129 * Link - a pair of integer numbers
131 //=============================================================================
135 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
136 Link() : n1(0), n2(0) {}
139 int HashCode(const Link& aLink, int aLimit)
141 return HashCode(aLink.n1 + aLink.n2, aLimit);
144 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
146 return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
147 aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
150 //================================================================================
152 * \brief Initialize netgen::OCCGeometry with OCCT shape
154 //================================================================================
156 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
157 const TopoDS_Shape& shape)
159 occgeo.shape = shape;
162 BRepTools::Clean (shape);
163 BRepMesh_IncrementalMesh::BRepMesh_IncrementalMesh (shape, 0.01, true);
165 BRepBndLib::Add (shape, bb);
166 double x1,y1,z1,x2,y2,z2;
167 bb.Get (x1,y1,z1,x2,y2,z2);
168 MESSAGE("shape bounding box:\n" <<
169 "(" << x1 << " " << y1 << " " << z1 << ") " <<
170 "(" << x2 << " " << y2 << " " << z2 << ")");
171 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
172 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
173 occgeo.boundingbox = netgen::Box<3> (p1,p2);
176 //=============================================================================
178 * Here we are going to use the NETGEN mesher
180 //=============================================================================
181 bool NETGENPlugin_Mesher::Compute()
183 MESSAGE("Compute with:\n"
184 " max size = " << netgen::mparam.maxh << "\n"
185 " segments per edge = " << netgen::mparam.segmentsperedge);
187 " growth rate = " << netgen::mparam.grading << "\n"
188 " elements per radius = " << netgen::mparam.curvaturesafety << "\n"
189 " second order = " << netgen::mparam.secondorder << "\n"
190 " quad allowed = " << netgen::mparam.quad);
192 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
195 // -------------------------
196 // Prepare OCC geometry
197 // -------------------------
199 netgen::OCCGeometry occgeo;
200 PrepareOCCgeometry( occgeo, _shape );
202 // -------------------------
204 // -------------------------
206 netgen::Mesh *ngMesh = NULL;
207 // we start always with ANALYSE,
208 // but end depending on _optimize and _isVolume
209 int startWith = netgen::MESHCONST_ANALYSE;
210 int endWith = (_optimize
211 ? (_isVolume ? netgen::MESHCONST_OPTVOLUME : netgen::MESHCONST_OPTSURFACE)
212 : netgen::MESHCONST_MESHSURFACE);
216 SMESH_Comment comment;
219 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
220 if (err) comment << "Error in netgen::OCCGenerateMesh()";
221 if (!err && !_optimize)
223 // we have got surface mesh only, so generate volume mesh
224 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
225 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
226 if (err) comment << "Error in netgen::OCCGenerateMesh()";
228 if (!err && netgen::mparam.secondorder > 0)
230 netgen::OCCRefinementSurfaces ref (occgeo);
231 ref.MakeSecondOrder (*ngMesh);
234 catch (netgen::NgException exc)
236 error->myName = err = COMPERR_ALGO_FAILED;
237 comment << exc.What();
240 int nbNod = ngMesh->GetNP();
241 int nbSeg = ngMesh->GetNSeg();
242 int nbFac = ngMesh->GetNSE();
243 int nbVol = ngMesh->GetNE();
245 MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
246 ", nb nodes: " << nbNod <<
247 ", nb segments: " << nbSeg <<
248 ", nb faces: " << nbFac <<
249 ", nb volumes: " << nbVol);
251 // -----------------------------------------------------------
252 // Feed back the SMESHDS with the generated Nodes and Elements
253 // -----------------------------------------------------------
255 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
256 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
257 if ( true /*isOK*/ ) // get whatever built
259 // vector of nodes in which node index == netgen ID
260 vector< SMDS_MeshNode* > nodeVec ( nbNod + 1 );
261 // map of nodes assigned to submeshes
262 NCollection_Map<int> pindMap;
263 // create and insert nodes into nodeVec
265 for (i = 1; i <= nbNod /*&& isOK*/; ++i )
267 const netgen::MeshPoint& ngPoint = ngMesh->Point(i);
268 SMDS_MeshNode* node = NULL;
269 bool newNodeOnVertex = false;
271 if (i <= occgeo.vmap.Extent())
274 aVert = TopoDS::Vertex(occgeo.vmap(i));
275 SMESHDS_SubMesh * submesh = meshDS->MeshElements(aVert);
278 SMDS_NodeIteratorPtr it = submesh->GetNodes();
281 node = const_cast<SMDS_MeshNode*> (it->next());
286 newNodeOnVertex = true;
289 node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
292 MESSAGE("Cannot create a mesh node");
293 if ( !comment.size() ) comment << "Cannot create a mesh node";
294 nbSeg = nbFac = nbVol = isOK = 0;
297 nodeVec.at(i) = node;
301 meshDS->SetNodeOnVertex(node, aVert);
306 // create mesh segments along geometric edges
307 NCollection_Map<Link> linkMap;
308 for (i = 1; i <= nbSeg/* && isOK*/; ++i )
310 const netgen::Segment& seg = ngMesh->LineSegment(i);
311 Link link(seg.p1, seg.p2);
312 if (linkMap.Contains(link))
316 int pinds[3] = { seg.p1, seg.p2, seg.pmid };
319 for (int j=0; j < 3; ++j)
322 if (pind <= 0) continue;
329 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
330 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
331 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
333 param = seg.epgeominfo[j].dist;
337 param = param2 * 0.5;
338 if (pindMap.Contains(pind))
342 meshDS->SetNodeOnEdge(nodeVec.at(pind), aEdge, param);
347 if (nbp < 3) // second order ?
348 edge = meshDS->AddEdge(nodeVec.at(pinds[0]), nodeVec.at(pinds[1]));
350 edge = meshDS->AddEdge(nodeVec.at(pinds[0]), nodeVec.at(pinds[1]),
351 nodeVec.at(pinds[2]));
354 if ( !comment.size() ) comment << "Cannot create a mesh edge";
355 MESSAGE("Cannot create a mesh edge");
356 nbSeg = nbFac = nbVol = isOK = 0;
360 meshDS->SetMeshElementOnShape(edge, aEdge);
363 // create mesh faces along geometric faces
364 for (i = 1; i <= nbFac/* && isOK*/; ++i )
366 const netgen::Element2d& elem = ngMesh->SurfaceElement(i);
367 int aGeomFaceInd = elem.GetIndex();
369 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
370 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
371 vector<SMDS_MeshNode*> nodes;
372 for (int j=1; j <= elem.GetNP(); ++j)
374 int pind = elem.PNum(j);
375 SMDS_MeshNode* node = nodeVec.at(pind);
376 nodes.push_back(node);
377 if (pindMap.Contains(pind))
381 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
382 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
386 SMDS_MeshFace* face = NULL;
387 switch (elem.GetType())
390 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
393 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
396 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
399 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
400 nodes[4],nodes[7],nodes[5],nodes[6]);
403 MESSAGE("NETGEN created a face of unexpected type, ignoring");
408 if ( !comment.size() ) comment << "Cannot create a mesh face";
409 MESSAGE("Cannot create a mesh face");
410 nbSeg = nbFac = nbVol = isOK = 0;
414 meshDS->SetMeshElementOnShape(face, aFace);
418 for (i = 1; i <= nbVol/* && isOK*/; ++i)
420 const netgen::Element& elem = ngMesh->VolumeElement(i);
421 int aSolidInd = elem.GetIndex();
423 if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
424 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
425 vector<SMDS_MeshNode*> nodes;
426 for (int j=1; j <= elem.GetNP(); ++j)
428 int pind = elem.PNum(j);
429 SMDS_MeshNode* node = nodeVec.at(pind);
430 nodes.push_back(node);
431 if (pindMap.Contains(pind))
433 if (!aSolid.IsNull())
436 meshDS->SetNodeInVolume(node, aSolid);
440 SMDS_MeshVolume* vol = NULL;
441 switch (elem.GetType())
444 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
447 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
448 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
451 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
456 if ( !comment.size() ) comment << "Cannot create a mesh volume";
457 MESSAGE("Cannot create a mesh volume");
458 nbSeg = nbFac = nbVol = isOK = 0;
461 if (!aSolid.IsNull())
462 meshDS->SetMeshElementOnShape(vol, aSolid);
466 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
467 error->myName = COMPERR_ALGO_FAILED;
468 if ( !comment.empty() )
469 error->myComment = comment;
471 // set bad compute error to subshapes of all failed subshapes shapes
472 if ( !error->IsOK() && err )
474 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
475 int status = occgeo.facemeshstatus[i-1];
476 if (status == 1 ) continue;
477 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
478 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
479 if ( !smError || smError->IsOK() ) {
481 smError.reset( new SMESH_ComputeError( error->myName, error->myComment ));
483 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
489 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
494 return error->IsOK();
497 //================================================================================
499 * \brief Remove "test.out" and "problemfaces" files in current directory
501 //================================================================================
503 void NETGENPlugin_Mesher::RemoveTmpFiles()
505 TCollection_AsciiString str("test.out");
506 OSD_Path path1( str );
507 OSD_File file1( path1 );
509 str = "problemfaces";
510 OSD_Path path2( str );
511 OSD_File file2( path2 );