Salome HOME
Merge from V6_main 01/04/2013
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D.cxx
1 // Copyright (C) 2007-2013  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.
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   list<const SMESHDS_Hypothesis*>::const_iterator itl;
144   const SMESHDS_Hypothesis* theHyp;
145
146   const list<const SMESHDS_Hypothesis*>& hyps =
147     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
148   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
149   if ( h == hyps.end())
150   {
151     aStatus = SMESH_Hypothesis::HYP_OK;
152     return true;  // can work with no hypothesis
153   }
154
155   aStatus = HYP_OK;
156   for ( ; h != hyps.end(); ++h )
157   {
158     if ( !_hypMaxElementVolume )
159       _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
160     if ( !_viscousLayersHyp )
161       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
162     if ( ! _hypParameters )
163       _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
164
165     if ( *h != _hypMaxElementVolume &&
166          *h != _viscousLayersHyp &&
167          *h != _hypParameters)
168       aStatus = HYP_INCOMPATIBLE;
169   }
170   if ( _hypMaxElementVolume && _hypParameters )
171     aStatus = HYP_INCOMPATIBLE;
172
173   if ( _hypMaxElementVolume )
174     _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
175
176   return aStatus == HYP_OK;
177 }
178
179 //=============================================================================
180 /*!
181  *Here we are going to use the NETGEN mesher
182  */
183 //=============================================================================
184
185 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
186                                      const TopoDS_Shape& aShape)
187 {
188 #ifdef WITH_SMESH_CANCEL_COMPUTE
189   netgen::multithread.terminate = 0;
190 #endif
191   MESSAGE("NETGENPlugin_NETGEN_3D::Compute with maxElmentsize = " << _maxElementVolume);
192
193   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
194
195   SMESH_MesherHelper helper(aMesh);
196   bool _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
197   helper.SetElementsOnShape( true );
198
199   int Netgen_NbOfNodes     = 0;
200
201   double Netgen_point[3];
202   int Netgen_triangle[3];
203
204   NETGENPlugin_NetgenLibWrapper ngLib;
205   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
206
207   // vector of nodes in which node index == netgen ID
208   vector< const SMDS_MeshNode* > nodeVec;
209   {
210     const int invalid_ID = -1;
211
212     SMESH::Controls::Area areaControl;
213     SMESH::Controls::TSequenceOfXYZ nodesCoords;
214
215     // maps nodes to ng ID
216     typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
217     typedef TNodeToIDMap::value_type                     TN2ID;
218     TNodeToIDMap nodeToNetgenID;
219
220     // find internal shapes
221     NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
222
223     // ---------------------------------
224     // Feed the Netgen with surface mesh
225     // ---------------------------------
226
227     TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
228     bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
229
230     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
231     if ( _viscousLayersHyp )
232     {
233       proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
234       if ( !proxyMesh )
235         return false;
236     }
237     if ( aMesh.NbQuadrangles() > 0 )
238     {
239       StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
240       Adaptor->Compute(aMesh,aShape,proxyMesh.get());
241       proxyMesh.reset( Adaptor );
242     }
243
244     for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
245     {
246       const TopoDS_Shape& aShapeFace = exFa.Current();
247       int faceID = meshDS->ShapeToIndex( aShapeFace );
248       bool isInternalFace = internals.isInternalShape( faceID );
249       bool isRev = false;
250       if ( checkReverse && !isInternalFace &&
251            helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
252         // IsReversedSubMesh() can work wrong on strongly curved faces,
253         // so we use it as less as possible
254         isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
255
256       const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
257       if ( !aSubMeshDSFace ) continue;
258       SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
259       while ( iteratorElem->more() ) // loop on elements on a geom face
260       {
261         // check mesh face
262         const SMDS_MeshElement* elem = iteratorElem->next();
263         if ( !elem )
264           return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
265         if ( elem->NbCornerNodes() != 3 )
266           return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
267
268         // Add nodes of triangles and triangles them-selves to netgen mesh
269
270         // add three nodes of triangle
271         bool hasDegen = false;
272         for ( int iN = 0; iN < 3; ++iN )
273         {
274           const SMDS_MeshNode* node = elem->GetNode( iN );
275           const int shapeID = node->getshapeId();
276           if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
277                helper.IsDegenShape( shapeID ))
278           {
279             // ignore all nodes on degeneraged edge and use node on its vertex instead
280             TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
281             node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
282             hasDegen = true;
283           }
284           int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
285           if ( ngID == invalid_ID )
286           {
287             ngID = ++Netgen_NbOfNodes;
288             Netgen_point [ 0 ] = node->X();
289             Netgen_point [ 1 ] = node->Y();
290             Netgen_point [ 2 ] = node->Z();
291             Ng_AddPoint(Netgen_mesh, Netgen_point);
292           }
293           Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
294         }
295         // add triangle
296         if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
297                           Netgen_triangle[0] == Netgen_triangle[2] ||
298                           Netgen_triangle[2] == Netgen_triangle[1] ))
299           continue;
300
301         Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
302
303         if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
304         {
305           swap( Netgen_triangle[1], Netgen_triangle[2] );
306           Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
307         }
308       } // loop on elements on a face
309     } // loop on faces of a SOLID or SHELL
310
311     // insert old nodes into nodeVec
312     nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
313     TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
314     for ( ; n_id != nodeToNetgenID.end(); ++n_id )
315       nodeVec[ n_id->second ] = n_id->first;
316     nodeToNetgenID.clear();
317
318     if ( internals.hasInternalVertexInSolid() )
319     {
320       netgen::OCCGeometry occgeo;
321       NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
322                                                    (netgen::Mesh&) *Netgen_mesh,
323                                                    nodeVec,
324                                                    internals);
325     }
326   }
327
328   // -------------------------
329   // Generate the volume mesh
330   // -------------------------
331
332   return compute( aMesh, helper, nodeVec, Netgen_mesh);
333 }
334
335 //================================================================================
336 /*!
337  * \brief set parameters and generate the volume mesh
338  */
339 //================================================================================
340
341 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh&                     aMesh,
342                                      SMESH_MesherHelper&             helper,
343                                      vector< const SMDS_MeshNode* >& nodeVec,
344                                      Ng_Mesh *                       Netgen_mesh)
345 {
346 #ifdef WITH_SMESH_CANCEL_COMPUTE
347   netgen::multithread.terminate = 0;
348 #endif
349   netgen::Mesh* ngMesh = (netgen::Mesh*)Netgen_mesh;
350   int Netgen_NbOfNodes = Ng_GetNP(Netgen_mesh);
351
352 #ifndef NETGEN_V5
353   char *optstr = 0;
354 #endif
355   int startWith = netgen::MESHCONST_MESHVOLUME;
356   int endWith   = netgen::MESHCONST_OPTVOLUME;
357   int err = 1;
358
359   NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
360   netgen::OCCGeometry occgeo;
361   
362   if ( _hypParameters )
363   {
364     aMesher.SetParameters( _hypParameters );
365     if ( !_hypParameters->GetOptimize() )
366       endWith = netgen::MESHCONST_MESHVOLUME;
367   }
368   else if ( _hypMaxElementVolume )
369   {
370     netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
371   }
372   else if ( aMesh.HasShapeToMesh() )
373   {
374     aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
375     netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
376   }
377   else
378   {
379     netgen::Point3d pmin, pmax;
380     ngMesh->GetBox (pmin, pmax);
381     netgen::mparam.maxh = Dist(pmin, pmax)/2;
382   }
383
384   if ( !_hypParameters && aMesh.HasShapeToMesh() )
385   {
386     netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
387   }
388
389   try
390   {
391 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
392     OCC_CATCH_SIGNALS;
393 #endif
394 #ifdef NETGEN_V5
395     ngMesh->CalcLocalH(netgen::mparam.grading);
396     err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
397 #else
398     ngMesh->CalcLocalH();
399     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
400 #endif
401 #ifdef WITH_SMESH_CANCEL_COMPUTE
402     if(netgen::multithread.terminate)
403       return false;
404 #endif
405     if ( err )
406       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
407   }
408   catch (Standard_Failure& ex)
409   {
410     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
411     str << " at " << netgen::multithread.task
412         << ": " << ex.DynamicType()->Name();
413     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
414       str << ": " << ex.GetMessageString();
415     error(str);
416   }
417   catch (netgen::NgException exc)
418   {
419     SMESH_Comment str("NgException");
420     if ( strlen( netgen::multithread.task ) > 0 )
421       str << " at " << netgen::multithread.task;
422     str << ": " << exc.What();
423     error(str);
424   }
425   catch (...)
426   {
427     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
428     if ( strlen( netgen::multithread.task ) > 0 )
429       str << " at " << netgen::multithread.task;
430     error(str);
431   }
432
433   int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
434   int Netgen_NbOfTetra    = Ng_GetNE(Netgen_mesh);
435
436   MESSAGE("End of Volume Mesh Generation. err=" << err <<
437           ", nb new nodes: " << Netgen_NbOfNodesNew - Netgen_NbOfNodes <<
438           ", nb tetra: " << Netgen_NbOfTetra);
439
440   // -------------------------------------------------------------------
441   // Feed back the SMESHDS with the generated Nodes and Volume Elements
442   // -------------------------------------------------------------------
443
444   if ( err )
445   {
446     SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
447     if ( ce && !ce->myBadElements.empty() )
448       error( ce );
449   }
450
451   bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
452   if ( isOK )
453   {
454     double Netgen_point[3];
455     int    Netgen_tetrahedron[4];
456
457     // create and insert new nodes into nodeVec
458     nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
459     int nodeIndex = Netgen_NbOfNodes + 1;
460     for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
461     {
462       Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
463       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
464     }
465
466     // create tetrahedrons
467     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
468     {
469       Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
470       try
471       {
472         helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
473                           nodeVec.at( Netgen_tetrahedron[1] ),
474                           nodeVec.at( Netgen_tetrahedron[2] ),
475                           nodeVec.at( Netgen_tetrahedron[3] ));
476       }
477       catch (...)
478       {
479       }
480     }
481   }
482
483   return !err;
484 }
485
486 //================================================================================
487 /*!
488  * \brief Compute tetrahedral mesh from 2D mesh without geometry
489  */
490 //================================================================================
491
492 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh&         aMesh,
493                                      SMESH_MesherHelper* aHelper)
494 {
495   MESSAGE("NETGENPlugin_NETGEN_3D::Compute with maxElmentsize = " << _maxElementVolume);  
496   const int invalid_ID = -1;
497   bool _quadraticMesh = false;
498
499   SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
500
501   if(MeshType == SMESH_MesherHelper::COMP)
502     return error( COMPERR_BAD_INPUT_MESH,
503                   SMESH_Comment("Mesh with linear and quadratic elements given."));
504   else if (MeshType == SMESH_MesherHelper::QUADRATIC)
505     _quadraticMesh = true;
506
507   // ---------------------------------
508   // Feed the Netgen with surface mesh
509   // ---------------------------------
510
511   int Netgen_NbOfNodes = 0;
512   int Netgen_param2ndOrder = 0;
513   double Netgen_paramFine = 1.;
514   double Netgen_paramSize = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
515   
516   double Netgen_point[3];
517   int Netgen_triangle[3];
518   int Netgen_tetrahedron[4];
519
520   NETGENPlugin_NetgenLibWrapper ngLib;
521   Ng_Mesh * Netgen_mesh = ngLib._ngMesh;
522
523   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
524   if ( aMesh.NbQuadrangles() > 0 )
525   {
526     StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
527     Adaptor->Compute(aMesh);
528     proxyMesh.reset( Adaptor );
529   }
530
531   // maps nodes to ng ID
532   typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
533   typedef TNodeToIDMap::value_type                     TN2ID;
534   TNodeToIDMap nodeToNetgenID;
535
536   SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
537   while( fIt->more())
538   {
539     // check element
540     const SMDS_MeshElement* elem = fIt->next();
541     if ( !elem )
542       return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
543     if ( elem->NbCornerNodes() != 3 )
544       return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
545       
546     // add three nodes of triangle
547     for ( int iN = 0; iN < 3; ++iN )
548     {
549       const SMDS_MeshNode* node = elem->GetNode( iN );
550       int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
551       if ( ngID == invalid_ID )
552       {
553         ngID = ++Netgen_NbOfNodes;
554         Netgen_point [ 0 ] = node->X();
555         Netgen_point [ 1 ] = node->Y();
556         Netgen_point [ 2 ] = node->Z();
557         Ng_AddPoint(Netgen_mesh, Netgen_point);
558       }
559       Netgen_triangle[ iN ] = ngID;
560     }
561     Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
562   }
563   proxyMesh.reset(); // delete tmp faces
564
565   // vector of nodes in which node index == netgen ID
566   vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
567   // insert old nodes into nodeVec
568   TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
569   for ( ; n_id != nodeToNetgenID.end(); ++n_id )
570     nodeVec.at( n_id->second ) = n_id->first;
571   nodeToNetgenID.clear();
572
573   // -------------------------
574   // Generate the volume mesh
575   // -------------------------
576
577   return compute( aMesh, *aHelper, nodeVec, Netgen_mesh);
578 }
579
580 #ifdef WITH_SMESH_CANCEL_COMPUTE
581 void NETGENPlugin_NETGEN_3D::CancelCompute()
582 {
583   SMESH_Algo::CancelCompute();
584   netgen::multithread.terminate = 1;
585 }
586 #endif
587
588 //=============================================================================
589 /*!
590  *
591  */
592 //=============================================================================
593
594 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
595                                       const TopoDS_Shape& aShape,
596                                       MapShapeNbElems& aResMap)
597 {
598   int nbtri = 0, nbqua = 0;
599   double fullArea = 0.0;
600   for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
601     TopoDS_Face F = TopoDS::Face( expF.Current() );
602     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
603     MapShapeNbElemsItr anIt = aResMap.find(sm);
604     if( anIt==aResMap.end() ) {
605       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
606       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
607       return false;
608     }
609     std::vector<int> aVec = (*anIt).second;
610     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
611     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
612     GProp_GProps G;
613     BRepGProp::SurfaceProperties(F,G);
614     double anArea = G.Mass();
615     fullArea += anArea;
616   }
617
618   // collect info from edges
619   int nb0d_e = 0, nb1d_e = 0;
620   bool IsQuadratic = false;
621   bool IsFirst = true;
622   TopTools_MapOfShape tmpMap;
623   for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
624     TopoDS_Edge E = TopoDS::Edge(expF.Current());
625     if( tmpMap.Contains(E) )
626       continue;
627     tmpMap.Add(E);
628     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
629     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
630     if( anIt==aResMap.end() ) {
631       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
632       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
633                                             "Submesh can not be evaluated",this));
634       return false;
635     }
636     std::vector<int> aVec = (*anIt).second;
637     nb0d_e += aVec[SMDSEntity_Node];
638     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
639     if(IsFirst) {
640       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
641       IsFirst = false;
642     }
643   }
644   tmpMap.Clear();
645
646   double ELen_face = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
647   double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
648   double ELen = Min(ELen_vol,ELen_face*2);
649
650   GProp_GProps G;
651   BRepGProp::VolumeProperties(aShape,G);
652   double aVolume = G.Mass();
653   double tetrVol = 0.1179*ELen*ELen*ELen;
654   double CoeffQuality = 0.9;
655   int nbVols = int( aVolume/tetrVol/CoeffQuality );
656   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
657   int nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
658   std::vector<int> aVec(SMDSEntity_Last);
659   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
660   if( IsQuadratic ) {
661     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
662     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
663     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
664   }
665   else {
666     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
667     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
668     aVec[SMDSEntity_Pyramid] = nbqua;
669   }
670   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
671   aResMap.insert(std::make_pair(sm,aVec));
672   
673   return true;
674 }
675
676