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