Salome HOME
Using RAII to remove file.close
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D.cxx
1 // Copyright (C) 2007-2022  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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.
10 //
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.
15 //
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
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
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)
28 // Project   : SALOME
29 //=============================================================================
30 //
31 #include "NETGENPlugin_NETGEN_3D.hxx"
32
33 #include "NETGENPlugin_Hypothesis.hxx"
34
35 #include "DriverStep.hxx"
36 #include "DriverMesh.hxx"
37 #include "netgen_param.hxx"
38
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>
53
54 #include <BRepGProp.hxx>
55 #include <BRep_Tool.hxx>
56 #include <GProp_GProps.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopoDS.hxx>
61
62 #include <Standard_Failure.hxx>
63 #include <Standard_ErrorHandler.hxx>
64
65 #include <utilities.h>
66
67 #include <list>
68 #include <vector>
69 #include <map>
70
71 #include <cstdlib>
72 #include <boost/filesystem.hpp>
73 namespace fs = boost::filesystem;
74
75 /*
76   Netgen include files
77 */
78
79 #ifndef OCCGEOMETRY
80 #define OCCGEOMETRY
81 #endif
82 #include <occgeom.hpp>
83
84 #ifdef NETGEN_V5
85 #include <ngexception.hpp>
86 #endif
87 #ifdef NETGEN_V6
88 #include <core/exception.hpp>
89 #endif
90
91 namespace nglib {
92 #include <nglib.h>
93 }
94 namespace netgen {
95
96   NETGENPLUGIN_DLL_HEADER
97   extern MeshingParameters mparam;
98
99   NETGENPLUGIN_DLL_HEADER
100   extern volatile multithreadt multithread;
101 }
102 using namespace nglib;
103 using namespace std;
104
105 //=============================================================================
106 /*!
107  *
108  */
109 //=============================================================================
110
111 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
112   : SMESH_3D_Algo(hypId, gen)
113 {
114   _name = "NETGEN_3D";
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");
119
120   _maxElementVolume = 0.;
121
122   _hypMaxElementVolume = NULL;
123   _hypParameters = NULL;
124   _viscousLayersHyp = NULL;
125
126   _requireShape = false; // can work without shape
127 }
128
129 //=============================================================================
130 /*!
131  *
132  */
133 //=============================================================================
134
135 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
136 {
137 }
138
139 //=============================================================================
140 /*!
141  *
142  */
143 //=============================================================================
144
145 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
146                                               const TopoDS_Shape& aShape,
147                                               Hypothesis_Status&  aStatus)
148 {
149   _hypMaxElementVolume = NULL;
150   _hypParameters = NULL;
151   _viscousLayersHyp = NULL;
152   _maxElementVolume = DBL_MAX;
153
154   // for correct work of GetProgress():
155   //netgen::multithread.percent = 0.;
156   //netgen::multithread.task = "Volume meshing";
157   _progressByTic = -1.;
158
159   list<const SMESHDS_Hypothesis*>::const_iterator itl;
160   //const SMESHDS_Hypothesis* theHyp;
161
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())
166   {
167     aStatus = SMESH_Hypothesis::HYP_OK;
168     return true;  // can work with no hypothesis
169   }
170
171   aStatus = HYP_OK;
172   for ( ; h != hyps.end(); ++h )
173   {
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 );
180
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;
186   }
187   if ( _hypMaxElementVolume && _hypParameters )
188     aStatus = HYP_INCOMPATIBLE;
189   else if ( aStatus == HYP_OK && _viscousLayersHyp )
190     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
191
192   if ( _hypMaxElementVolume )
193     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
194
195   return aStatus == HYP_OK;
196 }
197
198
199 void NETGENPlugin_NETGEN_3D::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
200 {
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();
220 #ifdef NETGEN_V6
221   // std::string
222   aParams.meshsizefilename = hyp->GetMeshSizeFile();
223 #else
224   // const char*
225   aParams.meshsizefilename = hyp->GetMeshSizeFile();
226 #endif
227 #ifdef NETGEN_V6
228   aParams.closeedgefac = 2;
229 #else
230   aParams.closeedgefac = 0;
231 #endif
232 }
233
234 // write 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)
239 {
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;
244
245   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
246   {
247     const TopoDS_Shape& aShapeFace = exFa.Current();
248     int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
249     bool isInternalFace = internals.isInternalShape( faceID );
250     bool isRev = false;
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 ));
256
257     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
258     if ( !aSubMeshDSFace ) continue;
259
260     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
261     if ( aParams._quadraticMesh &&
262           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
263     {
264       // add medium nodes of proxy triangles to helper (#16843)
265       while ( iteratorElem->more() )
266         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
267
268       iteratorElem = aSubMeshDSFace->GetElements();
269     }
270     while ( iteratorElem->more() ) // loop on elements on a geom face
271     {
272       // check mesh face
273       const SMDS_MeshElement* elem = iteratorElem->next();
274       if ( !elem )
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
281
282   {
283     std::ofstream df(output_file, ios::out|ios::binary);
284     int size=elemOrientation.size();
285
286     df.write((char*)&size, sizeof(int));
287     for(auto const& [id, orient]:elemOrientation){
288       df.write((char*)&id, sizeof(vtkIdType));
289       df.write((char*)&orient, sizeof(bool));
290     }
291   }
292 }
293
294 int NETGENPlugin_NETGEN_3D::RemoteCompute(SMESH_Mesh&         aMesh,
295                                           const TopoDS_Shape& aShape)
296 {
297   aMesh.Lock();
298   auto time0 = std::chrono::high_resolution_clock::now();
299   SMESH_Hypothesis::Hypothesis_Status hypStatus;
300   CheckHypothesis(aMesh, aShape, hypStatus);
301   auto time1 = std::chrono::high_resolution_clock::now();
302   auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
303   std::cout << "Time for check_hypo: " << elapsed.count() * 1e-9 << std::endl;
304
305
306   // Temporary folder for run
307   fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
308   fs::create_directories(tmp_folder);
309   // Using MESH2D generated after all triangles where created.
310   fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh2D.med");
311   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
312   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
313   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
314   // TODO: Remove that file we do not use it
315   fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
316   fs::path shape_file=tmp_folder / fs::path("shape.step");
317   fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
318   fs::path log_file=tmp_folder / fs::path("run_mesher.log");
319   //TODO: Handle variable mesh_name
320   std::string mesh_name = "Maillage_1";
321
322   //Writing Shape
323   export_shape(shape_file.string(), aShape);
324   auto time2 = std::chrono::high_resolution_clock::now();
325   elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
326   std::cout << "Time for export_shape: " << elapsed.count() * 1e-9 << std::endl;
327
328   //Writing hypo
329   netgen_params aParams;
330   FillParameters(_hypParameters, aParams);
331
332   export_netgen_params(param_file.string(), aParams);
333   auto time3 = std::chrono::high_resolution_clock::now();
334   elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time3-time2);
335   std::cout << "Time for fill+export param: " << elapsed.count() * 1e-9 << std::endl;
336
337   // Exporting element orientation
338   exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
339   auto time4 = std::chrono::high_resolution_clock::now();
340   elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time4-time3);
341   std::cout << "Time for exportElemnOrient: " << elapsed.count() * 1e-9 << std::endl;
342
343   aMesh.Unlock();
344   // Calling run_mesher
345   // TODO: check if we need to handle the .exe for windows
346   std::string cmd;
347   fs::path run_mesher_exe =
348     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
349     fs::path("bin")/
350     fs::path("salome")/
351     fs::path("run_mesher");
352   cmd = run_mesher_exe.string() +
353                   " NETGEN3D " + mesh_file.string() + " "
354                                + shape_file.string() + " "
355                                + param_file.string() + " "
356                                + element_orientation_file.string() + " "
357                                + std::to_string(aMesh.GetMesherNbThreads()) + " "
358                                + new_element_file.string() + " "
359                                + std::to_string(0) + " "
360                                + output_mesh_file.string() +
361                                " >> " + log_file.string();
362
363   //std::cout << "Running command: " << std::endl;
364   //std::cout << cmd << std::endl;
365
366   // Writing command in log
367   {
368     std::ofstream flog(log_file.string());
369     flog << cmd << endl;
370   }
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;
376
377   // TODO: better error handling (display log ?)
378   if(ret != 0){
379     // Run crahed
380     std::cerr << "Issue with command: " << std::endl;
381     std::cerr << cmd << std::endl;
382     return false;
383   }
384
385   aMesh.Lock();
386   {
387     std::ifstream df(new_element_file.string(), ios::binary);
388
389     int Netgen_NbOfNodes;
390     int Netgen_NbOfNodesNew;
391     int Netgen_NbOfTetra;
392     double Netgen_point[3];
393     int    Netgen_tetrahedron[4];
394     int nodeID;
395
396     SMESH_MesherHelper helper(aMesh);
397     // This function
398     int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
399     helper.SetElementsOnShape( true );
400
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));
405
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 )
411     {
412       //Id of the point
413       df.read((char*) &nodeID, sizeof(int));
414       nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
415     }
416
417     // Add new points and update nodeVec
418     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
419     {
420       df.read((char *) &Netgen_point, sizeof(double)*3);
421
422       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
423                                  Netgen_point[1],
424                                  Netgen_point[2]);
425     }
426
427     // Add tetrahedrons
428     df.read((char*) &Netgen_NbOfTetra, sizeof(int));
429
430     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
431     {
432       df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
433       helper.AddVolume(
434                     nodeVec.at( Netgen_tetrahedron[0] ),
435                     nodeVec.at( Netgen_tetrahedron[1] ),
436                     nodeVec.at( Netgen_tetrahedron[2] ),
437                     nodeVec.at( Netgen_tetrahedron[3] ));
438     }
439   }
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;
443
444   fs::remove_all(tmp_folder);
445   aMesh.Unlock();
446
447   return true;
448 }
449
450 //=============================================================================
451 /*!
452  *Here we are going to use the NETGEN mesher
453  */
454 //=============================================================================
455
456 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
457                                      const TopoDS_Shape& aShape)
458 {
459   if(aMesh.IsParallel())
460     return RemoteCompute(aMesh, aShape);
461   auto time0 = std::chrono::high_resolution_clock::now();
462
463   netgen::multithread.terminate = 0;
464   netgen::multithread.task = "Volume meshing";
465   _progressByTic = -1.;
466
467   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
468
469   SMESH_MesherHelper helper(aMesh);
470   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
471   helper.SetElementsOnShape( true );
472
473   int Netgen_NbOfNodes = 0;
474   double Netgen_point[3];
475   int Netgen_triangle[3];
476
477   NETGENPlugin_NetgenLibWrapper ngLib;
478   Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
479
480   // vector of nodes in which node index == netgen ID
481   vector< const SMDS_MeshNode* > nodeVec;
482   {
483     const int invalid_ID = -1;
484
485     SMESH::Controls::Area areaControl;
486     SMESH::Controls::TSequenceOfXYZ nodesCoords;
487
488     // maps nodes to ng ID
489     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
490     typedef TNodeToIDMap::value_type                     TN2ID;
491     TNodeToIDMap nodeToNetgenID;
492
493     // find internal shapes
494     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
495
496     // ---------------------------------
497     // Feed the Netgen with surface mesh
498     // ---------------------------------
499
500     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
501     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
502
503     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
504     if ( _viscousLayersHyp )
505     {
506       netgen::multithread.percent = 3;
507       proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
508       if ( !proxyMesh )
509         return false;
510     }
511     if ( aMesh.NbQuadrangles() > 0 )
512     {
513       netgen::multithread.percent = 6;
514       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
515       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
516       proxyMesh.reset( Adaptor );
517     }
518
519     for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
520     {
521       const TopoDS_Shape& aShapeFace = exFa.Current();
522       int faceID = meshDS->ShapeToIndex( aShapeFace );
523       bool isInternalFace = internals.isInternalShape( faceID );
524       bool isRev = false;
525       if ( checkReverse && !isInternalFace &&
526            helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
527         // IsReversedSubMesh() can work wrong on strongly curved faces,
528         // so we use it as less as possible
529         isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
530
531       const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
532       if ( !aSubMeshDSFace ) continue;
533
534       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
535       if ( _quadraticMesh &&
536            dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
537       {
538         // add medium nodes of proxy triangles to helper (#16843)
539         while ( iteratorElem->more() )
540           helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
541
542         iteratorElem = aSubMeshDSFace->GetElements();
543       }
544       while ( iteratorElem->more() ) // loop on elements on a geom face
545       {
546         // check mesh face
547         const SMDS_MeshElement* elem = iteratorElem->next();
548         if ( !elem )
549           return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
550         if ( elem->NbCornerNodes() != 3 )
551           return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
552
553         // Add nodes of triangles and triangles them-selves to netgen mesh
554
555         // add three nodes of triangle
556         bool hasDegen = false;
557         for ( int iN = 0; iN < 3; ++iN )
558         {
559           const SMDS_MeshNode* node = elem->GetNode( iN );
560           const int shapeID = node->getshapeId();
561           if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
562                helper.IsDegenShape( shapeID ))
563           {
564             // ignore all nodes on degeneraged edge and use node on its vertex instead
565             TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
566             node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
567             hasDegen = true;
568           }
569           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
570           if ( ngID == invalid_ID )
571           {
572             ngID = ++Netgen_NbOfNodes;
573             Netgen_point [ 0 ] = node->X();
574             Netgen_point [ 1 ] = node->Y();
575             Netgen_point [ 2 ] = node->Z();
576             Ng_AddPoint(Netgen_mesh, Netgen_point);
577           }
578           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
579         }
580         // add triangle
581         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
582                           Netgen_triangle[0] == Netgen_triangle[2] ||
583                           Netgen_triangle[2] == Netgen_triangle[1] ))
584           continue;
585
586         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
587
588         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
589         {
590           swap( Netgen_triangle[1], Netgen_triangle[2] );
591           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
592         }
593       } // loop on elements on a face
594     } // loop on faces of a SOLID or SHELL
595
596     // insert old nodes into nodeVec
597     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
598     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
599     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
600       nodeVec[ n_id->second ] = n_id->first;
601     nodeToNetgenID.clear();
602
603     if ( internals.hasInternalVertexInSolid() )
604     {
605       netgen::OCCGeometry occgeo;
606       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
607                                                    (netgen::Mesh&) *Netgen_mesh,
608                                                    nodeVec,
609                                                    internals);
610     }
611   }
612
613   // -------------------------
614   // Generate the volume mesh
615   // -------------------------
616   auto time1 = std::chrono::high_resolution_clock::now();
617   auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
618   std::cout << "Time for seq:fill_in_ngmesh: " << elapsed.count() * 1e-9 << std::endl;
619
620   return (ngLib._isComputeOk = compute( aMesh, helper, nodeVec, ngLib ));
621 }
622
623 // namespace
624 // {
625 //   void limitVolumeSize( netgen::Mesh* ngMesh,
626 //                         double        maxh )
627 //   {
628 //     // get average h of faces
629 //     double faceh = 0;
630 //     int nbh = 0;
631 //     for (int i = 1; i <= ngMesh->GetNSE(); i++)
632 //     {
633 //       const netgen::Element2d& face = ngMesh->SurfaceElement(i);
634 //       for (int j=1; j <= face.GetNP(); ++j)
635 //       {
636 //         const netgen::PointIndex & i1 = face.PNumMod(j);
637 //         const netgen::PointIndex & i2 = face.PNumMod(j+1);
638 //         if ( i1 < i2 )
639 //         {
640 //           const netgen::Point3d & p1 = ngMesh->Point( i1 );
641 //           const netgen::Point3d & p2 = ngMesh->Point( i2 );
642 //           faceh += netgen::Dist2( p1, p2 );
643 //           nbh++;
644 //         }
645 //       }
646 //     }
647 //     faceh = Sqrt( faceh / nbh );
648
649 //     double compareh;
650 //     if      ( faceh < 0.5 * maxh ) compareh = -1;
651 //     else if ( faceh > 1.5 * maxh ) compareh = 1;
652 //     else                           compareh = 0;
653 //     // cerr << "faceh " << faceh << endl;
654 //     // cerr << "init maxh " << maxh << endl;
655 //     // cerr << "compareh " << compareh << endl;
656
657 //     if ( compareh > 0 )
658 //       maxh *= 1.2;
659 //     else
660 //       maxh *= 0.8;
661 //     // cerr << "maxh " << maxh << endl;
662
663 //     // get bnd box
664 //     netgen::Point3d pmin, pmax;
665 //     ngMesh->GetBox( pmin, pmax, 0 );
666 //     const double dx = pmax.X() - pmin.X();
667 //     const double dy = pmax.Y() - pmin.Y();
668 //     const double dz = pmax.Z() - pmin.Z();
669
670 //     if ( ! & ngMesh->LocalHFunction() )
671 //       ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
672
673 //     // adjusted by SALOME_TESTS/Grids/smesh/bugs_08/I8
674 //     const int nbX = Max( 2, int( dx / maxh * 2 ));
675 //     const int nbY = Max( 2, int( dy / maxh * 2 ));
676 //     const int nbZ = Max( 2, int( dz / maxh * 2 ));
677
678 //     netgen::Point3d p;
679 //     for ( int i = 0; i <= nbX; ++i )
680 //     {
681 //       p.X() = pmin.X() +  i * dx / nbX;
682 //       for ( int j = 0; j <= nbY; ++j )
683 //       {
684 //         p.Y() = pmin.Y() +  j * dy / nbY;
685 //         for ( int k = 0; k <= nbZ; ++k )
686 //         {
687 //           p.Z() = pmin.Z() +  k * dz / nbZ;
688 //           ngMesh->RestrictLocalH( p, maxh );
689 //         }
690 //       }
691 //     }
692 //   }
693 // }
694
695 //================================================================================
696 /*!
697  * \brief set parameters and generate the volume mesh
698  */
699 //================================================================================
700
701 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
702                                      SMESH_MesherHelper&             helper,
703                                      vector< const SMDS_MeshNode* >& nodeVec,
704                                      NETGENPlugin_NetgenLibWrapper&  ngLib)
705 {
706   auto time0 = std::chrono::high_resolution_clock::now();
707
708   netgen::multithread.terminate = 0;
709
710   netgen::Mesh* ngMesh = ngLib._ngMesh;
711   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
712   int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
713
714   int startWith = netgen::MESHCONST_MESHVOLUME;
715   int endWith   = netgen::MESHCONST_OPTVOLUME;
716   int err = 1;
717
718   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
719   netgen::OCCGeometry occgeo;
720
721   if ( _hypParameters )
722   {
723     aMesher.SetParameters( _hypParameters );
724
725     if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
726          !_hypParameters->GetMeshSizeFile().empty() )
727     {
728       if ( ! &ngMesh->LocalHFunction() )
729       {
730         netgen::Point3d pmin, pmax;
731         ngMesh->GetBox( pmin, pmax, 0 );
732         ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
733       }
734       aMesher.SetLocalSize( occgeo, *ngMesh );
735
736       try {
737         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
738       } catch (netgen::NgException & ex) {
739         return error( COMPERR_BAD_PARMETERS, ex.What() );
740       }
741     }
742     if ( !_hypParameters->GetOptimize() )
743       endWith = netgen::MESHCONST_MESHVOLUME;
744   }
745   else if ( _hypMaxElementVolume )
746   {
747     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
748     // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
749   }
750   else if ( aMesh.HasShapeToMesh() )
751   {
752     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
753     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
754   }
755   else
756   {
757     netgen::Point3d pmin, pmax;
758     ngMesh->GetBox (pmin, pmax);
759     netgen::mparam.maxh = Dist(pmin, pmax)/2;
760   }
761
762   if ( !_hypParameters && aMesh.HasShapeToMesh() )
763   {
764     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
765   }
766
767   try
768   {
769     OCC_CATCH_SIGNALS;
770     auto time0 = std::chrono::high_resolution_clock::now();
771
772     ngLib.CalcLocalH(ngMesh);
773     err = ngLib.GenerateMesh(occgeo, startWith, endWith);
774
775     if(netgen::multithread.terminate)
776       return false;
777     if ( err )
778       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
779   }
780   catch (Standard_Failure& ex)
781   {
782     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
783     str << " at " << netgen::multithread.task
784         << ": " << ex.DynamicType()->Name();
785     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
786       str << ": " << ex.GetMessageString();
787     error(str);
788   }
789   catch (netgen::NgException& exc)
790   {
791     SMESH_Comment str("NgException");
792     if ( strlen( netgen::multithread.task ) > 0 )
793       str << " at " << netgen::multithread.task;
794     str << ": " << exc.What();
795     error(str);
796   }
797   catch (...)
798   {
799     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
800     if ( strlen( netgen::multithread.task ) > 0 )
801       str << " at " << netgen::multithread.task;
802     error(str);
803   }
804   auto time1 = std::chrono::high_resolution_clock::now();
805   auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
806   std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
807
808   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
809   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
810
811   // -------------------------------------------------------------------
812   // Feed back the SMESHDS with the generated Nodes and Volume Elements
813   // -------------------------------------------------------------------
814
815   if ( err )
816   {
817     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
818     if ( ce && ce->HasBadElems() )
819       error( ce );
820   }
821
822   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
823   if ( isOK )
824   {
825     double Netgen_point[3];
826     int    Netgen_tetrahedron[4];
827
828     // create and insert new nodes into nodeVec
829     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
830     int nodeIndex = Netgen_NbOfNodes + 1;
831     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
832     {
833       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
834       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
835     }
836
837     // create tetrahedrons
838     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
839     {
840       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
841       try
842       {
843         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
844                           nodeVec.at( Netgen_tetrahedron[1] ),
845                           nodeVec.at( Netgen_tetrahedron[2] ),
846                           nodeVec.at( Netgen_tetrahedron[3] ));
847       }
848       catch (...)
849       {
850       }
851     }
852   }
853   auto time2 = std::chrono::high_resolution_clock::now();
854   elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
855   std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
856
857
858   return !err;
859 }
860
861 //================================================================================
862 /*!
863  * \brief Compute tetrahedral mesh from 2D mesh without geometry
864  */
865 //================================================================================
866
867 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
868                                      SMESH_MesherHelper* aHelper)
869 {
870   const int invalid_ID = -1;
871
872   netgen::multithread.terminate = 0;
873   _progressByTic = -1.;
874
875   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
876   if ( MeshType == SMESH_MesherHelper::COMP )
877     return error( COMPERR_BAD_INPUT_MESH,
878                   SMESH_Comment("Mesh with linear and quadratic elements given"));
879
880   aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
881
882   // ---------------------------------
883   // Feed the Netgen with surface mesh
884   // ---------------------------------
885
886   int Netgen_NbOfNodes = 0;
887   double Netgen_point[3];
888   int Netgen_triangle[3];
889
890   NETGENPlugin_NetgenLibWrapper ngLib;
891   Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
892
893   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
894   if ( aMesh.NbQuadrangles() > 0 )
895   {
896     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
897     Adaptor->Compute(aMesh);
898     proxyMesh.reset( Adaptor );
899
900     if ( aHelper->IsQuadraticMesh() )
901     {
902       SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
903       while( fIt->more())
904         aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
905     }
906   }
907
908   // maps nodes to ng ID
909   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
910   typedef TNodeToIDMap::value_type                     TN2ID;
911   TNodeToIDMap nodeToNetgenID;
912
913   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
914   while( fIt->more())
915   {
916     // check element
917     const SMDS_MeshElement* elem = fIt->next();
918     if ( !elem )
919       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
920     if ( elem->NbCornerNodes() != 3 )
921       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
922
923     // add three nodes of triangle
924     for ( int iN = 0; iN < 3; ++iN )
925     {
926       const SMDS_MeshNode* node = elem->GetNode( iN );
927       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
928       if ( ngID == invalid_ID )
929       {
930         ngID = ++Netgen_NbOfNodes;
931         Netgen_point [ 0 ] = node->X();
932         Netgen_point [ 1 ] = node->Y();
933         Netgen_point [ 2 ] = node->Z();
934         Ng_AddPoint(Netgen_mesh, Netgen_point);
935       }
936       Netgen_triangle[ iN ] = ngID;
937     }
938     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
939   }
940   proxyMesh.reset(); // delete tmp faces
941
942   // vector of nodes in which node index == netgen ID
943   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
944   // insert old nodes into nodeVec
945   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
946   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
947     nodeVec.at( n_id->second ) = n_id->first;
948   nodeToNetgenID.clear();
949
950   // -------------------------
951   // Generate the volume mesh
952   // -------------------------
953
954   return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
955 }
956
957 void NETGENPlugin_NETGEN_3D::CancelCompute()
958 {
959   SMESH_Algo::CancelCompute();
960   netgen::multithread.terminate = 1;
961 }
962
963 //================================================================================
964 /*!
965  * \brief Return Compute progress
966  */
967 //================================================================================
968
969 double NETGENPlugin_NETGEN_3D::GetProgress() const
970 {
971   double res;
972   const char* volMeshing = "Volume meshing";
973   const char* dlnMeshing = "Delaunay meshing";
974   const double meshingRatio = 0.15;
975   const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
976
977   if ( _progressByTic < 0. &&
978        ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
979          strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
980   {
981     res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
982     //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
983   }
984   else // different otimizations
985   {
986     if ( _progressByTic < 0. )
987       ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
988     res = _progressByTic * _progressTic;
989     //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
990   }
991   return Min ( res, 0.98 );
992 }
993
994 //=============================================================================
995 /*!
996  *
997  */
998 //=============================================================================
999
1000 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
1001                                       const TopoDS_Shape& aShape,
1002                                       MapShapeNbElems& aResMap)
1003 {
1004   smIdType nbtri = 0, nbqua = 0;
1005   double fullArea = 0.0;
1006   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
1007     TopoDS_Face F = TopoDS::Face( expF.Current() );
1008     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1009     MapShapeNbElemsItr anIt = aResMap.find(sm);
1010     if( anIt==aResMap.end() ) {
1011       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1012       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
1013       return false;
1014     }
1015     std::vector<smIdType> aVec = (*anIt).second;
1016     nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1017     nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1018     GProp_GProps G;
1019     BRepGProp::SurfaceProperties(F,G);
1020     double anArea = G.Mass();
1021     fullArea += anArea;
1022   }
1023
1024   // collect info from edges
1025   smIdType nb0d_e = 0, nb1d_e = 0;
1026   bool IsQuadratic = false;
1027   bool IsFirst = true;
1028   TopTools_MapOfShape tmpMap;
1029   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
1030     TopoDS_Edge E = TopoDS::Edge(expF.Current());
1031     if( tmpMap.Contains(E) )
1032       continue;
1033     tmpMap.Add(E);
1034     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
1035     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
1036     if( anIt==aResMap.end() ) {
1037       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
1038       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
1039                                             "Submesh can not be evaluated",this));
1040       return false;
1041     }
1042     std::vector<smIdType> aVec = (*anIt).second;
1043     nb0d_e += aVec[SMDSEntity_Node];
1044     nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1045     if(IsFirst) {
1046       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1047       IsFirst = false;
1048     }
1049   }
1050   tmpMap.Clear();
1051
1052   double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
1053   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
1054   double ELen = Min(ELen_vol,ELen_face*2);
1055
1056   GProp_GProps G;
1057   BRepGProp::VolumeProperties(aShape,G);
1058   double aVolume = G.Mass();
1059   double tetrVol = 0.1179*ELen*ELen*ELen;
1060   double CoeffQuality = 0.9;
1061   smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
1062   smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
1063   smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
1064   std::vector<smIdType> aVec(SMDSEntity_Last);
1065   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1066   if( IsQuadratic ) {
1067     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
1068     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
1069     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
1070   }
1071   else {
1072     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
1073     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
1074     aVec[SMDSEntity_Pyramid] = nbqua;
1075   }
1076   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1077   aResMap.insert(std::make_pair(sm,aVec));
1078
1079   return true;
1080 }
1081
1082