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 "NETGENPlugin_DriverParam.hxx"
37 #include <SMDS_MeshElement.hxx>
38 #include <SMDS_MeshNode.hxx>
39 #include <SMESHDS_Mesh.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ControlsDef.hxx>
42 #include <SMESH_Gen.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_MeshEditor.hxx>
45 #include <SMESH_MesherHelper.hxx>
46 #include <SMESH_subMesh.hxx>
47 #include <StdMeshers_MaxElementVolume.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers.hxx>
50 #include <SMESH_subMesh.hxx>
51 #include <SMESH_DriverStep.hxx>
52 #include <SMESH_DriverMesh.hxx>
55 #include <BRepGProp.hxx>
56 #include <BRep_Tool.hxx>
57 #include <GProp_GProps.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx>
66 #include <utilities.h>
73 #include <boost/filesystem.hpp>
74 namespace fs = boost::filesystem;
83 #include <occgeom.hpp>
86 #include <ngexception.hpp>
89 #include <core/exception.hpp>
97 NETGENPLUGIN_DLL_HEADER
98 extern MeshingParameters mparam;
100 NETGENPLUGIN_DLL_HEADER
101 extern volatile multithreadt multithread;
103 using namespace nglib;
106 //=============================================================================
110 //=============================================================================
112 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
113 : SMESH_3D_Algo(hypId, gen)
116 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
117 _compatibleHypothesis.push_back("MaxElementVolume");
118 _compatibleHypothesis.push_back("NETGEN_Parameters");
119 _compatibleHypothesis.push_back("ViscousLayers");
121 _maxElementVolume = 0.;
123 _hypMaxElementVolume = NULL;
124 _hypParameters = NULL;
125 _viscousLayersHyp = NULL;
127 _requireShape = false; // can work without shape
130 //=============================================================================
134 //=============================================================================
136 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
140 //=============================================================================
144 //=============================================================================
146 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh& aMesh,
147 const TopoDS_Shape& aShape,
148 Hypothesis_Status& aStatus)
150 _hypMaxElementVolume = NULL;
151 _hypParameters = NULL;
152 _viscousLayersHyp = NULL;
153 _maxElementVolume = DBL_MAX;
155 // for correct work of GetProgress():
156 //netgen::multithread.percent = 0.;
157 //netgen::multithread.task = "Volume meshing";
158 _progressByTic = -1.;
160 list<const SMESHDS_Hypothesis*>::const_iterator itl;
161 //const SMESHDS_Hypothesis* theHyp;
163 const list<const SMESHDS_Hypothesis*>& hyps =
164 GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
165 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
166 if ( h == hyps.end())
168 aStatus = SMESH_Hypothesis::HYP_OK;
169 return true; // can work with no hypothesis
173 for ( ; h != hyps.end(); ++h )
175 if ( !_hypMaxElementVolume )
176 _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
177 if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
178 _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
179 if ( ! _hypParameters )
180 _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
182 if ( *h != _hypMaxElementVolume &&
183 *h != _viscousLayersHyp &&
184 *h != _hypParameters &&
185 !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
186 aStatus = HYP_INCOMPATIBLE;
188 if ( _hypMaxElementVolume && _hypParameters )
189 aStatus = HYP_INCOMPATIBLE;
190 else if ( aStatus == HYP_OK && _viscousLayersHyp )
191 error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
193 if ( _hypMaxElementVolume )
194 _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
196 return aStatus == HYP_OK;
200 void NETGENPlugin_NETGEN_3D::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
202 aParams.maxh = hyp->GetMaxSize();
203 aParams.minh = hyp->GetMinSize();
204 aParams.segmentsperedge = hyp->GetNbSegPerEdge();
205 aParams.grading = hyp->GetGrowthRate();
206 aParams.curvaturesafety = hyp->GetNbSegPerRadius();
207 aParams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
208 aParams.quad = hyp->GetQuadAllowed() ? 1 : 0;
209 aParams.optimize = hyp->GetOptimize();
210 aParams.fineness = hyp->GetFineness();
211 aParams.uselocalh = hyp->GetSurfaceCurvature();
212 aParams.merge_solids = hyp->GetFuseEdges();
213 aParams.chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
214 aParams.optsteps2d = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
215 aParams.optsteps3d = aParams.optimize ? hyp->GetNbVolOptSteps() : 0;
216 aParams.elsizeweight = hyp->GetElemSizeWeight();
217 aParams.opterrpow = hyp->GetWorstElemMeasure();
218 aParams.delaunay = hyp->GetUseDelauney();
219 aParams.checkoverlap = hyp->GetCheckOverlapping();
220 aParams.checkchartboundary = hyp->GetCheckChartBoundary();
223 aParams.meshsizefilename = hyp->GetMeshSizeFile();
226 aParams.meshsizefilename = hyp->GetMeshSizeFile();
229 aParams.closeedgefac = 2;
231 aParams.closeedgefac = 0;
235 // write in a binary file the orientation for each 2D element of the mesh
236 void NETGENPlugin_NETGEN_3D::exportElementOrientation(SMESH_Mesh& aMesh,
237 const TopoDS_Shape& aShape,
238 netgen_params& aParams,
239 const std::string output_file)
241 SMESH_MesherHelper helper(aMesh);
242 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
243 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
244 std::map<vtkIdType, bool> elemOrientation;
246 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
248 const TopoDS_Shape& aShapeFace = exFa.Current();
249 int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
250 bool isInternalFace = internals.isInternalShape( faceID );
252 if ( !isInternalFace &&
253 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
254 // IsReversedSubMesh() can work wrong on strongly curved faces,
255 // so we use it as less as possible
256 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
258 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
259 if ( !aSubMeshDSFace ) continue;
261 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
262 if ( aParams._quadraticMesh &&
263 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
265 // add medium nodes of proxy triangles to helper (#16843)
266 while ( iteratorElem->more() )
267 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
269 iteratorElem = aSubMeshDSFace->GetElements();
271 while ( iteratorElem->more() ) // loop on elements on a geom face
274 const SMDS_MeshElement* elem = iteratorElem->next();
276 error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
277 if ( elem->NbCornerNodes() != 3 )
278 error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
279 elemOrientation[elem->GetID()] = isRev;
280 } // loop on elements on a face
281 } // loop on faces of a SOLID or SHELL
284 std::ofstream df(output_file, ios::out|ios::binary);
285 int size=elemOrientation.size();
287 df.write((char*)&size, sizeof(int));
288 for(auto const& [id, orient]:elemOrientation){
289 df.write((char*)&id, sizeof(vtkIdType));
290 df.write((char*)&orient, sizeof(bool));
295 int NETGENPlugin_NETGEN_3D::RemoteCompute(SMESH_Mesh& aMesh,
296 const TopoDS_Shape& aShape)
299 auto time0 = std::chrono::high_resolution_clock::now();
300 SMESH_Hypothesis::Hypothesis_Status hypStatus;
301 CheckHypothesis(aMesh, aShape, hypStatus);
302 auto time1 = std::chrono::high_resolution_clock::now();
303 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
304 std::cout << "Time for check_hypo: " << elapsed.count() * 1e-9 << std::endl;
307 // Temporary folder for run
308 fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
309 fs::create_directories(tmp_folder);
310 // Using MESH2D generated after all triangles where created.
311 fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh2D.med");
312 fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
313 fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
314 fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
315 // TODO: Remove that file we do not use it
316 fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
317 fs::path shape_file=tmp_folder / fs::path("shape.step");
318 fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
319 fs::path log_file=tmp_folder / fs::path("run.log");
320 //TODO: Handle variable mesh_name
321 std::string mesh_name = "Maillage_1";
324 exportShape(shape_file.string(), aShape);
325 auto time2 = std::chrono::high_resolution_clock::now();
326 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
327 std::cout << "Time for exportShape: " << elapsed.count() * 1e-9 << std::endl;
330 netgen_params aParams;
331 fillParameters(_hypParameters, aParams);
333 exportNetgenParams(param_file.string(), aParams);
334 auto time3 = std::chrono::high_resolution_clock::now();
335 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time3-time2);
336 std::cout << "Time for fill+export param: " << elapsed.count() * 1e-9 << std::endl;
338 // Exporting element orientation
339 exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
340 auto time4 = std::chrono::high_resolution_clock::now();
341 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time4-time3);
342 std::cout << "Time for exportElemOrient: " << elapsed.count() * 1e-9 << std::endl;
345 // Calling run_mesher
346 // TODO: check if we need to handle the .exe for windows
348 fs::path run_mesher_exe =
349 fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
352 fs::path("NETGENPlugin_Runner");
353 cmd = run_mesher_exe.string() +
354 " NETGEN3D " + mesh_file.string() + " "
355 + shape_file.string() + " "
356 + param_file.string() + " "
357 + element_orientation_file.string() + " "
358 + std::to_string(aMesh.GetMesherNbThreads()) + " "
359 + new_element_file.string() + " "
361 " >> " + log_file.string();
363 //std::cout << "Running command: " << std::endl;
364 //std::cout << cmd << std::endl;
366 // Writing command in log
368 std::ofstream flog(log_file.string());
371 // TODO: Replace system by something else to handle redirection for windows
372 int ret = system(cmd.c_str());
373 auto time5 = std::chrono::high_resolution_clock::now();
374 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time5-time4);
375 std::cout << "Time for exec of run_mesher: " << elapsed.count() * 1e-9 << std::endl;
377 // TODO: better error handling (display log ?)
380 std::cerr << "Issue with command: " << std::endl;
381 std::cerr << cmd << std::endl;
387 std::ifstream df(new_element_file.string(), ios::binary);
389 int Netgen_NbOfNodes;
390 int Netgen_NbOfNodesNew;
391 int Netgen_NbOfTetra;
392 double Netgen_point[3];
393 int Netgen_tetrahedron[4];
396 SMESH_MesherHelper helper(aMesh);
398 int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
399 helper.SetElementsOnShape( true );
401 // Number of nodes in intial mesh
402 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
403 // Number of nodes added by netgen
404 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
406 // Filling nodevec (correspondence netgen numbering mesh numbering)
407 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
408 //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
409 SMESHDS_Mesh * meshDS = helper.GetMeshDS();
410 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
413 df.read((char*) &nodeID, sizeof(int));
414 nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
417 // Add new points and update nodeVec
418 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
420 df.read((char *) &Netgen_point, sizeof(double)*3);
422 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
428 df.read((char*) &Netgen_NbOfTetra, sizeof(int));
430 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
432 df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
434 nodeVec.at( Netgen_tetrahedron[0] ),
435 nodeVec.at( Netgen_tetrahedron[1] ),
436 nodeVec.at( Netgen_tetrahedron[2] ),
437 nodeVec.at( Netgen_tetrahedron[3] ));
440 auto time7 = std::chrono::high_resolution_clock::now();
441 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time7-time5);
442 std::cout << "Time for exec of add_in_mesh: " << elapsed.count() * 1e-9 << std::endl;
449 //=============================================================================
451 *Here we are going to use the NETGEN mesher
453 //=============================================================================
455 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
456 const TopoDS_Shape& aShape)
458 if(aMesh.IsParallel())
459 return RemoteCompute(aMesh, aShape);
460 auto time0 = std::chrono::high_resolution_clock::now();
462 netgen::multithread.terminate = 0;
463 netgen::multithread.task = "Volume meshing";
464 _progressByTic = -1.;
466 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
468 SMESH_MesherHelper helper(aMesh);
469 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
470 helper.SetElementsOnShape( true );
472 int Netgen_NbOfNodes = 0;
473 double Netgen_point[3];
474 int Netgen_triangle[3];
476 NETGENPlugin_NetgenLibWrapper ngLib;
477 Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
479 // vector of nodes in which node index == netgen ID
480 vector< const SMDS_MeshNode* > nodeVec;
482 const int invalid_ID = -1;
484 SMESH::Controls::Area areaControl;
485 SMESH::Controls::TSequenceOfXYZ nodesCoords;
487 // maps nodes to ng ID
488 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
489 typedef TNodeToIDMap::value_type TN2ID;
490 TNodeToIDMap nodeToNetgenID;
492 // find internal shapes
493 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
495 // ---------------------------------
496 // Feed the Netgen with surface mesh
497 // ---------------------------------
499 TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
500 bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
502 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
503 if ( _viscousLayersHyp )
505 netgen::multithread.percent = 3;
506 proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
510 if ( aMesh.NbQuadrangles() > 0 )
512 netgen::multithread.percent = 6;
513 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
514 Adaptor->Compute(aMesh,aShape,proxyMesh.get());
515 proxyMesh.reset( Adaptor );
518 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
520 const TopoDS_Shape& aShapeFace = exFa.Current();
521 int faceID = meshDS->ShapeToIndex( aShapeFace );
522 bool isInternalFace = internals.isInternalShape( faceID );
524 if ( checkReverse && !isInternalFace &&
525 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
526 // IsReversedSubMesh() can work wrong on strongly curved faces,
527 // so we use it as less as possible
528 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
530 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
531 if ( !aSubMeshDSFace ) continue;
533 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
534 if ( _quadraticMesh &&
535 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
537 // add medium nodes of proxy triangles to helper (#16843)
538 while ( iteratorElem->more() )
539 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
541 iteratorElem = aSubMeshDSFace->GetElements();
543 while ( iteratorElem->more() ) // loop on elements on a geom face
546 const SMDS_MeshElement* elem = iteratorElem->next();
548 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
549 if ( elem->NbCornerNodes() != 3 )
550 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
552 // Add nodes of triangles and triangles them-selves to netgen mesh
554 // add three nodes of triangle
555 bool hasDegen = false;
556 for ( int iN = 0; iN < 3; ++iN )
558 const SMDS_MeshNode* node = elem->GetNode( iN );
559 const int shapeID = node->getshapeId();
560 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
561 helper.IsDegenShape( shapeID ))
563 // ignore all nodes on degeneraged edge and use node on its vertex instead
564 TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
565 node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
568 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
569 if ( ngID == invalid_ID )
571 ngID = ++Netgen_NbOfNodes;
572 Netgen_point [ 0 ] = node->X();
573 Netgen_point [ 1 ] = node->Y();
574 Netgen_point [ 2 ] = node->Z();
575 Ng_AddPoint(Netgen_mesh, Netgen_point);
577 Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
580 if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
581 Netgen_triangle[0] == Netgen_triangle[2] ||
582 Netgen_triangle[2] == Netgen_triangle[1] ))
585 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
587 if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
589 swap( Netgen_triangle[1], Netgen_triangle[2] );
590 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
592 } // loop on elements on a face
593 } // loop on faces of a SOLID or SHELL
595 // insert old nodes into nodeVec
596 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
597 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
598 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
599 nodeVec[ n_id->second ] = n_id->first;
600 nodeToNetgenID.clear();
602 if ( internals.hasInternalVertexInSolid() )
604 netgen::OCCGeometry occgeo;
605 NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
606 (netgen::Mesh&) *Netgen_mesh,
612 // -------------------------
613 // Generate the volume mesh
614 // -------------------------
615 auto time1 = std::chrono::high_resolution_clock::now();
616 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
617 std::cout << "Time for seq:fill_in_ngmesh: " << elapsed.count() * 1e-9 << std::endl;
619 return (ngLib._isComputeOk = compute( aMesh, helper, nodeVec, ngLib ));
624 // void limitVolumeSize( netgen::Mesh* ngMesh,
627 // // get average h of faces
630 // for (int i = 1; i <= ngMesh->GetNSE(); i++)
632 // const netgen::Element2d& face = ngMesh->SurfaceElement(i);
633 // for (int j=1; j <= face.GetNP(); ++j)
635 // const netgen::PointIndex & i1 = face.PNumMod(j);
636 // const netgen::PointIndex & i2 = face.PNumMod(j+1);
639 // const netgen::Point3d & p1 = ngMesh->Point( i1 );
640 // const netgen::Point3d & p2 = ngMesh->Point( i2 );
641 // faceh += netgen::Dist2( p1, p2 );
646 // faceh = Sqrt( faceh / nbh );
649 // if ( faceh < 0.5 * maxh ) compareh = -1;
650 // else if ( faceh > 1.5 * maxh ) compareh = 1;
651 // else compareh = 0;
652 // // cerr << "faceh " << faceh << endl;
653 // // cerr << "init maxh " << maxh << endl;
654 // // cerr << "compareh " << compareh << endl;
656 // if ( compareh > 0 )
660 // // cerr << "maxh " << maxh << endl;
663 // netgen::Point3d pmin, pmax;
664 // ngMesh->GetBox( pmin, pmax, 0 );
665 // const double dx = pmax.X() - pmin.X();
666 // const double dy = pmax.Y() - pmin.Y();
667 // const double dz = pmax.Z() - pmin.Z();
669 // if ( ! & ngMesh->LocalHFunction() )
670 // ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
672 // // adjusted by SALOME_TESTS/Grids/smesh/bugs_08/I8
673 // const int nbX = Max( 2, int( dx / maxh * 2 ));
674 // const int nbY = Max( 2, int( dy / maxh * 2 ));
675 // const int nbZ = Max( 2, int( dz / maxh * 2 ));
677 // netgen::Point3d p;
678 // for ( int i = 0; i <= nbX; ++i )
680 // p.X() = pmin.X() + i * dx / nbX;
681 // for ( int j = 0; j <= nbY; ++j )
683 // p.Y() = pmin.Y() + j * dy / nbY;
684 // for ( int k = 0; k <= nbZ; ++k )
686 // p.Z() = pmin.Z() + k * dz / nbZ;
687 // ngMesh->RestrictLocalH( p, maxh );
694 //================================================================================
696 * \brief set parameters and generate the volume mesh
698 //================================================================================
700 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh& aMesh,
701 SMESH_MesherHelper& helper,
702 vector< const SMDS_MeshNode* >& nodeVec,
703 NETGENPlugin_NetgenLibWrapper& ngLib)
705 auto time0 = std::chrono::high_resolution_clock::now();
707 netgen::multithread.terminate = 0;
709 netgen::Mesh* ngMesh = ngLib._ngMesh;
710 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
711 int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
713 int startWith = netgen::MESHCONST_MESHVOLUME;
714 int endWith = netgen::MESHCONST_OPTVOLUME;
717 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
718 netgen::OCCGeometry occgeo;
720 if ( _hypParameters )
722 aMesher.SetParameters( _hypParameters );
724 if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
725 !_hypParameters->GetMeshSizeFile().empty() )
727 if ( ! &ngMesh->LocalHFunction() )
729 netgen::Point3d pmin, pmax;
730 ngMesh->GetBox( pmin, pmax, 0 );
731 ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
733 aMesher.SetLocalSize( occgeo, *ngMesh );
736 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
737 } catch (netgen::NgException & ex) {
738 return error( COMPERR_BAD_PARMETERS, ex.What() );
741 if ( !_hypParameters->GetOptimize() )
742 endWith = netgen::MESHCONST_MESHVOLUME;
744 else if ( _hypMaxElementVolume )
746 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
747 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
749 else if ( aMesh.HasShapeToMesh() )
751 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
752 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
756 netgen::Point3d pmin, pmax;
757 ngMesh->GetBox (pmin, pmax);
758 netgen::mparam.maxh = Dist(pmin, pmax)/2;
761 if ( !_hypParameters && aMesh.HasShapeToMesh() )
763 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
769 auto time0 = std::chrono::high_resolution_clock::now();
771 ngLib.CalcLocalH(ngMesh);
772 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
774 if(netgen::multithread.terminate)
777 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
779 catch (Standard_Failure& ex)
781 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
782 str << " at " << netgen::multithread.task
783 << ": " << ex.DynamicType()->Name();
784 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
785 str << ": " << ex.GetMessageString();
788 catch (netgen::NgException& exc)
790 SMESH_Comment str("NgException");
791 if ( strlen( netgen::multithread.task ) > 0 )
792 str << " at " << netgen::multithread.task;
793 str << ": " << exc.What();
798 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
799 if ( strlen( netgen::multithread.task ) > 0 )
800 str << " at " << netgen::multithread.task;
803 auto time1 = std::chrono::high_resolution_clock::now();
804 auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
805 std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
807 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
808 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
810 // -------------------------------------------------------------------
811 // Feed back the SMESHDS with the generated Nodes and Volume Elements
812 // -------------------------------------------------------------------
816 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
817 if ( ce && ce->HasBadElems() )
821 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
824 double Netgen_point[3];
825 int Netgen_tetrahedron[4];
827 // create and insert new nodes into nodeVec
828 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
829 int nodeIndex = Netgen_NbOfNodes + 1;
830 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
832 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
833 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
836 // create tetrahedrons
837 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
839 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
842 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
843 nodeVec.at( Netgen_tetrahedron[1] ),
844 nodeVec.at( Netgen_tetrahedron[2] ),
845 nodeVec.at( Netgen_tetrahedron[3] ));
852 auto time2 = std::chrono::high_resolution_clock::now();
853 elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
854 std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
860 //================================================================================
862 * \brief Compute tetrahedral mesh from 2D mesh without geometry
864 //================================================================================
866 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
867 SMESH_MesherHelper* aHelper)
869 const int invalid_ID = -1;
871 netgen::multithread.terminate = 0;
872 _progressByTic = -1.;
874 SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
875 if ( MeshType == SMESH_MesherHelper::COMP )
876 return error( COMPERR_BAD_INPUT_MESH,
877 SMESH_Comment("Mesh with linear and quadratic elements given"));
879 aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
881 // ---------------------------------
882 // Feed the Netgen with surface mesh
883 // ---------------------------------
885 int Netgen_NbOfNodes = 0;
886 double Netgen_point[3];
887 int Netgen_triangle[3];
889 NETGENPlugin_NetgenLibWrapper ngLib;
890 Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
892 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
893 if ( aMesh.NbQuadrangles() > 0 )
895 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
896 Adaptor->Compute(aMesh);
897 proxyMesh.reset( Adaptor );
899 if ( aHelper->IsQuadraticMesh() )
901 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
903 aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
907 // maps nodes to ng ID
908 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
909 typedef TNodeToIDMap::value_type TN2ID;
910 TNodeToIDMap nodeToNetgenID;
912 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
916 const SMDS_MeshElement* elem = fIt->next();
918 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
919 if ( elem->NbCornerNodes() != 3 )
920 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
922 // add three nodes of triangle
923 for ( int iN = 0; iN < 3; ++iN )
925 const SMDS_MeshNode* node = elem->GetNode( iN );
926 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
927 if ( ngID == invalid_ID )
929 ngID = ++Netgen_NbOfNodes;
930 Netgen_point [ 0 ] = node->X();
931 Netgen_point [ 1 ] = node->Y();
932 Netgen_point [ 2 ] = node->Z();
933 Ng_AddPoint(Netgen_mesh, Netgen_point);
935 Netgen_triangle[ iN ] = ngID;
937 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
939 proxyMesh.reset(); // delete tmp faces
941 // vector of nodes in which node index == netgen ID
942 vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
943 // insert old nodes into nodeVec
944 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
945 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
946 nodeVec.at( n_id->second ) = n_id->first;
947 nodeToNetgenID.clear();
949 // -------------------------
950 // Generate the volume mesh
951 // -------------------------
953 return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
956 void NETGENPlugin_NETGEN_3D::CancelCompute()
958 SMESH_Algo::CancelCompute();
959 netgen::multithread.terminate = 1;
962 //================================================================================
964 * \brief Return Compute progress
966 //================================================================================
968 double NETGENPlugin_NETGEN_3D::GetProgress() const
971 const char* volMeshing = "Volume meshing";
972 const char* dlnMeshing = "Delaunay meshing";
973 const double meshingRatio = 0.15;
974 const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
976 if ( _progressByTic < 0. &&
977 ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
978 strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
980 res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
981 //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
983 else // different otimizations
985 if ( _progressByTic < 0. )
986 ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
987 res = _progressByTic * _progressTic;
988 //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
990 return Min ( res, 0.98 );
993 //=============================================================================
997 //=============================================================================
999 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
1000 const TopoDS_Shape& aShape,
1001 MapShapeNbElems& aResMap)
1003 smIdType nbtri = 0, nbqua = 0;
1004 double fullArea = 0.0;
1005 for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
1006 TopoDS_Face F = TopoDS::Face( expF.Current() );
1007 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1008 MapShapeNbElemsItr anIt = aResMap.find(sm);
1009 if( anIt==aResMap.end() ) {
1010 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1011 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
1014 std::vector<smIdType> aVec = (*anIt).second;
1015 nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1016 nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1018 BRepGProp::SurfaceProperties(F,G);
1019 double anArea = G.Mass();
1023 // collect info from edges
1024 smIdType nb0d_e = 0, nb1d_e = 0;
1025 bool IsQuadratic = false;
1026 bool IsFirst = true;
1027 TopTools_MapOfShape tmpMap;
1028 for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
1029 TopoDS_Edge E = TopoDS::Edge(expF.Current());
1030 if( tmpMap.Contains(E) )
1033 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
1034 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
1035 if( anIt==aResMap.end() ) {
1036 SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
1037 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
1038 "Submesh can not be evaluated",this));
1041 std::vector<smIdType> aVec = (*anIt).second;
1042 nb0d_e += aVec[SMDSEntity_Node];
1043 nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1045 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1051 double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
1052 double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
1053 double ELen = Min(ELen_vol,ELen_face*2);
1056 BRepGProp::VolumeProperties(aShape,G);
1057 double aVolume = G.Mass();
1058 double tetrVol = 0.1179*ELen*ELen*ELen;
1059 double CoeffQuality = 0.9;
1060 smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
1061 smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
1062 smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
1063 std::vector<smIdType> aVec(SMDSEntity_Last);
1064 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1066 aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
1067 aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
1068 aVec[SMDSEntity_Quad_Pyramid] = nbqua;
1071 aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
1072 aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
1073 aVec[SMDSEntity_Pyramid] = nbqua;
1075 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1076 aResMap.insert(std::make_pair(sm,aVec));