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