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