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