]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_3D.cxx
Salome HOME
Better handle of deletion of temporary folder + missing delete of temporary SMESH_Mesh
[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 "NETGENPlugin_DriverParam.hxx"
36
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>
53
54
55 #include <BRepGProp.hxx>
56 #include <BRep_Tool.hxx>
57 #include <GProp_GProps.hxx>
58 #include <TopExp.hxx>
59 #include <TopExp_Explorer.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopoDS.hxx>
62
63 #include <Standard_Failure.hxx>
64 #include <Standard_ErrorHandler.hxx>
65
66 #include <utilities.h>
67
68 #include <list>
69 #include <vector>
70 #include <map>
71
72 #include <cstdlib>
73 #include <boost/filesystem.hpp>
74 namespace fs = boost::filesystem;
75
76 /*
77   Netgen include files
78 */
79
80 #ifndef OCCGEOMETRY
81 #define OCCGEOMETRY
82 #endif
83 #include <occgeom.hpp>
84
85 #ifdef NETGEN_V5
86 #include <ngexception.hpp>
87 #endif
88 #ifdef NETGEN_V6
89 #include <core/exception.hpp>
90 #endif
91
92 namespace nglib {
93 #include <nglib.h>
94 }
95 namespace netgen {
96
97   NETGENPLUGIN_DLL_HEADER
98   extern MeshingParameters mparam;
99
100   NETGENPLUGIN_DLL_HEADER
101   extern volatile multithreadt multithread;
102 }
103 using namespace nglib;
104 using namespace std;
105
106 //=============================================================================
107 /*!
108  *
109  */
110 //=============================================================================
111
112 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
113   : SMESH_3D_Algo(hypId, gen)
114 {
115   _name = "NETGEN_3D";
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");
120
121   _maxElementVolume = 0.;
122
123   _hypMaxElementVolume = NULL;
124   _hypParameters = NULL;
125   _viscousLayersHyp = NULL;
126
127   _requireShape = false; // can work without shape
128 }
129
130 //=============================================================================
131 /*!
132  *
133  */
134 //=============================================================================
135
136 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
137 {
138 }
139
140 //=============================================================================
141 /*!
142  *
143  */
144 //=============================================================================
145
146 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
147                                               const TopoDS_Shape& aShape,
148                                               Hypothesis_Status&  aStatus)
149 {
150   _hypMaxElementVolume = NULL;
151   _hypParameters = NULL;
152   _viscousLayersHyp = NULL;
153   _maxElementVolume = DBL_MAX;
154
155   // for correct work of GetProgress():
156   //netgen::multithread.percent = 0.;
157   //netgen::multithread.task = "Volume meshing";
158   _progressByTic = -1.;
159
160   list<const SMESHDS_Hypothesis*>::const_iterator itl;
161   //const SMESHDS_Hypothesis* theHyp;
162
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())
167   {
168     aStatus = SMESH_Hypothesis::HYP_OK;
169     return true;  // can work with no hypothesis
170   }
171
172   aStatus = HYP_OK;
173   for ( ; h != hyps.end(); ++h )
174   {
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 );
181
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;
187   }
188   if ( _hypMaxElementVolume && _hypParameters )
189     aStatus = HYP_INCOMPATIBLE;
190   else if ( aStatus == HYP_OK && _viscousLayersHyp )
191     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
192
193   if ( _hypMaxElementVolume )
194     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
195
196   return aStatus == HYP_OK;
197 }
198
199
200 void NETGENPlugin_NETGEN_3D::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
201 {
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();
221 #ifdef NETGEN_V6
222   // std::string
223   aParams.meshsizefilename = hyp->GetMeshSizeFile();
224 #else
225   // const char*
226   aParams.meshsizefilename = hyp->GetMeshSizeFile();
227 #endif
228 #ifdef NETGEN_V6
229   aParams.closeedgefac = 2;
230 #else
231   aParams.closeedgefac = 0;
232 #endif
233 }
234
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)
240 {
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;
245
246   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
247   {
248     const TopoDS_Shape& aShapeFace = exFa.Current();
249     int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
250     bool isInternalFace = internals.isInternalShape( faceID );
251     bool isRev = false;
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 ));
257
258     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
259     if ( !aSubMeshDSFace ) continue;
260
261     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
262     if ( aParams._quadraticMesh &&
263           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
264     {
265       // add medium nodes of proxy triangles to helper (#16843)
266       while ( iteratorElem->more() )
267         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
268
269       iteratorElem = aSubMeshDSFace->GetElements();
270     }
271     while ( iteratorElem->more() ) // loop on elements on a geom face
272     {
273       // check mesh face
274       const SMDS_MeshElement* elem = iteratorElem->next();
275       if ( !elem )
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
282
283   {
284     std::ofstream df(output_file, ios::out|ios::binary);
285     int size=elemOrientation.size();
286
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));
291     }
292   }
293 }
294
295 int NETGENPlugin_NETGEN_3D::RemoteCompute(SMESH_Mesh&         aMesh,
296                                           const TopoDS_Shape& aShape)
297 {
298   aMesh.Lock();
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;
305
306
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";
322
323   //Writing Shape
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;
328
329   //Writing hypo
330   netgen_params aParams;
331   fillParameters(_hypParameters, aParams);
332
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;
337
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;
343
344   aMesh.Unlock();
345   // Calling run_mesher
346   // TODO: check if we need to handle the .exe for windows
347   std::string cmd;
348   fs::path run_mesher_exe =
349     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
350     fs::path("bin")/
351     fs::path("salome")/
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() + " "
360                                + "NONE" +
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   aMesh.Unlock();
445
446   return true;
447 }
448
449 //=============================================================================
450 /*!
451  *Here we are going to use the NETGEN mesher
452  */
453 //=============================================================================
454
455 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
456                                      const TopoDS_Shape& aShape)
457 {
458   if(aMesh.IsParallel())
459     return RemoteCompute(aMesh, aShape);
460   auto time0 = std::chrono::high_resolution_clock::now();
461
462   netgen::multithread.terminate = 0;
463   netgen::multithread.task = "Volume meshing";
464   _progressByTic = -1.;
465
466   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
467
468   SMESH_MesherHelper helper(aMesh);
469   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
470   helper.SetElementsOnShape( true );
471
472   int Netgen_NbOfNodes = 0;
473   double Netgen_point[3];
474   int Netgen_triangle[3];
475
476   NETGENPlugin_NetgenLibWrapper ngLib;
477   Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
478
479   // vector of nodes in which node index == netgen ID
480   vector< const SMDS_MeshNode* > nodeVec;
481   {
482     const int invalid_ID = -1;
483
484     SMESH::Controls::Area areaControl;
485     SMESH::Controls::TSequenceOfXYZ nodesCoords;
486
487     // maps nodes to ng ID
488     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
489     typedef TNodeToIDMap::value_type                     TN2ID;
490     TNodeToIDMap nodeToNetgenID;
491
492     // find internal shapes
493     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
494
495     // ---------------------------------
496     // Feed the Netgen with surface mesh
497     // ---------------------------------
498
499     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
500     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
501
502     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
503     if ( _viscousLayersHyp )
504     {
505       netgen::multithread.percent = 3;
506       proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
507       if ( !proxyMesh )
508         return false;
509     }
510     if ( aMesh.NbQuadrangles() > 0 )
511     {
512       netgen::multithread.percent = 6;
513       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
514       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
515       proxyMesh.reset( Adaptor );
516     }
517
518     for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
519     {
520       const TopoDS_Shape& aShapeFace = exFa.Current();
521       int faceID = meshDS->ShapeToIndex( aShapeFace );
522       bool isInternalFace = internals.isInternalShape( faceID );
523       bool isRev = false;
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 ));
529
530       const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
531       if ( !aSubMeshDSFace ) continue;
532
533       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
534       if ( _quadraticMesh &&
535            dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
536       {
537         // add medium nodes of proxy triangles to helper (#16843)
538         while ( iteratorElem->more() )
539           helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
540
541         iteratorElem = aSubMeshDSFace->GetElements();
542       }
543       while ( iteratorElem->more() ) // loop on elements on a geom face
544       {
545         // check mesh face
546         const SMDS_MeshElement* elem = iteratorElem->next();
547         if ( !elem )
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");
551
552         // Add nodes of triangles and triangles them-selves to netgen mesh
553
554         // add three nodes of triangle
555         bool hasDegen = false;
556         for ( int iN = 0; iN < 3; ++iN )
557         {
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 ))
562           {
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 );
566             hasDegen = true;
567           }
568           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
569           if ( ngID == invalid_ID )
570           {
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);
576           }
577           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
578         }
579         // add triangle
580         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
581                           Netgen_triangle[0] == Netgen_triangle[2] ||
582                           Netgen_triangle[2] == Netgen_triangle[1] ))
583           continue;
584
585         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
586
587         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
588         {
589           swap( Netgen_triangle[1], Netgen_triangle[2] );
590           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
591         }
592       } // loop on elements on a face
593     } // loop on faces of a SOLID or SHELL
594
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();
601
602     if ( internals.hasInternalVertexInSolid() )
603     {
604       netgen::OCCGeometry occgeo;
605       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
606                                                    (netgen::Mesh&) *Netgen_mesh,
607                                                    nodeVec,
608                                                    internals);
609     }
610   }
611
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;
618
619   return (ngLib._isComputeOk = compute( aMesh, helper, nodeVec, ngLib ));
620 }
621
622 // namespace
623 // {
624 //   void limitVolumeSize( netgen::Mesh* ngMesh,
625 //                         double        maxh )
626 //   {
627 //     // get average h of faces
628 //     double faceh = 0;
629 //     int nbh = 0;
630 //     for (int i = 1; i <= ngMesh->GetNSE(); i++)
631 //     {
632 //       const netgen::Element2d& face = ngMesh->SurfaceElement(i);
633 //       for (int j=1; j <= face.GetNP(); ++j)
634 //       {
635 //         const netgen::PointIndex & i1 = face.PNumMod(j);
636 //         const netgen::PointIndex & i2 = face.PNumMod(j+1);
637 //         if ( i1 < i2 )
638 //         {
639 //           const netgen::Point3d & p1 = ngMesh->Point( i1 );
640 //           const netgen::Point3d & p2 = ngMesh->Point( i2 );
641 //           faceh += netgen::Dist2( p1, p2 );
642 //           nbh++;
643 //         }
644 //       }
645 //     }
646 //     faceh = Sqrt( faceh / nbh );
647
648 //     double compareh;
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;
655
656 //     if ( compareh > 0 )
657 //       maxh *= 1.2;
658 //     else
659 //       maxh *= 0.8;
660 //     // cerr << "maxh " << maxh << endl;
661
662 //     // get bnd box
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();
668
669 //     if ( ! & ngMesh->LocalHFunction() )
670 //       ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
671
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 ));
676
677 //     netgen::Point3d p;
678 //     for ( int i = 0; i <= nbX; ++i )
679 //     {
680 //       p.X() = pmin.X() +  i * dx / nbX;
681 //       for ( int j = 0; j <= nbY; ++j )
682 //       {
683 //         p.Y() = pmin.Y() +  j * dy / nbY;
684 //         for ( int k = 0; k <= nbZ; ++k )
685 //         {
686 //           p.Z() = pmin.Z() +  k * dz / nbZ;
687 //           ngMesh->RestrictLocalH( p, maxh );
688 //         }
689 //       }
690 //     }
691 //   }
692 // }
693
694 //================================================================================
695 /*!
696  * \brief set parameters and generate the volume mesh
697  */
698 //================================================================================
699
700 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
701                                      SMESH_MesherHelper&             helper,
702                                      vector< const SMDS_MeshNode* >& nodeVec,
703                                      NETGENPlugin_NetgenLibWrapper&  ngLib)
704 {
705   auto time0 = std::chrono::high_resolution_clock::now();
706
707   netgen::multithread.terminate = 0;
708
709   netgen::Mesh* ngMesh = ngLib._ngMesh;
710   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
711   int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
712
713   int startWith = netgen::MESHCONST_MESHVOLUME;
714   int endWith   = netgen::MESHCONST_OPTVOLUME;
715   int err = 1;
716
717   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
718   netgen::OCCGeometry occgeo;
719
720   if ( _hypParameters )
721   {
722     aMesher.SetParameters( _hypParameters );
723
724     if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
725          !_hypParameters->GetMeshSizeFile().empty() )
726     {
727       if ( ! &ngMesh->LocalHFunction() )
728       {
729         netgen::Point3d pmin, pmax;
730         ngMesh->GetBox( pmin, pmax, 0 );
731         ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
732       }
733       aMesher.SetLocalSize( occgeo, *ngMesh );
734
735       try {
736         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
737       } catch (netgen::NgException & ex) {
738         return error( COMPERR_BAD_PARMETERS, ex.What() );
739       }
740     }
741     if ( !_hypParameters->GetOptimize() )
742       endWith = netgen::MESHCONST_MESHVOLUME;
743   }
744   else if ( _hypMaxElementVolume )
745   {
746     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
747     // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
748   }
749   else if ( aMesh.HasShapeToMesh() )
750   {
751     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
752     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
753   }
754   else
755   {
756     netgen::Point3d pmin, pmax;
757     ngMesh->GetBox (pmin, pmax);
758     netgen::mparam.maxh = Dist(pmin, pmax)/2;
759   }
760
761   if ( !_hypParameters && aMesh.HasShapeToMesh() )
762   {
763     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
764   }
765
766   try
767   {
768     OCC_CATCH_SIGNALS;
769     auto time0 = std::chrono::high_resolution_clock::now();
770
771     ngLib.CalcLocalH(ngMesh);
772     err = ngLib.GenerateMesh(occgeo, startWith, endWith);
773
774     if(netgen::multithread.terminate)
775       return false;
776     if ( err )
777       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
778   }
779   catch (Standard_Failure& ex)
780   {
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();
786     error(str);
787   }
788   catch (netgen::NgException& exc)
789   {
790     SMESH_Comment str("NgException");
791     if ( strlen( netgen::multithread.task ) > 0 )
792       str << " at " << netgen::multithread.task;
793     str << ": " << exc.What();
794     error(str);
795   }
796   catch (...)
797   {
798     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
799     if ( strlen( netgen::multithread.task ) > 0 )
800       str << " at " << netgen::multithread.task;
801     error(str);
802   }
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;
806
807   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
808   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
809
810   // -------------------------------------------------------------------
811   // Feed back the SMESHDS with the generated Nodes and Volume Elements
812   // -------------------------------------------------------------------
813
814   if ( err )
815   {
816     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
817     if ( ce && ce->HasBadElems() )
818       error( ce );
819   }
820
821   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
822   if ( isOK )
823   {
824     double Netgen_point[3];
825     int    Netgen_tetrahedron[4];
826
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 )
831     {
832       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
833       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
834     }
835
836     // create tetrahedrons
837     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
838     {
839       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
840       try
841       {
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] ));
846       }
847       catch (...)
848       {
849       }
850     }
851   }
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;
855
856
857   return !err;
858 }
859
860 //================================================================================
861 /*!
862  * \brief Compute tetrahedral mesh from 2D mesh without geometry
863  */
864 //================================================================================
865
866 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
867                                      SMESH_MesherHelper* aHelper)
868 {
869   const int invalid_ID = -1;
870
871   netgen::multithread.terminate = 0;
872   _progressByTic = -1.;
873
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"));
878
879   aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
880
881   // ---------------------------------
882   // Feed the Netgen with surface mesh
883   // ---------------------------------
884
885   int Netgen_NbOfNodes = 0;
886   double Netgen_point[3];
887   int Netgen_triangle[3];
888
889   NETGENPlugin_NetgenLibWrapper ngLib;
890   Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
891
892   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
893   if ( aMesh.NbQuadrangles() > 0 )
894   {
895     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
896     Adaptor->Compute(aMesh);
897     proxyMesh.reset( Adaptor );
898
899     if ( aHelper->IsQuadraticMesh() )
900     {
901       SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
902       while( fIt->more())
903         aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
904     }
905   }
906
907   // maps nodes to ng ID
908   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
909   typedef TNodeToIDMap::value_type                     TN2ID;
910   TNodeToIDMap nodeToNetgenID;
911
912   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
913   while( fIt->more())
914   {
915     // check element
916     const SMDS_MeshElement* elem = fIt->next();
917     if ( !elem )
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");
921
922     // add three nodes of triangle
923     for ( int iN = 0; iN < 3; ++iN )
924     {
925       const SMDS_MeshNode* node = elem->GetNode( iN );
926       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
927       if ( ngID == invalid_ID )
928       {
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);
934       }
935       Netgen_triangle[ iN ] = ngID;
936     }
937     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
938   }
939   proxyMesh.reset(); // delete tmp faces
940
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();
948
949   // -------------------------
950   // Generate the volume mesh
951   // -------------------------
952
953   return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
954 }
955
956 void NETGENPlugin_NETGEN_3D::CancelCompute()
957 {
958   SMESH_Algo::CancelCompute();
959   netgen::multithread.terminate = 1;
960 }
961
962 //================================================================================
963 /*!
964  * \brief Return Compute progress
965  */
966 //================================================================================
967
968 double NETGENPlugin_NETGEN_3D::GetProgress() const
969 {
970   double res;
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++;
975
976   if ( _progressByTic < 0. &&
977        ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
978          strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
979   {
980     res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
981     //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
982   }
983   else // different otimizations
984   {
985     if ( _progressByTic < 0. )
986       ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
987     res = _progressByTic * _progressTic;
988     //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
989   }
990   return Min ( res, 0.98 );
991 }
992
993 //=============================================================================
994 /*!
995  *
996  */
997 //=============================================================================
998
999 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
1000                                       const TopoDS_Shape& aShape,
1001                                       MapShapeNbElems& aResMap)
1002 {
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));
1012       return false;
1013     }
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]);
1017     GProp_GProps G;
1018     BRepGProp::SurfaceProperties(F,G);
1019     double anArea = G.Mass();
1020     fullArea += anArea;
1021   }
1022
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) )
1031       continue;
1032     tmpMap.Add(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));
1039       return false;
1040     }
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]);
1044     if(IsFirst) {
1045       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1046       IsFirst = false;
1047     }
1048   }
1049   tmpMap.Clear();
1050
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);
1054
1055   GProp_GProps G;
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;
1065   if( IsQuadratic ) {
1066     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
1067     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
1068     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
1069   }
1070   else {
1071     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
1072     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
1073     aVec[SMDSEntity_Pyramid] = nbqua;
1074   }
1075   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1076   aResMap.insert(std::make_pair(sm,aVec));
1077
1078   return true;
1079 }
1080
1081