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