1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 //=============================================================================
24 // File : NETGENPlugin_NETGEN_3D.cxx
25 // Moved here from SMESH_NETGEN_3D.cxx
26 // Created : lundi 27 Janvier 2003
27 // Author : Nadir BOUHAMOU (CEA)
29 //=============================================================================
31 #include "NETGENPlugin_NETGEN_3D.hxx"
33 #include "NETGENPlugin_Hypothesis.hxx"
35 #include "DriverStep.hxx"
36 #include "DriverMesh.hxx"
37 #include "netgen_param.hxx"
39 #include <SMDS_MeshElement.hxx>
40 #include <SMDS_MeshNode.hxx>
41 #include <SMESHDS_Mesh.hxx>
42 #include <SMESH_Comment.hxx>
43 #include <SMESH_ControlsDef.hxx>
44 #include <SMESH_Gen.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MeshEditor.hxx>
47 #include <SMESH_MesherHelper.hxx>
48 #include <SMESH_subMesh.hxx>
49 #include <StdMeshers_MaxElementVolume.hxx>
50 #include <StdMeshers_QuadToTriaAdaptor.hxx>
51 #include <StdMeshers_ViscousLayers.hxx>
52 #include <SMESH_subMesh.hxx>
54 #include <BRepGProp.hxx>
55 #include <BRep_Tool.hxx>
56 #include <GProp_GProps.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
62 #include <Standard_Failure.hxx>
63 #include <Standard_ErrorHandler.hxx>
65 #include <utilities.h>
72 #include <boost/filesystem.hpp>
73 namespace fs = boost::filesystem;
82 #include <occgeom.hpp>
85 #include <ngexception.hpp>
88 #include <core/exception.hpp>
96 NETGENPLUGIN_DLL_HEADER
97 extern MeshingParameters mparam;
99 NETGENPLUGIN_DLL_HEADER
100 extern volatile multithreadt multithread;
102 using namespace nglib;
105 //=============================================================================
109 //=============================================================================
111 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
112 : SMESH_3D_Algo(hypId, gen)
115 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
116 _compatibleHypothesis.push_back("MaxElementVolume");
117 _compatibleHypothesis.push_back("NETGEN_Parameters");
118 _compatibleHypothesis.push_back("ViscousLayers");
120 _maxElementVolume = 0.;
122 _hypMaxElementVolume = NULL;
123 _hypParameters = NULL;
124 _viscousLayersHyp = NULL;
126 _requireShape = false; // can work without shape
129 //=============================================================================
133 //=============================================================================
135 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
139 //=============================================================================
143 //=============================================================================
145 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh& aMesh,
146 const TopoDS_Shape& aShape,
147 Hypothesis_Status& aStatus)
149 _hypMaxElementVolume = NULL;
150 _hypParameters = NULL;
151 _viscousLayersHyp = NULL;
152 _maxElementVolume = DBL_MAX;
154 // for correct work of GetProgress():
155 //netgen::multithread.percent = 0.;
156 //netgen::multithread.task = "Volume meshing";
157 _progressByTic = -1.;
159 list<const SMESHDS_Hypothesis*>::const_iterator itl;
160 //const SMESHDS_Hypothesis* theHyp;
162 const list<const SMESHDS_Hypothesis*>& hyps =
163 GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
164 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
165 if ( h == hyps.end())
167 aStatus = SMESH_Hypothesis::HYP_OK;
168 return true; // can work with no hypothesis
172 for ( ; h != hyps.end(); ++h )
174 if ( !_hypMaxElementVolume )
175 _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
176 if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
177 _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
178 if ( ! _hypParameters )
179 _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
181 if ( *h != _hypMaxElementVolume &&
182 *h != _viscousLayersHyp &&
183 *h != _hypParameters &&
184 !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
185 aStatus = HYP_INCOMPATIBLE;
187 if ( _hypMaxElementVolume && _hypParameters )
188 aStatus = HYP_INCOMPATIBLE;
189 else if ( aStatus == HYP_OK && _viscousLayersHyp )
190 error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
192 if ( _hypMaxElementVolume )
193 _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
195 return aStatus == HYP_OK;
199 void NETGENPlugin_NETGEN_3D::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
201 aParams.maxh = hyp->GetMaxSize();
202 aParams.minh = hyp->GetMinSize();
203 aParams.segmentsperedge = hyp->GetNbSegPerEdge();
204 aParams.grading = hyp->GetGrowthRate();
205 aParams.curvaturesafety = hyp->GetNbSegPerRadius();
206 aParams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
207 aParams.quad = hyp->GetQuadAllowed() ? 1 : 0;
208 aParams.optimize = hyp->GetOptimize();
209 aParams.fineness = hyp->GetFineness();
210 aParams.uselocalh = hyp->GetSurfaceCurvature();
211 aParams.merge_solids = hyp->GetFuseEdges();
212 aParams.chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
213 aParams.optsteps2d = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
214 aParams.optsteps3d = aParams.optimize ? hyp->GetNbVolOptSteps() : 0;
215 aParams.elsizeweight = hyp->GetElemSizeWeight();
216 aParams.opterrpow = hyp->GetWorstElemMeasure();
217 aParams.delaunay = hyp->GetUseDelauney();
218 aParams.checkoverlap = hyp->GetCheckOverlapping();
219 aParams.checkchartboundary = hyp->GetCheckChartBoundary();
222 aParams.meshsizefilename = hyp->GetMeshSizeFile();
225 aParams.meshsizefilename = hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
228 aParams.closeedgefac = 2;
230 aParams.closeedgefac = 0;
234 // wirte in a binary file the orientation for each 2D element of the mesh
235 void NETGENPlugin_NETGEN_3D::exportElementOrientation(SMESH_Mesh& aMesh,
236 const TopoDS_Shape& aShape,
237 netgen_params& aParams,
238 const std::string output_file)
240 SMESH_MesherHelper helper(aMesh);
241 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
242 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
243 std::map<vtkIdType, bool> elemOrientation;
245 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
247 const TopoDS_Shape& aShapeFace = exFa.Current();
248 int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
249 bool isInternalFace = internals.isInternalShape( faceID );
251 if ( !isInternalFace &&
252 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
253 // IsReversedSubMesh() can work wrong on strongly curved faces,
254 // so we use it as less as possible
255 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
257 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
258 if ( !aSubMeshDSFace ) continue;
260 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
261 if ( aParams._quadraticMesh &&
262 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
264 // add medium nodes of proxy triangles to helper (#16843)
265 while ( iteratorElem->more() )
266 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
268 iteratorElem = aSubMeshDSFace->GetElements();
270 while ( iteratorElem->more() ) // loop on elements on a geom face
273 const SMDS_MeshElement* elem = iteratorElem->next();
275 error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
276 if ( elem->NbCornerNodes() != 3 )
277 error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
278 elemOrientation[elem->GetID()] = isRev;
279 } // loop on elements on a face
280 } // loop on faces of a SOLID or SHELL
282 std::ofstream df(output_file, ios::out|ios::binary);
283 int size=elemOrientation.size();
285 df.write((char*)&size, sizeof(int));
286 for(auto const& [id, orient]:elemOrientation){
287 df.write((char*)&id, sizeof(vtkIdType));
288 df.write((char*)&orient, sizeof(bool));
293 int NETGENPlugin_NETGEN_3D::RemoteCompute(SMESH_Mesh& aMesh,
294 const TopoDS_Shape& aShape)
297 SMESH_Hypothesis::Hypothesis_Status hypStatus;
298 CheckHypothesis(aMesh, aShape, hypStatus);
300 // Temporary folder for run
301 fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
302 fs::create_directories(tmp_folder);
303 // Using MESH2D generated after all triangles where created.
304 fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh2D.med");
305 fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
306 fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
307 fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
308 // TODO: Remove that file we do not use it
309 fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
310 fs::path shape_file=tmp_folder / fs::path("shape.step");
311 fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
312 fs::path log_file=tmp_folder / fs::path("run_mesher.log");
313 //TODO: Handle variable mesh_name
314 std::string mesh_name = "Maillage_1";
317 export_shape(shape_file.string(), aShape);
319 netgen_params aParams;
320 FillParameters(_hypParameters, aParams);
322 export_netgen_params(param_file.string(), aParams);
324 // Exporting element orientation
325 exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
328 // Calling run_mesher
329 // TODO: check if we need to handle the .exe for windows
331 fs::path run_mesher_exe =
332 fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
335 fs::path("run_mesher");
336 cmd = run_mesher_exe.string() +
337 " NETGEN3D " + mesh_file.string() + " "
338 + shape_file.string() + " "
339 + param_file.string() + " "
340 + element_orientation_file.string() + " "
341 + new_element_file.string() + " "
342 + std::to_string(0) + " "
343 + output_mesh_file.string() +
344 " >> " + log_file.string();
346 //std::cout << "Running command: " << std::endl;
347 //std::cout << cmd << std::endl;
349 // Writing command in log
350 std::ofstream flog(log_file.string());
354 // TODO: Replace system by something else to handle redirection for windows
355 int ret = system(cmd.c_str());
357 // TODO: better error handling (display log ?)
360 //throw Exception("Meshing failed");
361 std::cerr << "Issue with command: " << std::endl;
362 std::cerr << cmd << std::endl;
368 std::ifstream df(new_element_file.string(), ios::binary);
370 int Netgen_NbOfNodes;
371 int Netgen_NbOfNodesNew;
372 int Netgen_NbOfTetra;
373 double Netgen_point[3];
374 int Netgen_tetrahedron[4];
377 SMESH_MesherHelper helper(aMesh);
379 int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
380 helper.SetElementsOnShape( true );
382 // Number of nodes in intial mesh
383 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
384 // Number of nodes added by netgen
385 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
387 // Filling nodevec (correspondence netgen numbering mesh numbering)
388 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
389 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
392 df.read((char*) &nodeID, sizeof(int));
393 nodeVec.at(nodeIndex) = nullptr;
394 SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
395 while(iteratorNode->more()){
396 const SMDS_MeshNode* node = iteratorNode->next();
397 if(node->GetID() == nodeID){
398 nodeVec.at(nodeIndex) = node;
402 if(nodeVec.at(nodeIndex) == nullptr){
403 std::cout << "Error could not identify id";
408 // Add new points and update nodeVec
409 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
411 df.read((char *) &Netgen_point, sizeof(double)*3);
413 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
419 df.read((char*) &Netgen_NbOfTetra, sizeof(int));
420 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
422 df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
423 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
424 nodeVec.at( Netgen_tetrahedron[1] ),
425 nodeVec.at( Netgen_tetrahedron[2] ),
426 nodeVec.at( Netgen_tetrahedron[3] ));
435 //=============================================================================
437 *Here we are going to use the NETGEN mesher
439 //=============================================================================
441 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
442 const TopoDS_Shape& aShape)
444 if(aMesh.IsParallel())
445 return RemoteCompute(aMesh, aShape);
447 netgen::multithread.terminate = 0;
448 netgen::multithread.task = "Volume meshing";
449 _progressByTic = -1.;
451 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
453 SMESH_MesherHelper helper(aMesh);
454 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
455 helper.SetElementsOnShape( true );
457 int Netgen_NbOfNodes = 0;
458 double Netgen_point[3];
459 int Netgen_triangle[3];
461 NETGENPlugin_NetgenLibWrapper ngLib;
462 Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
464 // vector of nodes in which node index == netgen ID
465 vector< const SMDS_MeshNode* > nodeVec;
467 const int invalid_ID = -1;
469 SMESH::Controls::Area areaControl;
470 SMESH::Controls::TSequenceOfXYZ nodesCoords;
472 // maps nodes to ng ID
473 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
474 typedef TNodeToIDMap::value_type TN2ID;
475 TNodeToIDMap nodeToNetgenID;
477 // find internal shapes
478 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
480 // ---------------------------------
481 // Feed the Netgen with surface mesh
482 // ---------------------------------
484 TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
485 bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
487 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
488 if ( _viscousLayersHyp )
490 netgen::multithread.percent = 3;
491 proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
495 if ( aMesh.NbQuadrangles() > 0 )
497 netgen::multithread.percent = 6;
498 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
499 Adaptor->Compute(aMesh,aShape,proxyMesh.get());
500 proxyMesh.reset( Adaptor );
503 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
505 const TopoDS_Shape& aShapeFace = exFa.Current();
506 int faceID = meshDS->ShapeToIndex( aShapeFace );
507 bool isInternalFace = internals.isInternalShape( faceID );
509 if ( checkReverse && !isInternalFace &&
510 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
511 // IsReversedSubMesh() can work wrong on strongly curved faces,
512 // so we use it as less as possible
513 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
515 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
516 if ( !aSubMeshDSFace ) continue;
518 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
519 if ( _quadraticMesh &&
520 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
522 // add medium nodes of proxy triangles to helper (#16843)
523 while ( iteratorElem->more() )
524 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
526 iteratorElem = aSubMeshDSFace->GetElements();
528 while ( iteratorElem->more() ) // loop on elements on a geom face
531 const SMDS_MeshElement* elem = iteratorElem->next();
533 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
534 if ( elem->NbCornerNodes() != 3 )
535 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
537 // Add nodes of triangles and triangles them-selves to netgen mesh
539 // add three nodes of triangle
540 bool hasDegen = false;
541 for ( int iN = 0; iN < 3; ++iN )
543 const SMDS_MeshNode* node = elem->GetNode( iN );
544 const int shapeID = node->getshapeId();
545 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
546 helper.IsDegenShape( shapeID ))
548 // ignore all nodes on degeneraged edge and use node on its vertex instead
549 TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
550 node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
553 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
554 if ( ngID == invalid_ID )
556 ngID = ++Netgen_NbOfNodes;
557 Netgen_point [ 0 ] = node->X();
558 Netgen_point [ 1 ] = node->Y();
559 Netgen_point [ 2 ] = node->Z();
560 Ng_AddPoint(Netgen_mesh, Netgen_point);
562 Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
565 if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
566 Netgen_triangle[0] == Netgen_triangle[2] ||
567 Netgen_triangle[2] == Netgen_triangle[1] ))
570 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
572 if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
574 swap( Netgen_triangle[1], Netgen_triangle[2] );
575 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
577 } // loop on elements on a face
578 } // loop on faces of a SOLID or SHELL
580 // insert old nodes into nodeVec
581 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
582 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
583 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
584 nodeVec[ n_id->second ] = n_id->first;
585 nodeToNetgenID.clear();
587 if ( internals.hasInternalVertexInSolid() )
589 netgen::OCCGeometry occgeo;
590 NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
591 (netgen::Mesh&) *Netgen_mesh,
597 // -------------------------
598 // Generate the volume mesh
599 // -------------------------
601 return (ngLib._isComputeOk = compute( aMesh, helper, nodeVec, ngLib ));
606 // void limitVolumeSize( netgen::Mesh* ngMesh,
609 // // get average h of faces
612 // for (int i = 1; i <= ngMesh->GetNSE(); i++)
614 // const netgen::Element2d& face = ngMesh->SurfaceElement(i);
615 // for (int j=1; j <= face.GetNP(); ++j)
617 // const netgen::PointIndex & i1 = face.PNumMod(j);
618 // const netgen::PointIndex & i2 = face.PNumMod(j+1);
621 // const netgen::Point3d & p1 = ngMesh->Point( i1 );
622 // const netgen::Point3d & p2 = ngMesh->Point( i2 );
623 // faceh += netgen::Dist2( p1, p2 );
628 // faceh = Sqrt( faceh / nbh );
631 // if ( faceh < 0.5 * maxh ) compareh = -1;
632 // else if ( faceh > 1.5 * maxh ) compareh = 1;
633 // else compareh = 0;
634 // // cerr << "faceh " << faceh << endl;
635 // // cerr << "init maxh " << maxh << endl;
636 // // cerr << "compareh " << compareh << endl;
638 // if ( compareh > 0 )
642 // // cerr << "maxh " << maxh << endl;
645 // netgen::Point3d pmin, pmax;
646 // ngMesh->GetBox( pmin, pmax, 0 );
647 // const double dx = pmax.X() - pmin.X();
648 // const double dy = pmax.Y() - pmin.Y();
649 // const double dz = pmax.Z() - pmin.Z();
651 // if ( ! & ngMesh->LocalHFunction() )
652 // ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
654 // // adjusted by SALOME_TESTS/Grids/smesh/bugs_08/I8
655 // const int nbX = Max( 2, int( dx / maxh * 2 ));
656 // const int nbY = Max( 2, int( dy / maxh * 2 ));
657 // const int nbZ = Max( 2, int( dz / maxh * 2 ));
659 // netgen::Point3d p;
660 // for ( int i = 0; i <= nbX; ++i )
662 // p.X() = pmin.X() + i * dx / nbX;
663 // for ( int j = 0; j <= nbY; ++j )
665 // p.Y() = pmin.Y() + j * dy / nbY;
666 // for ( int k = 0; k <= nbZ; ++k )
668 // p.Z() = pmin.Z() + k * dz / nbZ;
669 // ngMesh->RestrictLocalH( p, maxh );
676 //================================================================================
678 * \brief set parameters and generate the volume mesh
680 //================================================================================
682 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh& aMesh,
683 SMESH_MesherHelper& helper,
684 vector< const SMDS_MeshNode* >& nodeVec,
685 NETGENPlugin_NetgenLibWrapper& ngLib)
687 netgen::multithread.terminate = 0;
689 netgen::Mesh* ngMesh = ngLib._ngMesh;
690 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
691 int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
693 int startWith = netgen::MESHCONST_MESHVOLUME;
694 int endWith = netgen::MESHCONST_OPTVOLUME;
697 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
698 netgen::OCCGeometry occgeo;
700 if ( _hypParameters )
702 aMesher.SetParameters( _hypParameters );
704 if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
705 !_hypParameters->GetMeshSizeFile().empty() )
707 if ( ! &ngMesh->LocalHFunction() )
709 netgen::Point3d pmin, pmax;
710 ngMesh->GetBox( pmin, pmax, 0 );
711 ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
713 aMesher.SetLocalSize( occgeo, *ngMesh );
716 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
717 } catch (netgen::NgException & ex) {
718 return error( COMPERR_BAD_PARMETERS, ex.What() );
721 if ( !_hypParameters->GetOptimize() )
722 endWith = netgen::MESHCONST_MESHVOLUME;
724 else if ( _hypMaxElementVolume )
726 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
727 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
729 else if ( aMesh.HasShapeToMesh() )
731 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
732 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
736 netgen::Point3d pmin, pmax;
737 ngMesh->GetBox (pmin, pmax);
738 netgen::mparam.maxh = Dist(pmin, pmax)/2;
741 if ( !_hypParameters && aMesh.HasShapeToMesh() )
743 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
750 ngLib.CalcLocalH(ngMesh);
751 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
753 if(netgen::multithread.terminate)
756 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
758 catch (Standard_Failure& ex)
760 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
761 str << " at " << netgen::multithread.task
762 << ": " << ex.DynamicType()->Name();
763 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
764 str << ": " << ex.GetMessageString();
767 catch (netgen::NgException& exc)
769 SMESH_Comment str("NgException");
770 if ( strlen( netgen::multithread.task ) > 0 )
771 str << " at " << netgen::multithread.task;
772 str << ": " << exc.What();
777 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
778 if ( strlen( netgen::multithread.task ) > 0 )
779 str << " at " << netgen::multithread.task;
783 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
784 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
786 // -------------------------------------------------------------------
787 // Feed back the SMESHDS with the generated Nodes and Volume Elements
788 // -------------------------------------------------------------------
792 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
793 if ( ce && ce->HasBadElems() )
797 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
800 double Netgen_point[3];
801 int Netgen_tetrahedron[4];
803 // create and insert new nodes into nodeVec
804 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
805 int nodeIndex = Netgen_NbOfNodes + 1;
806 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
808 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
809 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
812 // create tetrahedrons
813 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
815 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
818 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
819 nodeVec.at( Netgen_tetrahedron[1] ),
820 nodeVec.at( Netgen_tetrahedron[2] ),
821 nodeVec.at( Netgen_tetrahedron[3] ));
832 //================================================================================
834 * \brief Compute tetrahedral mesh from 2D mesh without geometry
836 //================================================================================
838 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
839 SMESH_MesherHelper* aHelper)
841 const int invalid_ID = -1;
843 netgen::multithread.terminate = 0;
844 _progressByTic = -1.;
846 SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
847 if ( MeshType == SMESH_MesherHelper::COMP )
848 return error( COMPERR_BAD_INPUT_MESH,
849 SMESH_Comment("Mesh with linear and quadratic elements given"));
851 aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
853 // ---------------------------------
854 // Feed the Netgen with surface mesh
855 // ---------------------------------
857 int Netgen_NbOfNodes = 0;
858 double Netgen_point[3];
859 int Netgen_triangle[3];
861 NETGENPlugin_NetgenLibWrapper ngLib;
862 Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
864 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
865 if ( aMesh.NbQuadrangles() > 0 )
867 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
868 Adaptor->Compute(aMesh);
869 proxyMesh.reset( Adaptor );
871 if ( aHelper->IsQuadraticMesh() )
873 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
875 aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
879 // maps nodes to ng ID
880 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
881 typedef TNodeToIDMap::value_type TN2ID;
882 TNodeToIDMap nodeToNetgenID;
884 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
888 const SMDS_MeshElement* elem = fIt->next();
890 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
891 if ( elem->NbCornerNodes() != 3 )
892 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
894 // add three nodes of triangle
895 for ( int iN = 0; iN < 3; ++iN )
897 const SMDS_MeshNode* node = elem->GetNode( iN );
898 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
899 if ( ngID == invalid_ID )
901 ngID = ++Netgen_NbOfNodes;
902 Netgen_point [ 0 ] = node->X();
903 Netgen_point [ 1 ] = node->Y();
904 Netgen_point [ 2 ] = node->Z();
905 Ng_AddPoint(Netgen_mesh, Netgen_point);
907 Netgen_triangle[ iN ] = ngID;
909 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
911 proxyMesh.reset(); // delete tmp faces
913 // vector of nodes in which node index == netgen ID
914 vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
915 // insert old nodes into nodeVec
916 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
917 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
918 nodeVec.at( n_id->second ) = n_id->first;
919 nodeToNetgenID.clear();
921 // -------------------------
922 // Generate the volume mesh
923 // -------------------------
925 return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
928 void NETGENPlugin_NETGEN_3D::CancelCompute()
930 SMESH_Algo::CancelCompute();
931 netgen::multithread.terminate = 1;
934 //================================================================================
936 * \brief Return Compute progress
938 //================================================================================
940 double NETGENPlugin_NETGEN_3D::GetProgress() const
943 const char* volMeshing = "Volume meshing";
944 const char* dlnMeshing = "Delaunay meshing";
945 const double meshingRatio = 0.15;
946 const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
948 if ( _progressByTic < 0. &&
949 ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
950 strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
952 res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
953 //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
955 else // different otimizations
957 if ( _progressByTic < 0. )
958 ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
959 res = _progressByTic * _progressTic;
960 //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
962 return Min ( res, 0.98 );
965 //=============================================================================
969 //=============================================================================
971 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
972 const TopoDS_Shape& aShape,
973 MapShapeNbElems& aResMap)
975 smIdType nbtri = 0, nbqua = 0;
976 double fullArea = 0.0;
977 for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
978 TopoDS_Face F = TopoDS::Face( expF.Current() );
979 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
980 MapShapeNbElemsItr anIt = aResMap.find(sm);
981 if( anIt==aResMap.end() ) {
982 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
983 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
986 std::vector<smIdType> aVec = (*anIt).second;
987 nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
988 nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
990 BRepGProp::SurfaceProperties(F,G);
991 double anArea = G.Mass();
995 // collect info from edges
996 smIdType nb0d_e = 0, nb1d_e = 0;
997 bool IsQuadratic = false;
999 TopTools_MapOfShape tmpMap;
1000 for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
1001 TopoDS_Edge E = TopoDS::Edge(expF.Current());
1002 if( tmpMap.Contains(E) )
1005 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
1006 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
1007 if( anIt==aResMap.end() ) {
1008 SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
1009 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
1010 "Submesh can not be evaluated",this));
1013 std::vector<smIdType> aVec = (*anIt).second;
1014 nb0d_e += aVec[SMDSEntity_Node];
1015 nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1017 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1023 double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
1024 double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
1025 double ELen = Min(ELen_vol,ELen_face*2);
1028 BRepGProp::VolumeProperties(aShape,G);
1029 double aVolume = G.Mass();
1030 double tetrVol = 0.1179*ELen*ELen*ELen;
1031 double CoeffQuality = 0.9;
1032 smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
1033 smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
1034 smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
1035 std::vector<smIdType> aVec(SMDSEntity_Last);
1036 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1038 aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
1039 aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
1040 aVec[SMDSEntity_Quad_Pyramid] = nbqua;
1043 aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
1044 aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
1045 aVec[SMDSEntity_Pyramid] = nbqua;
1047 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1048 aResMap.insert(std::make_pair(sm,aVec));