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