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