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