Salome HOME
Regression of SALOME_TESTS/Grids/smesh/viscous_layers_01/B2
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D.cxx
1 // Copyright (C) 2007-2016  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
49 #include <BRepGProp.hxx>
50 #include <BRep_Tool.hxx>
51 #include <GProp_GProps.hxx>
52 #include <TopExp.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_ListIteratorOfListOfShape.hxx>
55 #include <TopoDS.hxx>
56
57 #include <Standard_Failure.hxx>
58 #include <Standard_ErrorHandler.hxx>
59
60 #include <utilities.h>
61
62 #include <list>
63 #include <vector>
64 #include <map>
65
66 /*
67   Netgen include files
68 */
69
70 #ifndef OCCGEOMETRY
71 #define OCCGEOMETRY
72 #endif
73 #include <occgeom.hpp>
74 namespace nglib {
75 #include <nglib.h>
76 }
77 namespace netgen {
78 #ifdef NETGEN_V5
79   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
80 #else
81   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
82 #endif
83   extern MeshingParameters mparam;
84   extern volatile multithreadt multithread;
85 }
86 using namespace nglib;
87 using namespace std;
88
89 //=============================================================================
90 /*!
91  *  
92  */
93 //=============================================================================
94
95 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, int studyId,
96                              SMESH_Gen* gen)
97   : SMESH_3D_Algo(hypId, studyId, gen)
98 {
99   _name = "NETGEN_3D";
100   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
101   _compatibleHypothesis.push_back("MaxElementVolume");
102   _compatibleHypothesis.push_back("NETGEN_Parameters");
103   _compatibleHypothesis.push_back("ViscousLayers");
104
105   _maxElementVolume = 0.;
106
107   _hypMaxElementVolume = NULL;
108   _hypParameters = NULL;
109   _viscousLayersHyp = NULL;
110
111   _requireShape = false; // can work without shape
112 }
113
114 //=============================================================================
115 /*!
116  *  
117  */
118 //=============================================================================
119
120 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
121 {
122 }
123
124 //=============================================================================
125 /*!
126  *  
127  */
128 //=============================================================================
129
130 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh&         aMesh,
131                                               const TopoDS_Shape& aShape,
132                                               Hypothesis_Status&  aStatus)
133 {
134   _hypMaxElementVolume = NULL;
135   _hypParameters = NULL;
136   _viscousLayersHyp = NULL;
137   _maxElementVolume = DBL_MAX;
138
139   // for correct work of GetProgress():
140   netgen::multithread.percent = 0.;
141   netgen::multithread.task = "Volume meshing";
142   _progressByTic = -1.;
143
144   list<const SMESHDS_Hypothesis*>::const_iterator itl;
145   //const SMESHDS_Hypothesis* theHyp;
146
147   const list<const SMESHDS_Hypothesis*>& hyps =
148     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
149   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
150   if ( h == hyps.end())
151   {
152     aStatus = SMESH_Hypothesis::HYP_OK;
153     return true;  // can work with no hypothesis
154   }
155
156   aStatus = HYP_OK;
157   for ( ; h != hyps.end(); ++h )
158   {
159     if ( !_hypMaxElementVolume )
160       _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
161     if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
162       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
163     if ( ! _hypParameters )
164       _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
165
166     if ( *h != _hypMaxElementVolume &&
167          *h != _viscousLayersHyp &&
168          *h != _hypParameters &&
169          !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
170       aStatus = HYP_INCOMPATIBLE;
171   }
172   if ( _hypMaxElementVolume && _hypParameters )
173     aStatus = HYP_INCOMPATIBLE;
174   else if ( aStatus == HYP_OK && _viscousLayersHyp )
175     error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
176
177   if ( _hypMaxElementVolume )
178     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
179
180   return aStatus == HYP_OK;
181 }
182
183 //=============================================================================
184 /*!
185  *Here we are going to use the NETGEN mesher
186  */
187 //=============================================================================
188
189 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
190                                      const TopoDS_Shape& aShape)
191 {
192   netgen::multithread.terminate = 0;
193   netgen::multithread.task = "Volume meshing";
194   _progressByTic = -1.;
195
196   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
197
198   SMESH_MesherHelper helper(aMesh);
199   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
200   helper.SetElementsOnShape( true );
201
202   int Netgen_NbOfNodes = 0;
203   double Netgen_point[3];
204   int Netgen_triangle[3];
205
206   NETGENPlugin_NetgenLibWrapper ngLib;
207   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
208
209   // vector of nodes in which node index == netgen ID
210   vector< const SMDS_MeshNode* > nodeVec;
211   {
212     const int invalid_ID = -1;
213
214     SMESH::Controls::Area areaControl;
215     SMESH::Controls::TSequenceOfXYZ nodesCoords;
216
217     // maps nodes to ng ID
218     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
219     typedef TNodeToIDMap::value_type                     TN2ID;
220     TNodeToIDMap nodeToNetgenID;
221
222     // find internal shapes
223     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
224
225     // ---------------------------------
226     // Feed the Netgen with surface mesh
227     // ---------------------------------
228
229     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
230     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
231
232     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
233     if ( _viscousLayersHyp )
234     {
235       netgen::multithread.percent = 3;
236       proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
237       if ( !proxyMesh )
238         return false;
239     }
240     if ( aMesh.NbQuadrangles() > 0 )
241     {
242       netgen::multithread.percent = 6;
243       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
244       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
245       proxyMesh.reset( Adaptor );
246     }
247
248     for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
249     {
250       const TopoDS_Shape& aShapeFace = exFa.Current();
251       int faceID = meshDS->ShapeToIndex( aShapeFace );
252       bool isInternalFace = internals.isInternalShape( faceID );
253       bool isRev = false;
254       if ( checkReverse && !isInternalFace &&
255            helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
256         // IsReversedSubMesh() can work wrong on strongly curved faces,
257         // so we use it as less as possible
258         isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
259
260       const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
261       if ( !aSubMeshDSFace ) continue;
262       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
263       while ( iteratorElem->more() ) // loop on elements on a geom face
264       {
265         // check mesh face
266         const SMDS_MeshElement* elem = iteratorElem->next();
267         if ( !elem )
268           return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
269         if ( elem->NbCornerNodes() != 3 )
270           return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
271
272         // Add nodes of triangles and triangles them-selves to netgen mesh
273
274         // add three nodes of triangle
275         bool hasDegen = false;
276         for ( int iN = 0; iN < 3; ++iN )
277         {
278           const SMDS_MeshNode* node = elem->GetNode( iN );
279           const int shapeID = node->getshapeId();
280           if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
281                helper.IsDegenShape( shapeID ))
282           {
283             // ignore all nodes on degeneraged edge and use node on its vertex instead
284             TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
285             node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
286             hasDegen = true;
287           }
288           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
289           if ( ngID == invalid_ID )
290           {
291             ngID = ++Netgen_NbOfNodes;
292             Netgen_point [ 0 ] = node->X();
293             Netgen_point [ 1 ] = node->Y();
294             Netgen_point [ 2 ] = node->Z();
295             Ng_AddPoint(Netgen_mesh, Netgen_point);
296           }
297           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
298         }
299         // add triangle
300         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
301                           Netgen_triangle[0] == Netgen_triangle[2] ||
302                           Netgen_triangle[2] == Netgen_triangle[1] ))
303           continue;
304
305         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
306
307         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
308         {
309           swap( Netgen_triangle[1], Netgen_triangle[2] );
310           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
311         }
312       } // loop on elements on a face
313     } // loop on faces of a SOLID or SHELL
314
315     // insert old nodes into nodeVec
316     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
317     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
318     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
319       nodeVec[ n_id->second ] = n_id->first;
320     nodeToNetgenID.clear();
321
322     if ( internals.hasInternalVertexInSolid() )
323     {
324       netgen::OCCGeometry occgeo;
325       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
326                                                    (netgen::Mesh&) *Netgen_mesh,
327                                                    nodeVec,
328                                                    internals);
329     }
330   }
331
332   // -------------------------
333   // Generate the volume mesh
334   // -------------------------
335
336   return ( ngLib._isComputeOk = compute( aMesh, helper, nodeVec, Netgen_mesh));
337 }
338
339 namespace
340 {
341   void limitVolumeSize( netgen::Mesh* ngMesh,
342                         double        maxh )
343   {
344     // get average h of faces
345     double faceh = 0;
346     int nbh = 0;
347     for (int i = 1; i <= ngMesh->GetNSE(); i++)
348     {
349       const netgen::Element2d& face = ngMesh->SurfaceElement(i);
350       for (int j=1; j <= face.GetNP(); ++j)
351       {
352         const netgen::PointIndex & i1 = face.PNumMod(j);
353         const netgen::PointIndex & i2 = face.PNumMod(j+1);
354         if ( i1 < i2 )
355         {
356           const netgen::Point3d & p1 = ngMesh->Point( i1 );
357           const netgen::Point3d & p2 = ngMesh->Point( i2 );
358           faceh += netgen::Dist2( p1, p2 );
359           nbh++;
360         }
361       }
362     }
363     faceh = Sqrt( faceh / nbh );
364
365     double compareh;
366     if      ( faceh < 0.5 * maxh ) compareh = -1;
367     else if ( faceh > 1.5 * maxh ) compareh = 1;
368     else                           compareh = 0;
369     // cerr << "faceh " << faceh << endl;
370     // cerr << "init maxh " << maxh << endl;
371     // cerr << "compareh " << compareh << endl;
372
373     if ( compareh > 0 )
374       maxh *= 1.2;
375     else
376       maxh *= 0.8;
377     // cerr << "maxh " << maxh << endl;
378
379     // get bnd box
380     netgen::Point3d pmin, pmax;
381     ngMesh->GetBox( pmin, pmax, 0 );
382     const double dx = pmax.X() - pmin.X();
383     const double dy = pmax.Y() - pmin.Y();
384     const double dz = pmax.Z() - pmin.Z();
385
386     if ( ! & ngMesh->LocalHFunction() )
387       ngMesh->SetLocalH( pmin, pmax, compareh <= 0 ? 0.1 : 0.5 );
388
389     // adjusted by SALOME_TESTS/Grids/smesh/bugs_08/I8
390     const int nbX = Max( 2, int( dx / maxh * 2 ));
391     const int nbY = Max( 2, int( dy / maxh * 2 ));
392     const int nbZ = Max( 2, int( dz / maxh * 2 ));
393
394     netgen::Point3d p;
395     for ( int i = 0; i <= nbX; ++i )
396     {
397       p.X() = pmin.X() +  i * dx / nbX;
398       for ( int j = 0; j <= nbY; ++j )
399       {
400         p.Y() = pmin.Y() +  j * dy / nbY;
401         for ( int k = 0; k <= nbZ; ++k )
402         {
403           p.Z() = pmin.Z() +  k * dz / nbZ;
404           ngMesh->RestrictLocalH( p, maxh );
405         }
406       }
407     }
408   }
409 }
410
411 //================================================================================
412 /*!
413  * \brief set parameters and generate the volume mesh
414  */
415 //================================================================================
416
417 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
418                                      SMESH_MesherHelper&             helper,
419                                      vector< const SMDS_MeshNode* >& nodeVec,
420                                      Ng_Mesh *                       Netgen_mesh)
421 {
422   netgen::multithread.terminate = 0;
423
424   netgen::Mesh* ngMesh = (netgen::Mesh*)Netgen_mesh;
425   int Netgen_NbOfNodes = Ng_GetNP(Netgen_mesh);
426
427 #ifndef NETGEN_V5
428   char *optstr = 0;
429 #endif
430   int startWith = netgen::MESHCONST_MESHVOLUME;
431   int endWith   = netgen::MESHCONST_OPTVOLUME;
432   int err = 1;
433
434   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
435   netgen::OCCGeometry occgeo;
436   
437   if ( _hypParameters )
438   {
439     aMesher.SetParameters( _hypParameters );
440     if ( !_hypParameters->GetOptimize() )
441       endWith = netgen::MESHCONST_MESHVOLUME;
442   }
443   else if ( _hypMaxElementVolume )
444   {
445     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
446     // limitVolumeSize( ngMesh, netgen::mparam.maxh ); // result is unpredictable
447   }
448   else if ( aMesh.HasShapeToMesh() )
449   {
450     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
451     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
452   }
453   else
454   {
455     netgen::Point3d pmin, pmax;
456     ngMesh->GetBox (pmin, pmax);
457     netgen::mparam.maxh = Dist(pmin, pmax)/2;
458   }
459
460   if ( !_hypParameters && aMesh.HasShapeToMesh() )
461   {
462     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
463   }
464
465   try
466   {
467     OCC_CATCH_SIGNALS;
468
469 #ifdef NETGEN_V5
470     ngMesh->CalcLocalH(netgen::mparam.grading);
471     err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
472 #else
473     ngMesh->CalcLocalH();
474     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
475 #endif
476     if(netgen::multithread.terminate)
477       return false;
478     if ( err )
479       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
480   }
481   catch (Standard_Failure& ex)
482   {
483     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
484     str << " at " << netgen::multithread.task
485         << ": " << ex.DynamicType()->Name();
486     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
487       str << ": " << ex.GetMessageString();
488     error(str);
489   }
490   catch (netgen::NgException exc)
491   {
492     SMESH_Comment str("NgException");
493     if ( strlen( netgen::multithread.task ) > 0 )
494       str << " at " << netgen::multithread.task;
495     str << ": " << exc.What();
496     error(str);
497   }
498   catch (...)
499   {
500     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
501     if ( strlen( netgen::multithread.task ) > 0 )
502       str << " at " << netgen::multithread.task;
503     error(str);
504   }
505
506   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
507   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
508
509   MESSAGE("End of Volume Mesh Generation. err=" << err <<
510           ", nb new nodes: " << Netgen_NbOfNodesNew - Netgen_NbOfNodes <<
511           ", nb tetra: " << Netgen_NbOfTetra);
512
513   // -------------------------------------------------------------------
514   // Feed back the SMESHDS with the generated Nodes and Volume Elements
515   // -------------------------------------------------------------------
516
517   if ( err )
518   {
519     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
520     if ( ce && !ce->myBadElements.empty() )
521       error( ce );
522   }
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
556   return !err;
557 }
558
559 //================================================================================
560 /*!
561  * \brief Compute tetrahedral mesh from 2D mesh without geometry
562  */
563 //================================================================================
564
565 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
566                                      SMESH_MesherHelper* aHelper)
567 {
568   const int invalid_ID = -1;
569
570   netgen::multithread.terminate = 0;
571   _progressByTic = -1.;
572
573   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
574   if ( MeshType == SMESH_MesherHelper::COMP )
575     return error( COMPERR_BAD_INPUT_MESH,
576                   SMESH_Comment("Mesh with linear and quadratic elements given"));
577
578   aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
579
580   // ---------------------------------
581   // Feed the Netgen with surface mesh
582   // ---------------------------------
583
584   int Netgen_NbOfNodes = 0;
585   double Netgen_point[3];
586   int Netgen_triangle[3];
587
588   NETGENPlugin_NetgenLibWrapper ngLib;
589   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
590
591   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
592   if ( aMesh.NbQuadrangles() > 0 )
593   {
594     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
595     Adaptor->Compute(aMesh);
596     proxyMesh.reset( Adaptor );
597   }
598
599   // maps nodes to ng ID
600   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
601   typedef TNodeToIDMap::value_type                     TN2ID;
602   TNodeToIDMap nodeToNetgenID;
603
604   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
605   while( fIt->more())
606   {
607     // check element
608     const SMDS_MeshElement* elem = fIt->next();
609     if ( !elem )
610       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
611     if ( elem->NbCornerNodes() != 3 )
612       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
613       
614     // add three nodes of triangle
615     for ( int iN = 0; iN < 3; ++iN )
616     {
617       const SMDS_MeshNode* node = elem->GetNode( iN );
618       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
619       if ( ngID == invalid_ID )
620       {
621         ngID = ++Netgen_NbOfNodes;
622         Netgen_point [ 0 ] = node->X();
623         Netgen_point [ 1 ] = node->Y();
624         Netgen_point [ 2 ] = node->Z();
625         Ng_AddPoint(Netgen_mesh, Netgen_point);
626       }
627       Netgen_triangle[ iN ] = ngID;
628     }
629     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
630   }
631   proxyMesh.reset(); // delete tmp faces
632
633   // vector of nodes in which node index == netgen ID
634   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
635   // insert old nodes into nodeVec
636   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
637   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
638     nodeVec.at( n_id->second ) = n_id->first;
639   nodeToNetgenID.clear();
640
641   // -------------------------
642   // Generate the volume mesh
643   // -------------------------
644
645   return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, Netgen_mesh));
646 }
647
648 void NETGENPlugin_NETGEN_3D::CancelCompute()
649 {
650   SMESH_Algo::CancelCompute();
651   netgen::multithread.terminate = 1;
652 }
653
654 //================================================================================
655 /*!
656  * \brief Return Compute progress
657  */
658 //================================================================================
659
660 double NETGENPlugin_NETGEN_3D::GetProgress() const
661 {
662   double res;
663   const char* volMeshing = "Volume meshing";
664   const char* dlnMeshing = "Delaunay meshing";
665   const double meshingRatio = 0.15;
666   const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
667
668   if ( _progressByTic < 0. &&
669        ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
670          strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
671   {
672     res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
673     //cout << netgen::multithread.task << " " <<_progressTic << "-" << netgen::multithread.percent << endl;
674   }
675   else // different otimizations
676   {
677     if ( _progressByTic < 0. )
678       ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
679     res = _progressByTic * _progressTic;
680     //cout << netgen::multithread.task << " " << _progressTic << " " << res << endl;
681   }
682   return Min ( res, 0.98 );
683 }
684
685 //=============================================================================
686 /*!
687  *
688  */
689 //=============================================================================
690
691 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
692                                       const TopoDS_Shape& aShape,
693                                       MapShapeNbElems& aResMap)
694 {
695   int nbtri = 0, nbqua = 0;
696   double fullArea = 0.0;
697   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
698     TopoDS_Face F = TopoDS::Face( expF.Current() );
699     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
700     MapShapeNbElemsItr anIt = aResMap.find(sm);
701     if( anIt==aResMap.end() ) {
702       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
703       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
704       return false;
705     }
706     std::vector<int> aVec = (*anIt).second;
707     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
708     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
709     GProp_GProps G;
710     BRepGProp::SurfaceProperties(F,G);
711     double anArea = G.Mass();
712     fullArea += anArea;
713   }
714
715   // collect info from edges
716   int nb0d_e = 0, nb1d_e = 0;
717   bool IsQuadratic = false;
718   bool IsFirst = true;
719   TopTools_MapOfShape tmpMap;
720   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
721     TopoDS_Edge E = TopoDS::Edge(expF.Current());
722     if( tmpMap.Contains(E) )
723       continue;
724     tmpMap.Add(E);
725     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
726     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
727     if( anIt==aResMap.end() ) {
728       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
729       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
730                                             "Submesh can not be evaluated",this));
731       return false;
732     }
733     std::vector<int> aVec = (*anIt).second;
734     nb0d_e += aVec[SMDSEntity_Node];
735     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
736     if(IsFirst) {
737       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
738       IsFirst = false;
739     }
740   }
741   tmpMap.Clear();
742
743   double ELen_face = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
744   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
745   double ELen = Min(ELen_vol,ELen_face*2);
746
747   GProp_GProps G;
748   BRepGProp::VolumeProperties(aShape,G);
749   double aVolume = G.Mass();
750   double tetrVol = 0.1179*ELen*ELen*ELen;
751   double CoeffQuality = 0.9;
752   int nbVols = int( aVolume/tetrVol/CoeffQuality );
753   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
754   int nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
755   std::vector<int> aVec(SMDSEntity_Last);
756   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
757   if( IsQuadratic ) {
758     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
759     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
760     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
761   }
762   else {
763     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
764     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
765     aVec[SMDSEntity_Pyramid] = nbqua;
766   }
767   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
768   aResMap.insert(std::make_pair(sm,aVec));
769   
770   return true;
771 }
772
773