Salome HOME
Creating Remote and SA NETGEN_3D plugins
[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 // TODO: remove use of netgen_param
36 #include "NETGENPlugin_DriverParam.hxx"
37
38 #include <SMDS_MeshElement.hxx>
39 #include <SMDS_MeshNode.hxx>
40 #include <SMESHDS_Mesh.hxx>
41 #include <SMESH_Comment.hxx>
42 #include <SMESH_ControlsDef.hxx>
43 #include <SMESH_Gen.hxx>
44 #include <SMESH_Mesh.hxx>
45 #include <SMESH_MeshEditor.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_MaxElementVolume.hxx>
49 #include <StdMeshers_QuadToTriaAdaptor.hxx>
50 #include <StdMeshers_ViscousLayers.hxx>
51 #include <SMESH_subMesh.hxx>
52
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
73 /*
74   Netgen include files
75 */
76
77 #ifndef OCCGEOMETRY
78 #define OCCGEOMETRY
79 #endif
80 #include <occgeom.hpp>
81
82 #ifdef NETGEN_V5
83 #include <ngexception.hpp>
84 #endif
85 #ifdef NETGEN_V6
86 #include <core/exception.hpp>
87 #endif
88
89 namespace nglib {
90 #include <nglib.h>
91 }
92 namespace netgen {
93
94   NETGENPLUGIN_DLL_HEADER
95   extern MeshingParameters mparam;
96
97   NETGENPLUGIN_DLL_HEADER
98   extern volatile multithreadt multithread;
99 }
100 using namespace nglib;
101 using namespace std;
102
103 //=============================================================================
104 /*!
105  *
106  */
107 //=============================================================================
108
109 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
110   : SMESH_3D_Algo(hypId, gen)
111 {
112   _name = "NETGEN_3D";
113   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
114   _compatibleHypothesis.push_back("MaxElementVolume");
115   _compatibleHypothesis.push_back("NETGEN_Parameters");
116   _compatibleHypothesis.push_back("ViscousLayers");
117
118   _maxElementVolume = 0.;
119
120   _hypMaxElementVolume = NULL;
121   _hypParameters = NULL;
122   _viscousLayersHyp = NULL;
123
124   _requireShape = false; // can work without shape
125 }
126
127 //=============================================================================
128 /*!
129  *
130  */
131 //=============================================================================
132
133 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
134 {
135 }
136
137 //=============================================================================
138 /*!
139  *
140  */
141 //=============================================================================
142
143 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
144                                               const TopoDS_Shape& aShape,
145                                               Hypothesis_Status&  aStatus)
146 {
147   _hypMaxElementVolume = NULL;
148   _hypParameters = NULL;
149   _viscousLayersHyp = NULL;
150   _maxElementVolume = DBL_MAX;
151
152   // for correct work of GetProgress():
153   //netgen::multithread.percent = 0.;
154   //netgen::multithread.task = "Volume meshing";
155   _progressByTic = -1.;
156
157   list<const SMESHDS_Hypothesis*>::const_iterator itl;
158   //const SMESHDS_Hypothesis* theHyp;
159
160   const list<const SMESHDS_Hypothesis*>& hyps =
161     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
162   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
163   if ( h == hyps.end())
164   {
165     aStatus = SMESH_Hypothesis::HYP_OK;
166     return true;  // can work with no hypothesis
167   }
168
169   aStatus = HYP_OK;
170   for ( ; h != hyps.end(); ++h )
171   {
172     if ( !_hypMaxElementVolume )
173       _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
174     if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
175       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
176     if ( ! _hypParameters )
177       _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
178
179     if ( *h != _hypMaxElementVolume &&
180          *h != _viscousLayersHyp &&
181          *h != _hypParameters &&
182          !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
183       aStatus = HYP_INCOMPATIBLE;
184   }
185   if ( _hypMaxElementVolume && _hypParameters )
186     aStatus = HYP_INCOMPATIBLE;
187   else if ( aStatus == HYP_OK && _viscousLayersHyp )
188     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
189
190   if ( _hypMaxElementVolume )
191     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
192
193   return aStatus == HYP_OK;
194 }
195
196
197
198 //=============================================================================
199 /*!
200  *Here we are going to use the NETGEN mesher
201  */
202 //=============================================================================
203
204 /**
205  * @brief Get an iterator on the Surface element with their orientation
206  *
207  */
208
209 bool NETGENPlugin_NETGEN_3D::getSurfaceElements(
210     SMESH_Mesh&         aMesh,
211     const TopoDS_Shape& aShape,
212     SMESH_ProxyMesh::Ptr proxyMesh,
213     NETGENPlugin_Internals &internals,
214     SMESH_MesherHelper &helper,
215     netgen_params &aParams,
216     std::map<const SMDS_MeshElement*, tuple<bool, bool>>& listElements
217 )
218 {
219   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
220   TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
221   bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
222
223   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
224   {
225     const TopoDS_Shape& aShapeFace = exFa.Current();
226     int faceID = meshDS->ShapeToIndex( aShapeFace );
227     bool isInternalFace = internals.isInternalShape( faceID );
228     bool isRev = false;
229     if ( checkReverse && !isInternalFace &&
230           helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
231       // IsReversedSubMesh() can work wrong on strongly curved faces,
232       // so we use it as less as possible
233       isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
234
235     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
236     if ( !aSubMeshDSFace ) continue;
237
238     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
239     if ( aParams._quadraticMesh &&
240           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
241     {
242       // add medium nodes of proxy triangles to helper (#16843)
243       while ( iteratorElem->more() )
244         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
245
246       iteratorElem = aSubMeshDSFace->GetElements();
247     }
248     while(iteratorElem->more()){
249       const SMDS_MeshElement* elem = iteratorElem->next();
250       // check mesh face
251       if ( !elem ){
252         aParams._error = COMPERR_BAD_INPUT_MESH;
253         aParams._comment = "Null element encounters";
254         return true;
255       }
256       if ( elem->NbCornerNodes() != 3 ){
257         aParams._error = COMPERR_BAD_INPUT_MESH;
258         aParams._comment = "Not triangle element encounters";
259         return true;
260       }
261       listElements[elem] = tuple(isRev, isInternalFace);
262     }
263   }
264
265   return false;
266 }
267
268
269 bool NETGENPlugin_NETGEN_3D::computeFillNgMesh(
270   SMESH_Mesh&         aMesh,
271   const TopoDS_Shape& aShape,
272   vector< const SMDS_MeshNode* > &nodeVec,
273   NETGENPlugin_NetgenLibWrapper &ngLib,
274   SMESH_MesherHelper &helper,
275   netgen_params &aParams,
276   int &Netgen_NbOfNodes)
277 {
278   netgen::multithread.terminate = 0;
279   netgen::multithread.task = "Volume meshing";
280   aParams._progressByTic = -1.;
281
282   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
283
284   aParams._quadraticMesh = helper.IsQuadraticSubMesh(aShape);
285   helper.SetElementsOnShape( true );
286
287   Netgen_NbOfNodes = 0;
288   double Netgen_point[3];
289   int Netgen_triangle[3];
290
291   Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
292
293   {
294     const int invalid_ID = -1;
295
296     SMESH::Controls::Area areaControl;
297     SMESH::Controls::TSequenceOfXYZ nodesCoords;
298
299     // maps nodes to ng ID
300     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
301     typedef TNodeToIDMap::value_type                     TN2ID;
302     TNodeToIDMap nodeToNetgenID;
303
304     // find internal shapes
305     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
306
307     // ---------------------------------
308     // Feed the Netgen with surface mesh
309     // ---------------------------------
310     bool isRev=false;
311     bool isInternalFace=false;
312
313     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
314     if ( aParams._viscousLayersHyp )
315     {
316       netgen::multithread.percent = 3;
317       proxyMesh = aParams._viscousLayersHyp->Compute( aMesh, aShape );
318       if ( !proxyMesh )
319         return false;
320     }
321     if ( aMesh.NbQuadrangles() > 0 )
322     {
323       netgen::multithread.percent = 6;
324       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
325       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
326       proxyMesh.reset( Adaptor );
327     }
328
329     std::map<const SMDS_MeshElement*, tuple<bool, bool>> listElements;
330     bool ret = getSurfaceElements(aMesh, aShape, proxyMesh, internals, helper, aParams, listElements);
331     if(ret)
332       return ret;
333
334     for ( auto const& [elem, info] : listElements ) // loop on elements on a geom face
335     {
336       isRev = get<0>(info);
337       isInternalFace = get<1>(info);
338       // Add nodes of triangles and triangles them-selves to netgen mesh
339
340       // add three nodes of triangle
341       bool hasDegen = false;
342       for ( int iN = 0; iN < 3; ++iN )
343       {
344         const SMDS_MeshNode* node = elem->GetNode( iN );
345         const int shapeID = node->getshapeId();
346         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
347               helper.IsDegenShape( shapeID ))
348         {
349           // ignore all nodes on degeneraged edge and use node on its vertex instead
350           TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
351           node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
352           hasDegen = true;
353         }
354         int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
355         if ( ngID == invalid_ID )
356         {
357           ngID = ++Netgen_NbOfNodes;
358           Netgen_point [ 0 ] = node->X();
359           Netgen_point [ 1 ] = node->Y();
360           Netgen_point [ 2 ] = node->Z();
361           Ng_AddPoint(Netgen_mesh, Netgen_point);
362         }
363         Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
364       }
365       // add triangle
366       if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
367                         Netgen_triangle[0] == Netgen_triangle[2] ||
368                         Netgen_triangle[2] == Netgen_triangle[1] ))
369         continue;
370
371       Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
372
373       if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
374       {
375         swap( Netgen_triangle[1], Netgen_triangle[2] );
376         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
377       }
378     } // loop on elements on a face
379
380     // insert old nodes into nodeVec
381     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
382     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
383     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
384       nodeVec[ n_id->second ] = n_id->first;
385     nodeToNetgenID.clear();
386
387     if ( internals.hasInternalVertexInSolid() )
388     {
389       netgen::OCCGeometry occgeo;
390       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
391                                                    (netgen::Mesh&) *Netgen_mesh,
392                                                    nodeVec,
393                                                    internals);
394     }
395   }
396   Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
397   return false;
398 }
399
400 bool NETGENPlugin_NETGEN_3D::computePrepareParam(
401   SMESH_Mesh&         aMesh,
402   NETGENPlugin_NetgenLibWrapper &ngLib,
403   netgen::OCCGeometry &occgeo,
404   SMESH_MesherHelper &helper,
405   netgen_params &aParams,
406   int &endWith)
407
408 {
409   netgen::multithread.terminate = 0;
410
411   netgen::Mesh* ngMesh = ngLib._ngMesh;
412
413   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
414
415
416   if ( aParams._hypParameters )
417   {
418     aMesher.SetParameters( aParams._hypParameters );
419
420     if ( !aParams._hypParameters->GetLocalSizesAndEntries().empty() ||
421          !aParams._hypParameters->GetMeshSizeFile().empty() )
422     {
423       if ( ! &ngMesh->LocalHFunction() )
424       {
425         netgen::Point3d pmin, pmax;
426         ngMesh->GetBox( pmin, pmax, 0 );
427         ngMesh->SetLocalH( pmin, pmax, aParams._hypParameters->GetGrowthRate() );
428       }
429       aMesher.SetLocalSize( occgeo, *ngMesh );
430
431       try {
432         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
433       } catch (netgen::NgException & ex) {
434         aParams._error = COMPERR_BAD_PARMETERS;
435         aParams._comment = ex.What();
436         return false;
437       }
438     }
439     if ( !aParams._hypParameters->GetOptimize() )
440       endWith = netgen::MESHCONST_MESHVOLUME;
441   }
442   else if ( aParams._hypMaxElementVolume )
443   {
444     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( aParams.maxElementVolume, 1/3. );
445     // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
446   }
447   else if ( aMesh.HasShapeToMesh() )
448   {
449     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
450     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
451   }
452   else
453   {
454     netgen::Point3d pmin, pmax;
455     ngMesh->GetBox (pmin, pmax);
456     netgen::mparam.maxh = Dist(pmin, pmax)/2;
457   }
458
459   if ( !aParams._hypParameters && aMesh.HasShapeToMesh() )
460   {
461     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
462   }
463   return false;
464 }
465
466 bool NETGENPlugin_NETGEN_3D::computeRunMesher(
467   netgen::OCCGeometry &occgeo,
468   vector< const SMDS_MeshNode* > &nodeVec,
469   netgen::Mesh* ngMesh,
470   NETGENPlugin_NetgenLibWrapper &ngLib,
471   netgen_params &aParams,
472   int &startWith, int &endWith)
473 {
474   int err = 1;
475
476   try
477   {
478     OCC_CATCH_SIGNALS;
479
480     ngLib.CalcLocalH(ngMesh);
481     err = ngLib.GenerateMesh(occgeo, startWith, endWith);
482
483     if(netgen::multithread.terminate)
484       return false;
485     if ( err ){
486       aParams._comment = SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
487       return true;
488     }
489   }
490   catch (Standard_Failure& ex)
491   {
492     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
493     str << " at " << netgen::multithread.task
494         << ": " << ex.DynamicType()->Name();
495     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
496       str << ": " << ex.GetMessageString();
497     aParams._comment = str;
498     return true;
499   }
500   catch (netgen::NgException& exc)
501   {
502     SMESH_Comment str("NgException");
503     if ( strlen( netgen::multithread.task ) > 0 )
504       str << " at " << netgen::multithread.task;
505     str << ": " << exc.What();
506     aParams._comment = str;
507     return true;
508   }
509   catch (...)
510   {
511     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
512     if ( strlen( netgen::multithread.task ) > 0 )
513       str << " at " << netgen::multithread.task;
514     aParams._comment = str;
515     return true;
516   }
517
518   if ( err )
519   {
520     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
521     if ( ce && ce->HasBadElems() ){
522       aParams._error = ce->myName;
523       aParams._comment = ce->myComment;
524       return true;
525     }
526   }
527
528   return false;
529 }
530
531 bool NETGENPlugin_NETGEN_3D::computeFillMesh(
532   vector< const SMDS_MeshNode* > &nodeVec,
533   NETGENPlugin_NetgenLibWrapper &ngLib,
534   SMESH_MesherHelper &helper,
535   int &Netgen_NbOfNodes
536   )
537 {
538   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
539
540   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
541   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
542
543   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
544   if ( isOK )
545   {
546     double Netgen_point[3];
547     int    Netgen_tetrahedron[4];
548
549     // create and insert new nodes into nodeVec
550     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
551     int nodeIndex = Netgen_NbOfNodes + 1;
552     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
553     {
554       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
555       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
556     }
557
558     // create tetrahedrons
559     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
560     {
561       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
562       try
563       {
564         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
565                           nodeVec.at( Netgen_tetrahedron[1] ),
566                           nodeVec.at( Netgen_tetrahedron[2] ),
567                           nodeVec.at( Netgen_tetrahedron[3] ));
568       }
569       catch (...)
570       {
571       }
572     }
573   }
574   return false;
575 }
576
577 bool NETGENPlugin_NETGEN_3D::Compute(
578   SMESH_Mesh&         aMesh,
579   const TopoDS_Shape& aShape)
580 {
581   // vector of nodes in which node index == netgen ID
582   vector< const SMDS_MeshNode* > nodeVec;
583   NETGENPlugin_NetgenLibWrapper ngLib;
584   SMESH_MesherHelper helper(aMesh);
585   int startWith = netgen::MESHCONST_MESHVOLUME;
586   int endWith   = netgen::MESHCONST_OPTVOLUME;
587   int Netgen_NbOfNodes;
588
589   netgen_params aParams;
590
591   aParams._hypParameters = const_cast<NETGENPlugin_Hypothesis*>(_hypParameters);
592   aParams._hypMaxElementVolume = const_cast<StdMeshers_MaxElementVolume*>(_hypMaxElementVolume);
593   aParams.maxElementVolume = _maxElementVolume;
594   aParams._progressByTic = _progressByTic;
595   aParams._quadraticMesh = _quadraticMesh;
596   aParams._viscousLayersHyp = const_cast<StdMeshers_ViscousLayers*>(_viscousLayersHyp);
597
598   bool ret;
599   ret = computeFillNgMesh(aMesh, aShape, nodeVec, ngLib, helper, aParams, Netgen_NbOfNodes);
600   if(ret)
601     return error( aParams._error, aParams._comment);
602
603   netgen::OCCGeometry occgeo;
604   computePrepareParam(aMesh, ngLib, occgeo, helper, aParams, endWith);
605   ret = computeRunMesher(occgeo, nodeVec, ngLib._ngMesh, ngLib, aParams, startWith, endWith);
606   if(ret){
607     if(aParams._error)
608       return error(aParams._error, aParams._comment);
609
610     error(aParams._comment);
611     return true;
612   }
613   computeFillMesh(nodeVec, ngLib, helper, Netgen_NbOfNodes);
614
615   return false;
616
617 }
618
619 //================================================================================
620 /*!
621  * \brief set parameters and generate the volume mesh
622  */
623 //================================================================================
624
625 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
626                                      SMESH_MesherHelper&             helper,
627                                      vector< const SMDS_MeshNode* >& nodeVec,
628                                      NETGENPlugin_NetgenLibWrapper&  ngLib)
629 {
630   auto time0 = std::chrono::high_resolution_clock::now();
631
632   netgen::multithread.terminate = 0;
633
634   netgen::Mesh* ngMesh = ngLib._ngMesh;
635   Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
636   int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
637
638   int startWith = netgen::MESHCONST_MESHVOLUME;
639   int endWith   = netgen::MESHCONST_OPTVOLUME;
640   int err = 1;
641
642   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
643   netgen::OCCGeometry occgeo;
644
645   if ( _hypParameters )
646   {
647     aMesher.SetParameters( _hypParameters );
648
649     if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
650          !_hypParameters->GetMeshSizeFile().empty() )
651     {
652       if ( ! &ngMesh->LocalHFunction() )
653       {
654         netgen::Point3d pmin, pmax;
655         ngMesh->GetBox( pmin, pmax, 0 );
656         ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
657       }
658       aMesher.SetLocalSize( occgeo, *ngMesh );
659
660       try {
661         ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
662       } catch (netgen::NgException & ex) {
663         return error( COMPERR_BAD_PARMETERS, ex.What() );
664       }
665     }
666     if ( !_hypParameters->GetOptimize() )
667       endWith = netgen::MESHCONST_MESHVOLUME;
668   }
669   else if ( _hypMaxElementVolume )
670   {
671     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
672     // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
673   }
674   else if ( aMesh.HasShapeToMesh() )
675   {
676     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
677     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
678   }
679   else
680   {
681     netgen::Point3d pmin, pmax;
682     ngMesh->GetBox (pmin, pmax);
683     netgen::mparam.maxh = Dist(pmin, pmax)/2;
684   }
685
686   if ( !_hypParameters && aMesh.HasShapeToMesh() )
687   {
688     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
689   }
690
691   try
692   {
693     OCC_CATCH_SIGNALS;
694     auto time0 = std::chrono::high_resolution_clock::now();
695
696     ngLib.CalcLocalH(ngMesh);
697     err = ngLib.GenerateMesh(occgeo, startWith, endWith);
698
699     if(netgen::multithread.terminate)
700       return false;
701     if ( err )
702       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
703   }
704   catch (Standard_Failure& ex)
705   {
706     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
707     str << " at " << netgen::multithread.task
708         << ": " << ex.DynamicType()->Name();
709     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
710       str << ": " << ex.GetMessageString();
711     error(str);
712   }
713   catch (netgen::NgException& exc)
714   {
715     SMESH_Comment str("NgException");
716     if ( strlen( netgen::multithread.task ) > 0 )
717       str << " at " << netgen::multithread.task;
718     str << ": " << exc.What();
719     error(str);
720   }
721   catch (...)
722   {
723     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
724     if ( strlen( netgen::multithread.task ) > 0 )
725       str << " at " << netgen::multithread.task;
726     error(str);
727   }
728   auto time1 = std::chrono::high_resolution_clock::now();
729   auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time1-time0);
730   std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
731
732   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
733   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
734
735   // -------------------------------------------------------------------
736   // Feed back the SMESHDS with the generated Nodes and Volume Elements
737   // -------------------------------------------------------------------
738
739   if ( err )
740   {
741     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
742     if ( ce && ce->HasBadElems() )
743       error( ce );
744   }
745
746   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
747   if ( isOK )
748   {
749     double Netgen_point[3];
750     int    Netgen_tetrahedron[4];
751
752     // create and insert new nodes into nodeVec
753     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
754     int nodeIndex = Netgen_NbOfNodes + 1;
755     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
756     {
757       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
758       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
759     }
760
761     // create tetrahedrons
762     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
763     {
764       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
765       try
766       {
767         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
768                           nodeVec.at( Netgen_tetrahedron[1] ),
769                           nodeVec.at( Netgen_tetrahedron[2] ),
770                           nodeVec.at( Netgen_tetrahedron[3] ));
771       }
772       catch (...)
773       {
774       }
775     }
776   }
777   auto time2 = std::chrono::high_resolution_clock::now();
778   elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(time2-time1);
779   std::cout << "Time for seq:compute: " << elapsed.count() * 1e-9 << std::endl;
780
781
782   return !err;
783 }
784
785 //================================================================================
786 /*!
787  * \brief Compute tetrahedral mesh from 2D mesh without geometry
788  */
789 //================================================================================
790
791 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
792                                      SMESH_MesherHelper* aHelper)
793 {
794   const int invalid_ID = -1;
795
796   netgen::multithread.terminate = 0;
797   _progressByTic = -1.;
798
799   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
800   if ( MeshType == SMESH_MesherHelper::COMP )
801     return error( COMPERR_BAD_INPUT_MESH,
802                   SMESH_Comment("Mesh with linear and quadratic elements given"));
803
804   aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
805
806   // ---------------------------------
807   // Feed the Netgen with surface mesh
808   // ---------------------------------
809
810   int Netgen_NbOfNodes = 0;
811   double Netgen_point[3];
812   int Netgen_triangle[3];
813
814   NETGENPlugin_NetgenLibWrapper ngLib;
815   Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
816
817   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
818   if ( aMesh.NbQuadrangles() > 0 )
819   {
820     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
821     Adaptor->Compute(aMesh);
822     proxyMesh.reset( Adaptor );
823
824     if ( aHelper->IsQuadraticMesh() )
825     {
826       SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
827       while( fIt->more())
828         aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
829     }
830   }
831
832   // maps nodes to ng ID
833   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
834   typedef TNodeToIDMap::value_type                     TN2ID;
835   TNodeToIDMap nodeToNetgenID;
836
837   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
838   while( fIt->more())
839   {
840     // check element
841     const SMDS_MeshElement* elem = fIt->next();
842     if ( !elem )
843       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
844     if ( elem->NbCornerNodes() != 3 )
845       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
846
847     // add three nodes of triangle
848     for ( int iN = 0; iN < 3; ++iN )
849     {
850       const SMDS_MeshNode* node = elem->GetNode( iN );
851       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
852       if ( ngID == invalid_ID )
853       {
854         ngID = ++Netgen_NbOfNodes;
855         Netgen_point [ 0 ] = node->X();
856         Netgen_point [ 1 ] = node->Y();
857         Netgen_point [ 2 ] = node->Z();
858         Ng_AddPoint(Netgen_mesh, Netgen_point);
859       }
860       Netgen_triangle[ iN ] = ngID;
861     }
862     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
863   }
864   proxyMesh.reset(); // delete tmp faces
865
866   // vector of nodes in which node index == netgen ID
867   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
868   // insert old nodes into nodeVec
869   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
870   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
871     nodeVec.at( n_id->second ) = n_id->first;
872   nodeToNetgenID.clear();
873
874   // -------------------------
875   // Generate the volume mesh
876   // -------------------------
877
878   return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
879 }
880
881 void NETGENPlugin_NETGEN_3D::CancelCompute()
882 {
883   SMESH_Algo::CancelCompute();
884   netgen::multithread.terminate = 1;
885 }
886
887 //================================================================================
888 /*!
889  * \brief Return Compute progress
890  */
891 //================================================================================
892
893 double NETGENPlugin_NETGEN_3D::GetProgress() const
894 {
895   double res;
896   const char* volMeshing = "Volume meshing";
897   const char* dlnMeshing = "Delaunay meshing";
898   const double meshingRatio = 0.15;
899   const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
900
901   if ( _progressByTic < 0. &&
902        ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
903          strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
904   {
905     res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
906     //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
907   }
908   else // different otimizations
909   {
910     if ( _progressByTic < 0. )
911       ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
912     res = _progressByTic * _progressTic;
913     //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
914   }
915   return Min ( res, 0.98 );
916 }
917
918 //=============================================================================
919 /*!
920  *
921  */
922 //=============================================================================
923
924 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
925                                       const TopoDS_Shape& aShape,
926                                       MapShapeNbElems& aResMap)
927 {
928   smIdType nbtri = 0, nbqua = 0;
929   double fullArea = 0.0;
930   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
931     TopoDS_Face F = TopoDS::Face( expF.Current() );
932     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
933     MapShapeNbElemsItr anIt = aResMap.find(sm);
934     if( anIt==aResMap.end() ) {
935       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
936       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
937       return false;
938     }
939     std::vector<smIdType> aVec = (*anIt).second;
940     nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
941     nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
942     GProp_GProps G;
943     BRepGProp::SurfaceProperties(F,G);
944     double anArea = G.Mass();
945     fullArea += anArea;
946   }
947
948   // collect info from edges
949   smIdType nb0d_e = 0, nb1d_e = 0;
950   bool IsQuadratic = false;
951   bool IsFirst = true;
952   TopTools_MapOfShape tmpMap;
953   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
954     TopoDS_Edge E = TopoDS::Edge(expF.Current());
955     if( tmpMap.Contains(E) )
956       continue;
957     tmpMap.Add(E);
958     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
959     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
960     if( anIt==aResMap.end() ) {
961       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
962       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
963                                             "Submesh can not be evaluated",this));
964       return false;
965     }
966     std::vector<smIdType> aVec = (*anIt).second;
967     nb0d_e += aVec[SMDSEntity_Node];
968     nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
969     if(IsFirst) {
970       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
971       IsFirst = false;
972     }
973   }
974   tmpMap.Clear();
975
976   double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
977   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
978   double ELen = Min(ELen_vol,ELen_face*2);
979
980   GProp_GProps G;
981   BRepGProp::VolumeProperties(aShape,G);
982   double aVolume = G.Mass();
983   double tetrVol = 0.1179*ELen*ELen*ELen;
984   double CoeffQuality = 0.9;
985   smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
986   smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
987   smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
988   std::vector<smIdType> aVec(SMDSEntity_Last);
989   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
990   if( IsQuadratic ) {
991     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
992     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
993     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
994   }
995   else {
996     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
997     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
998     aVec[SMDSEntity_Pyramid] = nbqua;
999   }
1000   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1001   aResMap.insert(std::make_pair(sm,aVec));
1002
1003   return true;
1004 }
1005
1006