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