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