Salome HOME
3ef94f640eba9a7fba8fbdb64d36af90a9950ae5
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  NETGENPlugin : C++ implementation
24 // File      : NETGENPlugin_Mesher.cxx
25 // Author    : Michael Sazonov (OCN)
26 // Date      : 31/03/2006
27 // Project   : SALOME
28 //=============================================================================
29
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
33
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_MeshElement.hxx>
36 #include <SMDS_MeshNode.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Block.hxx>
39 #include <SMESH_Comment.hxx>
40 #include <SMESH_ComputeError.hxx>
41 #include <SMESH_File.hxx>
42 #include <SMESH_Gen_i.hxx>
43 #include <SMESH_Mesh.hxx>
44 #include <SMESH_MesherHelper.hxx>
45 #include <SMESH_subMesh.hxx>
46 #include <StdMeshers_QuadToTriaAdaptor.hxx>
47 #include <StdMeshers_ViscousLayers2D.hxx>
48
49 #include <SALOMEDS_Tool.hxx>
50
51 #include <utilities.h>
52
53 #include <BRepBuilderAPI_Copy.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Bnd_B3d.hxx>
56 #include <NCollection_Map.hxx>
57 #include <Standard_ErrorHandler.hxx>
58 #include <Standard_ProgramError.hxx>
59 #include <TopExp.hxx>
60 #include <TopExp_Explorer.hxx>
61 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
63 #include <TopTools_DataMapOfShapeInteger.hxx>
64 #include <TopTools_DataMapOfShapeShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
66 #include <TopoDS.hxx>
67 #include <OSD_File.hxx>
68 #include <OSD_Path.hxx>
69
70 // Netgen include files
71 #ifndef OCCGEOMETRY
72 #define OCCGEOMETRY
73 #endif
74 #include <occgeom.hpp>
75 #include <meshing.hpp>
76 //#include <ngexception.hpp>
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 void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
84   extern MeshingParameters mparam;
85   extern volatile multithreadt multithread;
86   extern bool merge_solids;
87 }
88
89 #include <vector>
90 #include <limits>
91
92 #ifdef WIN32
93 #include <process.h>
94 #endif
95 using namespace nglib;
96 using namespace std;
97
98 #ifdef _DEBUG_
99 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
100 #else
101 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
102 #endif
103
104 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
105
106 #ifdef _DEBUG_
107 // dump elements added to ng mesh
108 //#define DUMP_SEGMENTS
109 //#define DUMP_TRIANGLES
110 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
111 #endif
112
113 TopTools_IndexedMapOfShape ShapesWithLocalSize;
114 std::map<int,double> VertexId2LocalSize;
115 std::map<int,double> EdgeId2LocalSize;
116 std::map<int,double> FaceId2LocalSize;
117
118 //=============================================================================
119 /*!
120  *
121  */
122 //=============================================================================
123
124 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
125                                           const TopoDS_Shape& aShape,
126                                           const bool          isVolume)
127   : _mesh    (mesh),
128     _shape   (aShape),
129     _isVolume(isVolume),
130     _optimize(true),
131     _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
132     _isViscousLayers2D(false),
133     _ngMesh(NULL),
134     _occgeom(NULL),
135     _curShapeIndex(-1),
136     _progressTic(1),
137     _totalTime(1.0),
138     _simpleHyp(NULL),
139     _ptrToMe(NULL)
140 {
141   SetDefaultParameters();
142   ShapesWithLocalSize.Clear();
143   VertexId2LocalSize.clear();
144   EdgeId2LocalSize.clear();
145   FaceId2LocalSize.clear();
146 }
147
148 //================================================================================
149 /*!
150  * Destuctor
151  */
152 //================================================================================
153
154 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
155 {
156   if ( _ptrToMe )
157     *_ptrToMe = NULL;
158   _ptrToMe = 0;
159   _ngMesh = NULL;
160 }
161
162 //================================================================================
163 /*!
164  * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
165  * nullified at destruction of this
166  */
167 //================================================================================
168
169 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
170 {
171   if ( _ptrToMe )
172     *_ptrToMe = NULL;
173
174   _ptrToMe = ptr;
175
176   if ( _ptrToMe )
177     *_ptrToMe = this;
178 }
179
180 //================================================================================
181 /*!
182  * \brief Initialize global NETGEN parameters with default values
183  */
184 //================================================================================
185
186 void NETGENPlugin_Mesher::SetDefaultParameters()
187 {
188   netgen::MeshingParameters& mparams = netgen::mparam;
189   // maximal mesh edge size
190   mparams.maxh            = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
191   mparams.minh            = 0;
192   // minimal number of segments per edge
193   mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
194   // rate of growth of size between elements
195   mparams.grading         = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
196   // safety factor for curvatures (elements per radius)
197   mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
198   // create elements of second order
199   mparams.secondorder     = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
200   // quad-dominated surface meshing
201   if (_isVolume)
202     mparams.quad          = 0;
203   else
204     mparams.quad          = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
205   _fineness               = NETGENPlugin_Hypothesis::GetDefaultFineness();
206   mparams.uselocalh       = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
207   netgen::merge_solids    = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
208 }
209
210 //=============================================================================
211 /*!
212  *
213  */
214 //=============================================================================
215
216 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
217 {
218   if ( GeomShape.IsNull() ) return;
219   TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
220   if (GeomType == TopAbs_COMPOUND) {
221     for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
222       SetLocalSize(it.Value(), LocalSize);
223     }
224     return;
225   }
226   int key;
227   if (! ShapesWithLocalSize.Contains(GeomShape))
228     key = ShapesWithLocalSize.Add(GeomShape);
229   else
230     key = ShapesWithLocalSize.FindIndex(GeomShape);
231   if (GeomType == TopAbs_VERTEX) {
232     VertexId2LocalSize[key] = LocalSize;
233   } else if (GeomType == TopAbs_EDGE) {
234     EdgeId2LocalSize[key] = LocalSize;
235   } else if (GeomType == TopAbs_FACE) {
236     FaceId2LocalSize[key] = LocalSize;
237   }
238 }
239
240 //=============================================================================
241 /*!
242  * Pass parameters to NETGEN
243  */
244 //=============================================================================
245 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
246 {
247   if (hyp)
248   {
249     netgen::MeshingParameters& mparams = netgen::mparam;
250     // Initialize global NETGEN parameters:
251     // maximal mesh segment size
252     mparams.maxh            = hyp->GetMaxSize();
253     // maximal mesh element linear size
254     mparams.minh            = hyp->GetMinSize();
255     // minimal number of segments per edge
256     mparams.segmentsperedge = hyp->GetNbSegPerEdge();
257     // rate of growth of size between elements
258     mparams.grading         = hyp->GetGrowthRate();
259     // safety factor for curvatures (elements per radius)
260     mparams.curvaturesafety = hyp->GetNbSegPerRadius();
261     // create elements of second order
262     mparams.secondorder     = hyp->GetSecondOrder() ? 1 : 0;
263     // quad-dominated surface meshing
264     // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
265     //if (!_isVolume)
266       mparams.quad          = hyp->GetQuadAllowed() ? 1 : 0;
267     _optimize               = hyp->GetOptimize();
268     _fineness               = hyp->GetFineness();
269     mparams.uselocalh       = hyp->GetSurfaceCurvature();
270     netgen::merge_solids    = hyp->GetFuseEdges();
271     _simpleHyp = NULL;
272
273     SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
274     CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
275     SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
276     SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
277     
278     const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
279     NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
280     for (it ; it != localSizes.end() ; it++)
281       {
282         std::string entry = (*it).first;
283         double val = (*it).second;
284         // --
285         GEOM::GEOM_Object_var aGeomObj;
286         TopoDS_Shape S = TopoDS_Shape();
287         SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
288         if (!aSObj->_is_nil()) {
289           CORBA::Object_var obj = aSObj->GetObject();
290           aGeomObj = GEOM::GEOM_Object::_narrow(obj);
291           aSObj->UnRegister();
292         }
293         if ( !aGeomObj->_is_nil() )
294           S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
295         // --
296         SetLocalSize(S, val);
297       }
298   }
299 }
300
301 //=============================================================================
302 /*!
303  * Pass simple parameters to NETGEN
304  */
305 //=============================================================================
306
307 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
308 {
309   _simpleHyp = hyp;
310   if ( _simpleHyp )
311     SetDefaultParameters();
312 }
313
314 //=============================================================================
315 /*!
316  *  Link - a pair of integer numbers
317  */
318 //=============================================================================
319 struct Link
320 {
321   int n1, n2;
322   Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
323   Link() : n1(0), n2(0) {}
324 };
325
326 int HashCode(const Link& aLink, int aLimit)
327 {
328   return HashCode(aLink.n1 + aLink.n2, aLimit);
329 }
330
331 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
332 {
333   return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
334           aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
335 }
336
337 namespace
338 {
339   //================================================================================
340   /*!
341    * \brief return id of netgen point corresponding to SMDS node
342    */
343   //================================================================================
344   typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
345
346   int ngNodeId( const SMDS_MeshNode* node,
347                 netgen::Mesh&        ngMesh,
348                 TNode2IdMap&         nodeNgIdMap)
349   {
350     int newNgId = ngMesh.GetNP() + 1;
351
352     TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
353
354     if ( node_id->second == newNgId)
355     {
356 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
357       cout << "Ng " << newNgId << " - " << node;
358 #endif
359       netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
360       ngMesh.AddPoint( p );
361     }
362     return node_id->second;
363   }
364
365   //================================================================================
366   /*!
367    * \brief Return computed EDGEs connected to the given one
368    */
369   //================================================================================
370
371   list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge&                 edge,
372                                          const TopoDS_Face&                 face,
373                                          const set< SMESH_subMesh* > &      computedSM,
374                                          const SMESH_MesherHelper&          helper,
375                                          map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
376   {
377     // get ordered EDGEs
378     list< TopoDS_Edge > edges;
379     list< int > nbEdgesInWire;
380     int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
381
382     // find <edge> within <edges>
383     list< TopoDS_Edge >::iterator eItFwd = edges.begin();
384     for ( ; eItFwd != edges.end(); ++eItFwd )
385       if ( edge.IsSame( *eItFwd ))
386         break;
387     if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
388
389     if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
390     {
391       // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
392       // so treat each INTERNAL edge separately
393       TopoDS_Edge e = *eItFwd;
394       edges.clear();
395       edges.push_back( e );
396       return edges;
397     }
398
399     // get all computed EDGEs connected to <edge>
400
401     list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
402     TopoDS_Vertex vCommon;
403     TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
404     eAdded.Add( edge );
405
406     // put edges before <edge> to <edges> back
407     while ( edges.begin() != eItFwd )
408       edges.splice( edges.end(), edges, edges.begin() );
409
410     // search forward
411     ePrev = eItFwd;
412     while ( ++eItFwd != edges.end() )
413     {
414       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
415
416       bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
417       bool computed  = sm->IsMeshComputed();
418       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
419       bool doubled   = !eAdded.Add( *eItFwd );
420       bool orientOK  = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
421                         ( eItFwd->Orientation() < TopAbs_INTERNAL )    );
422       if ( !connected || !computed || !orientOK || added || doubled )
423       {
424         // stop advancement; move edges from tail to head
425         while ( edges.back() != *ePrev )
426           edges.splice( edges.begin(), edges, --edges.end() );
427         break;
428       }
429       ePrev = eItFwd;
430     }
431     // search backward
432     while ( eItBack != edges.begin() )
433     {
434       ePrev = eItBack;
435       --eItBack;
436       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
437
438       bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
439       bool computed  = sm->IsMeshComputed();
440       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
441       bool doubled   = !eAdded.Add( *eItBack );
442       bool orientOK  = (( ePrev  ->Orientation() < TopAbs_INTERNAL ) ==
443                         ( eItBack->Orientation() < TopAbs_INTERNAL )    );
444       if ( !connected || !computed || !orientOK || added || doubled)
445       {
446         // stop advancement
447         edges.erase( edges.begin(), ePrev );
448         break;
449       }
450     }
451     if ( edges.front() != edges.back() )
452     {
453       // assure that the 1st vertex is meshed
454       TopoDS_Edge eLast = edges.back();
455       while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
456               &&
457               edges.front() != eLast )
458         edges.splice( edges.end(), edges, edges.begin() );
459     }
460     return edges;
461   }
462
463   //================================================================================
464   /*!
465    * \brief Make triangulation of a shape precise enough
466    */
467   //================================================================================
468
469   void updateTriangulation( const TopoDS_Shape& shape )
470   {
471     // static set< Poly_Triangulation* > updated;
472
473     // TopLoc_Location loc;
474     // TopExp_Explorer fExp( shape, TopAbs_FACE );
475     // for ( ; fExp.More(); fExp.Next() )
476     // {
477     //   Handle(Poly_Triangulation) triangulation =
478     //     BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
479     //   if ( triangulation.IsNull() ||
480     //        updated.insert( triangulation.operator->() ).second )
481     //   {
482     //     BRepTools::Clean (shape);
483         try {
484           OCC_CATCH_SIGNALS;
485           BRepMesh_IncrementalMesh e(shape, 0.01, true);
486         }
487         catch (Standard_Failure)
488         {
489         }
490   //       updated.erase( triangulation.operator->() );
491   //       triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
492   //       updated.insert( triangulation.operator->() );
493   //     }
494   //   }
495   }
496   //================================================================================
497   /*!
498    * \brief Returns a medium node either existing in SMESH of created by NETGEN
499    *  \param [in] corner1 - corner node 1
500    *  \param [in] corner2 - corner node 2
501    *  \param [in] defaultMedium - the node created by NETGEN
502    *  \param [in] helper - holder of medium nodes existing in SMESH
503    *  \return const SMDS_MeshNode* - the result node
504    */
505   //================================================================================
506
507   const SMDS_MeshNode* mediumNode( const SMDS_MeshNode*      corner1,
508                                    const SMDS_MeshNode*      corner2,
509                                    const SMDS_MeshNode*      defaultMedium,
510                                    const SMESH_MesherHelper* helper)
511   {
512     if ( helper )
513     {
514       TLinkNodeMap::const_iterator l2n =
515         helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
516       if ( l2n != helper->GetTLinkNodeMap().end() )
517         defaultMedium = l2n->second;
518     }
519     return defaultMedium;
520   }
521
522   //================================================================================
523   /*!
524    * \brief Assure that mesh on given shapes is quadratic
525    */
526   //================================================================================
527
528   void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
529                       SMESH_Mesh*                       mesh )
530   {
531     for ( int i = 1; i <= shapes.Extent(); ++i )
532     {
533       SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
534       if ( !smDS ) continue;
535       SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
536       if ( !elemIt->more() ) continue;
537       const SMDS_MeshElement* e = elemIt->next();
538       if ( !e || e->IsQuadratic() )
539         continue;
540
541       TIDSortedElemSet elems;
542       elems.insert( e );
543       while ( elemIt->more() )
544         elems.insert( elems.end(), elemIt->next() );
545
546       SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
547     }
548   }
549
550 }
551
552 //================================================================================
553 /*!
554  * \brief Initialize netgen::OCCGeometry with OCCT shape
555  */
556 //================================================================================
557
558 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
559                                              const TopoDS_Shape&      shape,
560                                              SMESH_Mesh&              mesh,
561                                              list< SMESH_subMesh* > * meshedSM,
562                                              NETGENPlugin_Internals*  intern)
563 {
564   updateTriangulation( shape );
565
566   Bnd_Box bb;
567   BRepBndLib::Add (shape, bb);
568   double x1,y1,z1,x2,y2,z2;
569   bb.Get (x1,y1,z1,x2,y2,z2);
570   MESSAGE("shape bounding box:\n" <<
571           "(" << x1 << " " << y1 << " " << z1 << ") " <<
572           "(" << x2 << " " << y2 << " " << z2 << ")");
573   netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
574   netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
575   occgeo.boundingbox = netgen::Box<3> (p1,p2);
576
577   occgeo.shape = shape;
578   occgeo.changed = 1;
579
580   // fill maps of shapes of occgeo with not yet meshed subshapes
581
582   // get root submeshes
583   list< SMESH_subMesh* > rootSM;
584   const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
585   if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
586     rootSM.push_back( mesh.GetSubMesh( shape ));
587   }
588   else {
589     for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
590       rootSM.push_back( mesh.GetSubMesh( it.Value() ));
591   }
592
593   // add subshapes of empty submeshes
594   list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
595   for ( ; rootIt != rootEnd; ++rootIt ) {
596     SMESH_subMesh * root = *rootIt;
597     SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
598                                                                /*complexShapeFirst=*/true);
599     // to find a right orientation of subshapes (PAL20462)
600     TopTools_IndexedMapOfShape subShapes;
601     TopExp::MapShapes(root->GetSubShape(), subShapes);
602     while ( smIt->more() )
603     {
604       SMESH_subMesh* sm = smIt->next();
605       TopoDS_Shape shape = sm->GetSubShape();
606       if ( intern && intern->isShapeToPrecompute( shape ))
607         continue;
608       if ( !meshedSM || sm->IsEmpty() )
609       {
610         if ( shape.ShapeType() != TopAbs_VERTEX )
611           shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
612         if ( shape.Orientation() >= TopAbs_INTERNAL )
613           shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
614         switch ( shape.ShapeType() ) {
615         case TopAbs_FACE  : occgeo.fmap.Add( shape ); break;
616         case TopAbs_EDGE  : occgeo.emap.Add( shape ); break;
617         case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
618         case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
619         default:;
620         }
621       }
622       // collect submeshes of meshed shapes
623       else if (meshedSM)
624       {
625         const int dim = SMESH_Gen::GetShapeDim( shape );
626         meshedSM[ dim ].push_back( sm );
627       }
628     }
629   }
630   occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
631   occgeo.facemeshstatus = 0;
632   occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
633   occgeo.face_maxh_modified = 0;
634   occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
635   occgeo.face_maxh = netgen::mparam.maxh;
636 }
637
638 //================================================================================
639 /*!
640  * \brief Return a default min size value suitable for the given geometry.
641  */
642 //================================================================================
643
644 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
645                                               const double        maxSize)
646 {
647   updateTriangulation( geom );
648
649   TopLoc_Location loc;
650   int i1, i2, i3;
651   const int* pi[4] = { &i1, &i2, &i3, &i1 };
652   double minh = 1e100;
653   Bnd_B3d bb;
654   TopExp_Explorer fExp( geom, TopAbs_FACE );
655   for ( ; fExp.More(); fExp.Next() )
656   {
657     Handle(Poly_Triangulation) triangulation =
658       BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
659     if ( triangulation.IsNull() ) continue;
660     const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
661     const TColgp_Array1OfPnt&   points = triangulation->Nodes();
662     const Poly_Array1OfTriangle& trias = triangulation->Triangles();
663     for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
664     {
665       trias(iT).Get( i1, i2, i3 );
666       for ( int j = 0; j < 3; ++j )
667       {
668         double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
669         if ( dist2 < minh && fTol*fTol < dist2 )
670           minh = dist2;
671         bb.Add( points(*pi[j]));
672       }
673     }
674   }
675   if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
676   {
677     minh = 1e-3 * sqrt( bb.SquareExtent());
678     //cout << "BND BOX minh = " <<minh << endl;
679   }
680   else
681   {
682     minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine
683     //cout << "TRIANGULATION minh = " <<minh << endl;
684   }
685   if ( minh > 0.5 * maxSize )
686     minh = maxSize / 3.;
687
688   return minh;
689 }
690
691 //================================================================================
692 /*!
693  * \brief Restrict size of elements at a given point
694  */
695 //================================================================================
696
697 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
698                                             const gp_XYZ& p,
699                                             const double  size,
700                                             const bool    overrideMinH)
701 {
702   if ( overrideMinH && netgen::mparam.minh > size )
703   {
704     ngMesh.SetMinimalH( size );
705     netgen::mparam.minh = size;
706   }
707   netgen::Point3d pi(p.X(), p.Y(), p.Z());
708   ngMesh.RestrictLocalH( pi, size );
709 }
710
711 //================================================================================
712 /*!
713  * \brief fill ngMesh with nodes and elements of computed submeshes
714  */
715 //================================================================================
716
717 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry&           occgeom,
718                                      netgen::Mesh&                  ngMesh,
719                                      vector<const SMDS_MeshNode*>&  nodeVec,
720                                      const list< SMESH_subMesh* > & meshedSM,
721                                      SMESH_MesherHelper*            quadHelper,
722                                      SMESH_ProxyMesh::Ptr           proxyMesh)
723 {
724   TNode2IdMap nodeNgIdMap;
725   for ( int i = 1; i < nodeVec.size(); ++i )
726     nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
727
728   TopTools_MapOfShape visitedShapes;
729   map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
730   set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
731
732   SMESH_MesherHelper helper (*_mesh);
733
734   int faceNgID = ngMesh.GetNFD();
735
736   list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
737   for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
738   {
739     SMESH_subMesh* sm = *smIt;
740     if ( !visitedShapes.Add( sm->GetSubShape() ))
741       continue;
742
743     const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
744     if ( !smDS ) continue;
745
746     switch ( sm->GetSubShape().ShapeType() )
747     {
748     case TopAbs_EDGE: { // EDGE
749       // ----------------------
750       TopoDS_Edge geomEdge  = TopoDS::Edge( sm->GetSubShape() );
751       if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
752         geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
753
754       // Add ng segments for each not meshed FACE the EDGE bounds
755       PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
756       while ( const TopoDS_Shape * anc = fIt->next() )
757       {
758         faceNgID = occgeom.fmap.FindIndex( *anc );
759         if ( faceNgID < 1 )
760           continue; // meshed face
761
762         int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc );
763         if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
764           continue; // already treated EDGE
765
766         TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
767         if ( face.Orientation() >= TopAbs_INTERNAL )
768           face.Orientation( TopAbs_FORWARD ); // issue 0020676
769
770         // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
771         helper.SetSubShape( face );
772         list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
773                                                        visitedEdgeSM2Faces );
774         if ( edges.empty() )
775           continue; // wrong ancestor?
776
777         // find out orientation of <edges> within <face>
778         TopoDS_Edge eNotSeam = edges.front();
779         if ( helper.HasSeam() )
780         {
781           list< TopoDS_Edge >::iterator eIt = edges.begin();
782           while ( helper.IsRealSeam( *eIt )) ++eIt;
783           if ( eIt != edges.end() )
784             eNotSeam = *eIt;
785         }
786         TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
787         bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
788
789         // get all nodes from connected <edges>
790         bool isQuad   = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false;
791         StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad );
792         const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
793         if ( points.empty() ) return false; // invalid node params?
794         int i, nbSeg = fSide.NbSegments();
795
796         // remember EDGEs of fSide to treat only once
797         for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
798           visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
799
800         double otherSeamParam = 0;
801         bool isSeam = false;
802
803         // add segments
804
805         int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
806
807         for ( i = 0; i < nbSeg; ++i )
808         {
809           const UVPtStruct& p1 = points[ i ];
810           const UVPtStruct& p2 = points[ i+1 ];
811
812           if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
813           {
814             isSeam = false;
815             if ( helper.IsRealSeam( p1.node->getshapeId() ))
816             {
817               TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
818               isSeam = helper.IsRealSeam( e );
819               if ( isSeam )
820               {
821                 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
822               }
823             }
824           }
825           netgen::Segment seg;
826           // ng node ids
827           seg[0] = prevNgId;
828           seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
829           // node param on curve
830           seg.epgeominfo[ 0 ].dist = p1.param;
831           seg.epgeominfo[ 1 ].dist = p2.param;
832           // uv on face
833           seg.epgeominfo[ 0 ].u = p1.u;
834           seg.epgeominfo[ 0 ].v = p1.v;
835           seg.epgeominfo[ 1 ].u = p2.u;
836           seg.epgeominfo[ 1 ].v = p2.v;
837
838           //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
839           //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
840
841           //seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
842           seg.si = faceNgID;                   // = geom.fmap.FindIndex (face);
843           seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
844           ngMesh.AddSegment (seg);
845
846           SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
847           RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
848
849 #ifdef DUMP_SEGMENTS
850           cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl
851                << "\tface index: " << seg.si << endl
852                << "\tp1: " << seg[0] << endl
853                << "\tp2: " << seg[1] << endl
854                << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
855                << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
856             //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
857                << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
858                << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
859             //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
860 #endif
861           if ( isSeam )
862           {
863             if ( helper.GetPeriodicIndex() && 1 ) {
864               seg.epgeominfo[ 0 ].u = otherSeamParam;
865               seg.epgeominfo[ 1 ].u = otherSeamParam;
866               swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
867             } else {
868               seg.epgeominfo[ 0 ].v = otherSeamParam;
869               seg.epgeominfo[ 1 ].v = otherSeamParam;
870               swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
871             }
872             swap (seg[0], seg[1]);
873             swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
874             seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
875             ngMesh.AddSegment (seg);
876 #ifdef DUMP_SEGMENTS
877             cout << "Segment: " << seg.edgenr << endl
878                  << "\t is SEAM (reverse) of the previous. "
879                  << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
880                  << " = " << otherSeamParam << endl;
881 #endif
882           }
883           else if ( fOri == TopAbs_INTERNAL )
884           {
885             swap (seg[0], seg[1]);
886             swap( seg.epgeominfo[0], seg.epgeominfo[1] );
887             seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
888             ngMesh.AddSegment (seg);
889 #ifdef DUMP_SEGMENTS
890             cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
891 #endif
892           }
893         }
894       } // loop on geomEdge ancestors
895
896       if ( quadHelper ) // remember medium nodes of sub-meshes
897       {
898         SMDS_ElemIteratorPtr edges = smDS->GetElements();
899         while ( edges->more() )
900         {
901           const SMDS_MeshElement* e = edges->next();
902           if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
903             break;
904         }
905       }
906
907       break;
908     } // case TopAbs_EDGE
909
910     case TopAbs_FACE: { // FACE
911       // ----------------------
912       const TopoDS_Face& geomFace  = TopoDS::Face( sm->GetSubShape() );
913       helper.SetSubShape( geomFace );
914       bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
915
916       // Find solids the geomFace bounds
917       int solidID1 = 0, solidID2 = 0;
918       StdMeshers_QuadToTriaAdaptor* quadAdaptor =
919         dynamic_cast<StdMeshers_QuadToTriaAdaptor*>( proxyMesh.get() );
920       if ( quadAdaptor )
921       {
922         solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() );
923       }
924       else
925       {  
926         PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
927         while ( const TopoDS_Shape * solid = solidIt->next() )
928         {
929           int id = occgeom.somap.FindIndex ( *solid );
930           if ( solidID1 && id != solidID1 ) solidID2 = id;
931           else                              solidID1 = id;
932         }
933       }
934       // Add ng face descriptors of meshed faces
935       faceNgID++;
936       ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0));
937
938       // if second oreder is required, even already meshed faces must be passed to NETGEN
939       int fID = occgeom.fmap.Add( geomFace );
940       while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
941         fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
942       // Problem with the second order in a quadrangular mesh remains.
943       // 1) All quadrangles generated by NETGEN are moved to an inexistent face
944       //    by FillSMesh() (find "AddFaceDescriptor")
945       // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
946       //    are on faces where quadrangles were.
947       // Due to these 2 points, wrong geom faces are used while conversion to qudratic
948       // of the mentioned above quadrangles and triangles
949
950       // Orient the face correctly in solidID1 (issue 0020206)
951       bool reverse = false;
952       if ( solidID1 ) {
953         TopoDS_Shape solid = occgeom.somap( solidID1 );
954         TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
955         if ( faceOriInSolid >= 0 )
956           reverse =
957             helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
958       }
959
960       // Add surface elements
961
962       netgen::Element2d tri(3);
963       tri.SetIndex ( faceNgID );
964
965
966 #ifdef DUMP_TRIANGLES
967       cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace )
968            << " internal="<<isInternalFace << endl;
969 #endif
970       if ( proxyMesh )
971         smDS = proxyMesh->GetSubMesh( geomFace );
972
973       SMDS_ElemIteratorPtr faces = smDS->GetElements();
974       while ( faces->more() )
975       {
976         const SMDS_MeshElement* f = faces->next();
977         if ( f->NbNodes() % 3 != 0 ) // not triangle
978         {
979           PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
980           if ( const TopoDS_Shape * solid = solidIt->next() )
981             sm = _mesh->GetSubMesh( *solid );
982           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
983           smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh"));
984           smError->myBadElements.push_back( f );
985           return false;
986         }
987
988         for ( int i = 0; i < 3; ++i )
989         {
990           const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
991
992           // get node UV on face
993           int shapeID = node->getshapeId();
994           if ( helper.IsSeamShape( shapeID ))
995             if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() ))
996               inFaceNode = f->GetNodeWrap( i-1 );
997             else
998               inFaceNode = f->GetNodeWrap( i+1 );
999           gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1000
1001           int ind = reverse ? 3-i : i+1;
1002           tri.GeomInfoPi(ind).u = uv.X();
1003           tri.GeomInfoPi(ind).v = uv.Y();
1004           tri.PNum      (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1005         }
1006
1007         ngMesh.AddSurfaceElement (tri);
1008 #ifdef DUMP_TRIANGLES
1009         cout << tri << endl;
1010 #endif
1011
1012         if ( isInternalFace )
1013         {
1014           swap( tri[1], tri[2] );
1015           ngMesh.AddSurfaceElement (tri);
1016 #ifdef DUMP_TRIANGLES
1017           cout << tri << endl;
1018 #endif
1019         }
1020       }
1021
1022       if ( quadHelper ) // remember medium nodes of sub-meshes
1023       {
1024         SMDS_ElemIteratorPtr faces = smDS->GetElements();
1025         while ( faces->more() )
1026         {
1027           const SMDS_MeshElement* f = faces->next();
1028           if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1029             break;
1030         }
1031       }
1032
1033       break;
1034     } // case TopAbs_FACE
1035
1036     case TopAbs_VERTEX: { // VERTEX
1037       // --------------------------
1038       // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1039       // else netgen removes a free node and nodeVector becomes invalid
1040       PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1041                                                      *sm->GetFather(),
1042                                                      TopAbs_EDGE );
1043       bool toAdd = false;
1044       while ( const TopoDS_Shape* e = ansIt->next() )
1045       {
1046         SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1047         if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1048           break;
1049       }
1050       if ( toAdd )
1051       {
1052         SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1053         if ( nodeIt->more() )
1054           ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1055       }
1056       break;
1057     }
1058     default:;
1059     } // switch
1060   } // loop on submeshes
1061
1062   // fill nodeVec
1063   nodeVec.resize( ngMesh.GetNP() + 1 );
1064   TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1065   for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1066     nodeVec[ node_NgId->second ] = node_NgId->first;
1067
1068   return true;
1069 }
1070
1071 //================================================================================
1072 /*!
1073  * \brief Duplicate mesh faces on internal geom faces
1074  */
1075 //================================================================================
1076
1077 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1078                                       netgen::Mesh&              ngMesh,
1079                                       NETGENPlugin_Internals&    internalShapes)
1080 {
1081   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1082   
1083   // find ng indices of internal faces
1084   set<int> ngFaceIds;
1085   for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1086   {
1087     int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1088     if ( internalShapes.isInternalShape( smeshID ))
1089       ngFaceIds.insert( ngFaceID );
1090   }
1091   if ( !ngFaceIds.empty() )
1092   {
1093     // duplicate faces
1094     int i, nbFaces = ngMesh.GetNSE();
1095     for (int i = 1; i <= nbFaces; ++i)
1096     {
1097       netgen::Element2d elem = ngMesh.SurfaceElement(i);
1098       if ( ngFaceIds.count( elem.GetIndex() ))
1099       {
1100         swap( elem[1], elem[2] );
1101         ngMesh.AddSurfaceElement (elem);
1102       }
1103     }
1104   }
1105 }
1106
1107 namespace
1108 {
1109   //================================================================================
1110   // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1111   gp_XY_FunPtr(Subtracted);
1112   //gp_XY_FunPtr(Added);
1113
1114   //================================================================================
1115   /*!
1116    * \brief Evaluate distance between two 2d points along the surface
1117    */
1118   //================================================================================
1119
1120   double evalDist( const gp_XY&                uv1,
1121                    const gp_XY&                uv2,
1122                    const Handle(Geom_Surface)& surf,
1123                    const int                   stopHandler=-1)
1124   {
1125     if ( stopHandler > 0 ) // continue recursion
1126     {
1127       gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1128       return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1129     }
1130     double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1131     if ( stopHandler == 0 ) // stop recursion
1132       return dist3D;
1133     
1134     // start recursion if necessary
1135     double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1136     if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1137       return dist3D; // equal parametrization of a planar surface
1138
1139     return evalDist( uv1, uv2, surf, 3 ); // start recursion
1140   }
1141
1142   //================================================================================
1143   /*!
1144    * \brief Data of vertex internal in geom face
1145    */
1146   //================================================================================
1147
1148   struct TIntVData
1149   {
1150     gp_XY uv;        //!< UV in face parametric space
1151     int   ngId;      //!< ng id of corrsponding node
1152     gp_XY uvClose;   //!< UV of closest boundary node
1153     int   ngIdClose; //!< ng id of closest boundary node
1154   };
1155
1156   //================================================================================
1157   /*!
1158    * \brief Data of vertex internal in solid
1159    */
1160   //================================================================================
1161
1162   struct TIntVSoData
1163   {
1164     int   ngId;      //!< ng id of corresponding node
1165     int   ngIdClose; //!< ng id of closest 2d mesh element
1166     int   ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1167   };
1168
1169   inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2)
1170   {
1171     return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1172   }
1173 }
1174
1175 //================================================================================
1176 /*!
1177  * \brief Make netgen take internal vertices in faces into account by adding
1178  *        segments including internal vertices
1179  *
1180  * This function works in supposition that 1D mesh is already computed in ngMesh
1181  */
1182 //================================================================================
1183
1184 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry&     occgeom,
1185                                                 netgen::Mesh&                  ngMesh,
1186                                                 vector<const SMDS_MeshNode*>&  nodeVec,
1187                                                 NETGENPlugin_Internals&        internalShapes)
1188 {
1189   if ( nodeVec.size() < ngMesh.GetNP() )
1190     nodeVec.resize( ngMesh.GetNP(), 0 );
1191
1192   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1193   SMESH_MesherHelper helper( internalShapes.getMesh() );
1194
1195   const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1196   map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1197   for ( ; f2v != face2Vert.end(); ++f2v )
1198   {
1199     const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1200     if ( face.IsNull() ) continue;
1201     int faceNgID = occgeom.fmap.FindIndex (face);
1202     if ( faceNgID < 0 ) continue;
1203
1204     TopLoc_Location loc;
1205     Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1206
1207     helper.SetSubShape( face );
1208     helper.SetElementsOnShape( true );
1209
1210     // Get data of internal vertices and add them to ngMesh
1211
1212     multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1213
1214     int i, nbSegInit = ngMesh.GetNSeg();
1215
1216     // boundary characteristics
1217     double totSegLen2D = 0;
1218     int totNbSeg = 0;
1219
1220     const list<int>& iVertices = f2v->second;
1221     list<int>::const_iterator iv = iVertices.begin();
1222     for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1223     {
1224       TIntVData vData;
1225       // get node on vertex
1226       const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1227       const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1228       if ( !nV )
1229       {
1230         SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1231         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1232         nV = SMESH_Algo::VertexNode( V, meshDS );
1233         if ( !nV ) continue;
1234       }
1235       // add ng node
1236       netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1237       ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1238       vData.ngId = ngMesh.GetNP();
1239       nodeVec.push_back( nV );
1240
1241       // get node UV
1242       bool uvOK = true;
1243       vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1244       if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1245
1246       // loop on all segments of the face to find the node closest to vertex and to count
1247       // average segment 2d length
1248       double closeDist2 = numeric_limits<double>::max(), dist2;
1249       int ngIdLast = 0;
1250       for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1251       {
1252         netgen::Segment & seg = ngMesh.LineSegment(i);
1253         if ( seg.si != faceNgID ) continue;
1254         gp_XY uv[2];
1255         for ( int iEnd = 0; iEnd < 2; ++iEnd)
1256         {
1257           uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1258           if ( ngIdLast == seg[ iEnd ] ) continue;
1259           dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1260           if ( dist2 < closeDist2 )
1261             vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1262           ngIdLast = seg[ iEnd ];
1263         }
1264         if ( !nbV )
1265         {
1266           totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1267           totNbSeg++;
1268         }
1269       }
1270       dist2VData.insert( make_pair( closeDist2, vData ));
1271     }
1272
1273     if ( totNbSeg == 0 ) break;
1274     double avgSegLen2d = totSegLen2D / totNbSeg;
1275
1276     // Loop on vertices to add segments
1277
1278     multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1279     for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1280     {
1281       double closeDist2 = dist_vData->first, dist2;
1282       TIntVData & vData = dist_vData->second;
1283
1284       // try to find more close node among segments added for internal vertices
1285       for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1286       {
1287         netgen::Segment & seg = ngMesh.LineSegment(i);
1288         if ( seg.si != faceNgID ) continue;
1289         gp_XY uv[2];
1290         for ( int iEnd = 0; iEnd < 2; ++iEnd)
1291         {
1292           uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1293           dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1294           if ( dist2 < closeDist2 )
1295             vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1296         }
1297       }
1298       // decide whether to use the closest node as the second end of segment or to
1299       // create a new point
1300       int segEnd1 = vData.ngId;
1301       int segEnd2 = vData.ngIdClose; // to use closest node
1302       gp_XY uvV = vData.uv, uvP = vData.uvClose;
1303       double segLenHint  = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1304       double nodeDist2D  = sqrt( closeDist2 );
1305       double nodeDist3D  = evalDist( vData.uv, vData.uvClose, surf );
1306       bool avgLenOK  = ( avgSegLen2d < 0.75 * nodeDist2D );
1307       bool hintLenOK = ( segLenHint  < 0.75 * nodeDist3D );
1308       //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1309       if ( hintLenOK || avgLenOK )
1310       {
1311         // create a point between the closest node and V
1312
1313         // how far from V
1314         double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1315         // direction from V to closet node in 2D
1316         gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1317         // new point
1318         uvP = vData.uv + r * nodeDist2D * v2n.XY();
1319         gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1320
1321         netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1322         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1323         segEnd2 = ngMesh.GetNP();
1324         //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1325         SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1326         nodeVec.push_back( nP );
1327       }
1328       //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1329
1330       // Add the segment
1331       netgen::Segment seg;
1332
1333       if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1334       seg[0] = segEnd1;  // ng node id
1335       seg[1] = segEnd2;  // ng node id
1336       seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1337       seg.si = faceNgID;
1338
1339       seg.epgeominfo[ 0 ].dist = 0; // param on curve
1340       seg.epgeominfo[ 0 ].u    = uvV.X();
1341       seg.epgeominfo[ 0 ].v    = uvV.Y();
1342       seg.epgeominfo[ 1 ].dist = 1; // param on curve
1343       seg.epgeominfo[ 1 ].u    = uvP.X();
1344       seg.epgeominfo[ 1 ].v    = uvP.Y();
1345
1346 //       seg.epgeominfo[ 0 ].edgenr = 10; //  = geom.emap.FindIndex(edge);
1347 //       seg.epgeominfo[ 1 ].edgenr = 10; //  = geom.emap.FindIndex(edge);
1348
1349       ngMesh.AddSegment (seg);
1350
1351       // add reverse segment
1352       swap (seg[0], seg[1]);
1353       swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1354       seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1355       ngMesh.AddSegment (seg);
1356     }
1357
1358   }
1359 }
1360
1361 //================================================================================
1362 /*!
1363  * \brief Make netgen take internal vertices in solids into account by adding
1364  *        faces including internal vertices
1365  *
1366  * This function works in supposition that 2D mesh is already computed in ngMesh
1367  */
1368 //================================================================================
1369
1370 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry&     occgeom,
1371                                                  netgen::Mesh&                  ngMesh,
1372                                                  vector<const SMDS_MeshNode*>&  nodeVec,
1373                                                  NETGENPlugin_Internals&        internalShapes)
1374 {
1375 #ifdef DUMP_TRIANGLES_SCRIPT
1376   // create a python script making a mesh containing triangles added for internal vertices
1377   ofstream py(DUMP_TRIANGLES_SCRIPT);
1378   py << "import SMESH"<< endl
1379      << "from salome.smesh import smeshBuilder"<<endl
1380      << "smesh = smeshBuilder.New(salome.myStudy)"<<endl
1381      << "m = smesh.Mesh(name='triangles')" << endl;
1382 #endif
1383   if ( nodeVec.size() < ngMesh.GetNP() )
1384     nodeVec.resize( ngMesh.GetNP(), 0 );
1385
1386   SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1387   SMESH_MesherHelper helper( internalShapes.getMesh() );
1388
1389   const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1390   map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1391   for ( ; s2v != so2Vert.end(); ++s2v )
1392   {
1393     const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1394     if ( solid.IsNull() ) continue;
1395     int solidNgID = occgeom.somap.FindIndex (solid);
1396     if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1397
1398     helper.SetSubShape( solid );
1399     helper.SetElementsOnShape( true );
1400
1401     // find ng indices of faces within the solid
1402     set<int> ngFaceIds;
1403     for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1404       ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1405     if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1406       ngFaceIds.insert( 1 );
1407
1408     // Get data of internal vertices and add them to ngMesh
1409
1410     multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1411
1412     int i, nbFaceInit = ngMesh.GetNSE();
1413
1414     // boundary characteristics
1415     double totSegLen = 0;
1416     int totNbSeg = 0;
1417
1418     const list<int>& iVertices = s2v->second;
1419     list<int>::const_iterator iv = iVertices.begin();
1420     for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1421     {
1422       TIntVSoData vData;
1423       const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1424
1425       // get node on vertex
1426       const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1427       if ( !nV )
1428       {
1429         SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1430         sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1431         nV = SMESH_Algo::VertexNode( V, meshDS );
1432         if ( !nV ) continue;
1433       }
1434       // add ng node
1435       netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1436       ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
1437       vData.ngId = ngMesh.GetNP();
1438       nodeVec.push_back( nV );
1439
1440       // loop on all 2d elements to find the one closest to vertex and to count
1441       // average segment length
1442       double closeDist2 = numeric_limits<double>::max(), avgDist2;
1443       for (i = 1; i <= ngMesh.GetNSE(); ++i)
1444       {
1445         const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1446         if ( !ngFaceIds.count( elem.GetIndex() )) continue;
1447         avgDist2 = 0;
1448         multimap< double, int> dist2nID; // sort nodes of element by distance from V
1449         for ( int j = 0; j < elem.GetNP(); ++j)
1450         {
1451           netgen::MeshPoint mp = ngMesh.Point( elem[j] );
1452           double d2 = dist2( mpV, mp );
1453           dist2nID.insert( make_pair( d2, elem[j] ));
1454           avgDist2 += d2 / elem.GetNP();
1455           if ( !nbV )
1456             totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
1457         }
1458         double dist = dist2nID.begin()->first; //avgDist2;
1459         if ( dist < closeDist2 )
1460           vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
1461       }
1462       dist2VData.insert( make_pair( closeDist2, vData ));
1463     }
1464
1465     if ( totNbSeg == 0 ) break;
1466     double avgSegLen = totSegLen / totNbSeg;
1467
1468     // Loop on vertices to add triangles
1469
1470     multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
1471     for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1472     {
1473       double closeDist2   = dist_vData->first;
1474       TIntVSoData & vData = dist_vData->second;
1475
1476       const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
1477
1478       // try to find more close face among ones added for internal vertices
1479       for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
1480       {
1481         double avgDist2 = 0;
1482         multimap< double, int> dist2nID;
1483         const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1484         for ( int j = 0; j < elem.GetNP(); ++j)
1485         {
1486           double d = dist2( mpV, ngMesh.Point( elem[j] ));
1487           dist2nID.insert( make_pair( d, elem[j] ));
1488           avgDist2 += d / elem.GetNP();
1489           if ( avgDist2 < closeDist2 )
1490             vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
1491         }
1492       }
1493       // sort nodes of the closest face by angle with vector from V to the closest node
1494       const double tol = numeric_limits<double>::min();
1495       map< double, int > angle2ID;
1496       const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
1497       netgen::MeshPoint mp[2];
1498       mp[0] = ngMesh.Point( vData.ngIdCloseN );
1499       gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
1500       gp_XYZ pV( NGPOINT_COORDS( mpV ));
1501       gp_Vec v2p1( pV, p1 );
1502       double distN1 = v2p1.Magnitude();
1503       if ( distN1 <= tol ) continue;
1504       v2p1 /= distN1;
1505       for ( int j = 0; j < closeFace.GetNP(); ++j)
1506       {
1507         mp[1] = ngMesh.Point( closeFace[j] );
1508         gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
1509         angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
1510       }
1511       // get node with angle of 60 degrees or greater
1512       map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
1513       if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
1514       const double minAngle = 30. * M_PI / 180.;
1515       const double angle = angle_id->first;
1516       bool angleOK = ( angle > minAngle );
1517
1518       // find points to create a triangle
1519       netgen::Element2d tri(3);
1520       tri.SetIndex ( 1 );
1521       tri[0] = vData.ngId;
1522       tri[1] = vData.ngIdCloseN; // to use the closest nodes
1523       tri[2] = angle_id->second; // to use the node with best angle
1524
1525       // decide whether to use the closest node and the node with best angle or to create new ones
1526       for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
1527       {
1528         bool createNew = !angleOK, distOK = true;
1529         double distFromV;
1530         int triInd = isBestAngleN ? 2 : 1;
1531         mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
1532         if ( isBestAngleN )
1533         {
1534           if ( angleOK )
1535           {
1536             double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
1537             createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
1538           }
1539           else if ( angle < tol )
1540           {
1541             v2p1.SetX( v2p1.X() + 1e-3 );
1542           }
1543           distFromV = distN1;
1544         }
1545         else
1546         {
1547           double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1548           bool avgLenOK  = ( avgSegLen < 0.75 * distN1 );
1549           bool hintLenOK = ( segLenHint  < 0.75 * distN1 );
1550           createNew = (createNew || avgLenOK || hintLenOK );
1551           // we create a new node not closer than 0.5 to the closest face
1552           // in order not to clash with other close face
1553           double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
1554           distFromV = r * distN1;
1555         }
1556         if ( createNew )
1557         {
1558           // create a new point, between the node and the vertex if angleOK
1559           gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
1560           gp_Vec v2p( pV, p ); v2p.Normalize();
1561           if ( isBestAngleN && !angleOK )
1562             p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
1563           else
1564             p = pV + v2p.XYZ() * distFromV;
1565
1566           if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
1567
1568           mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
1569           ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
1570           tri[triInd] = ngMesh.GetNP();
1571           nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
1572         }
1573       }
1574       ngMesh.AddSurfaceElement (tri);
1575       swap( tri[1], tri[2] );
1576       ngMesh.AddSurfaceElement (tri);
1577
1578 #ifdef DUMP_TRIANGLES_SCRIPT
1579       py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
1580          << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
1581          << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
1582          << "m.AddFace([n1,n2,n3])" << endl;
1583 #endif
1584     } // loop on internal vertices of a solid
1585
1586   } // loop on solids with internal vertices
1587 }
1588
1589 //================================================================================
1590 /*!
1591  * \brief Fill netgen mesh with segments of a FACE
1592  *  \param ngMesh - netgen mesh
1593  *  \param geom - container of OCCT geometry to mesh
1594  *  \param wires - data of nodes on FACE boundary
1595  *  \param helper - mesher helper holding the FACE
1596  *  \param nodeVec - vector of nodes in which node index == netgen ID
1597  *  \retval SMESH_ComputeErrorPtr - error description 
1598  */
1599 //================================================================================
1600
1601 SMESH_ComputeErrorPtr
1602 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
1603                                        netgen::OCCGeometry&             geom,
1604                                        const TSideVector&               wires,
1605                                        SMESH_MesherHelper&              helper,
1606                                        vector< const SMDS_MeshNode* > & nodeVec,
1607                                        const bool                       overrideMinH)
1608 {
1609   // ----------------------------
1610   // Check wires and count nodes
1611   // ----------------------------
1612   int nbNodes = 0;
1613   for ( int iW = 0; iW < wires.size(); ++iW )
1614   {
1615     StdMeshers_FaceSidePtr wire = wires[ iW ];
1616     if ( wire->MissVertexNode() )
1617     {
1618       // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
1619       // It seems that there is no reason for this limitation
1620 //       return TError
1621 //         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
1622     }
1623     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1624     if ( uvPtVec.size() != wire->NbPoints() )
1625       return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
1626                                      SMESH_Comment("Unexpected nb of points on wire ") << iW
1627                                      << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
1628     nbNodes += wire->NbPoints();
1629   }
1630   nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
1631   if ( nodeVec.empty() )
1632     nodeVec.push_back( 0 );
1633
1634   // -----------------
1635   // Fill netgen mesh
1636   // -----------------
1637
1638   const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
1639                                                          NETGENPlugin_NETGEN_2D_ONLY */
1640
1641   // map for nodes on vertices since they can be shared between wires
1642   // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
1643   map<const SMDS_MeshNode*, int > node2ngID;
1644   if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
1645   {
1646     set< int > subIDs; // ids of sub-shapes of the FACE
1647     for ( int iW = 0; iW < wires.size(); ++iW )
1648     {
1649       StdMeshers_FaceSidePtr wire = wires[ iW ];
1650       for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
1651       {
1652         subIDs.insert( wire->EdgeID( iE ));
1653         subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
1654       }
1655     }
1656     for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
1657       if ( subIDs.count( nodeVec[ngID]->getshapeId() ))
1658         node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
1659   }
1660
1661   const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
1662   if ( ngMesh.GetNFD() < 1 )
1663     ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0));
1664
1665   for ( int iW = 0; iW < wires.size(); ++iW )
1666   {
1667     StdMeshers_FaceSidePtr wire = wires[ iW ];
1668     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
1669     const int nbSegments = wire->NbPoints() - 1;
1670
1671     // assure the 1st node to be in node2ngID, which is needed to correctly
1672     // "close chain of segments" (see below) in case if the 1st node is not
1673     // onVertex because it is on a Viscous layer
1674     node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
1675
1676     // compute length of every segment
1677     vector<double> segLen( nbSegments );
1678     for ( int i = 0; i < nbSegments; ++i )
1679       segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
1680
1681     int edgeID = 1, posID = -2;
1682     bool isInternalWire = false;
1683     double vertexNormPar = 0;
1684     const int prevNbNGSeg = ngMesh.GetNSeg();
1685     for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1686     {
1687       // Add the first point of a segment
1688
1689       const SMDS_MeshNode * n = uvPtVec[ i ].node;
1690       const int posShapeID = n->getshapeId();
1691       bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1692       bool onEdge   = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE   );
1693
1694       // skip nodes on degenerated edges
1695       if ( helper.IsDegenShape( posShapeID ) &&
1696            helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1697         continue;
1698
1699       int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1700       if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1701         ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1702       if ( ngID1 > ngMesh.GetNP() )
1703       {
1704         netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1705         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1706         nodeVec.push_back( n );
1707       }
1708       else // n is in ngMesh already, and ngID2 in prev segment is wrong
1709       {
1710         ngID2 = ngMesh.GetNP() + 1;
1711         if ( i > 0 ) // prev segment belongs to same wire
1712         {
1713           netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1714           prevSeg[1] = ngID1;
1715         }
1716       }
1717
1718       // Add the segment
1719
1720       netgen::Segment seg;
1721
1722       seg[0]     = ngID1;                // ng node id
1723       seg[1]     = ngID2;                // ng node id
1724       seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1725       seg.si     = faceID;               // = geom.fmap.FindIndex (face);
1726
1727       for ( int iEnd = 0; iEnd < 2; ++iEnd)
1728       {
1729         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1730
1731         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1732         seg.epgeominfo[ iEnd ].u    = pnt.u;
1733         seg.epgeominfo[ iEnd ].v    = pnt.v;
1734
1735         // find out edge id and node parameter on edge
1736         onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1737         if ( onVertex || posShapeID != posID )
1738         {
1739           // get edge id
1740           double normParam = pnt.normParam;
1741           if ( onVertex )
1742             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1743           int edgeIndexInWire = wire->EdgeIndex( normParam );
1744           vertexNormPar = wire->LastParameter( edgeIndexInWire );
1745           const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1746           edgeID = geom.emap.FindIndex( edge );
1747           posID  = posShapeID;
1748           isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1749           // if ( onVertex ) // param on curve is different on each of two edges
1750           //   seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1751         }
1752         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
1753       }
1754
1755       ngMesh.AddSegment (seg);
1756       {
1757         // restrict size of elements near the segment
1758         SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1759         // get an average size of adjacent segments to avoid sharp change of
1760         // element size (regression on issue 0020452, note 0010898)
1761         int   iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1762         int   iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1763         double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
1764         int   nbSeg = ( int( segLen[ iPrev ] > sumH / 100.)  +
1765                         int( segLen[ i     ] > sumH / 100.)  +
1766                         int( segLen[ iNext ] > sumH / 100.));
1767         if ( nbSeg > 0 )
1768           RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
1769       }
1770       if ( isInternalWire )
1771       {
1772         swap (seg[0], seg[1]);
1773         swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1774         seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1775         ngMesh.AddSegment (seg);
1776       }
1777     } // loop on segments on a wire
1778
1779     // close chain of segments
1780     if ( nbSegments > 0 )
1781     {
1782       netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1783       const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1784       lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1785       if ( lastSeg[1] > ngMesh.GetNP() )
1786       {
1787         netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1788         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1789         nodeVec.push_back( lastNode );
1790       }
1791       if ( isInternalWire )
1792       {
1793         netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1794         realLastSeg[0] = lastSeg[1];
1795       }
1796     }
1797
1798 #ifdef DUMP_SEGMENTS
1799     cout << "BEGIN WIRE " << iW << endl;
1800     for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
1801     {
1802       netgen::Segment& seg = ngMesh.LineSegment( i );
1803       if ( i > 1 ) {
1804         netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
1805         if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
1806         {
1807           cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1808           continue;
1809         }
1810       }
1811       cout << "Segment: " << seg.edgenr << endl
1812            << "\tp1: " << seg[0] << endl
1813            << "\tp2: " << seg[1] << endl
1814            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1815            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1816            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1817            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1818            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1819            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1820     }
1821     cout << "--END WIRE " << iW << endl;
1822 #endif
1823
1824   } // loop on WIREs of a FACE
1825
1826   // add a segment instead of an internal vertex
1827   if ( wasNgMeshEmpty )
1828   {
1829     NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1830     AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1831   }
1832   ngMesh.CalcSurfacesOfNode();
1833
1834   return TError();
1835 }
1836
1837 //================================================================================
1838 /*!
1839  * \brief Fill SMESH mesh according to contents of netgen mesh
1840  *  \param occgeo - container of OCCT geometry to mesh
1841  *  \param ngMesh - netgen mesh
1842  *  \param initState - bn of entities in netgen mesh before computing
1843  *  \param sMesh - SMESH mesh to fill in
1844  *  \param nodeVec - vector of nodes in which node index == netgen ID
1845  *  \param comment - returns problem description
1846  *  \param quadHelper - holder of medium nodes of sub-meshes
1847  *  \retval int - error
1848  */
1849 //================================================================================
1850
1851 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
1852                                    netgen::Mesh&                       ngMesh,
1853                                    const NETGENPlugin_ngMeshInfo&      initState,
1854                                    SMESH_Mesh&                         sMesh,
1855                                    std::vector<const SMDS_MeshNode*>&  nodeVec,
1856                                    SMESH_Comment&                      comment,
1857                                    SMESH_MesherHelper*                 quadHelper)
1858 {
1859   int nbNod = ngMesh.GetNP();
1860   int nbSeg = ngMesh.GetNSeg();
1861   int nbFac = ngMesh.GetNSE();
1862   int nbVol = ngMesh.GetNE();
1863
1864   SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1865
1866   // quadHelper is used for either
1867   // 1) making quadratic elements when a lower dimention mesh is loaded
1868   //    to SMESH before convertion to quadratic by NETGEN
1869   // 2) sewing of quadratic elements with quadratic elements of sub-meshes
1870   if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
1871     quadHelper = 0;
1872
1873   // -------------------------------------
1874   // Create and insert nodes into nodeVec
1875   // -------------------------------------
1876
1877   nodeVec.resize( nbNod + 1 );
1878   int i, nbInitNod = initState._nbNodes;
1879   for (i = nbInitNod+1; i <= nbNod; ++i )
1880   {
1881     const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1882     SMDS_MeshNode* node = NULL;
1883     TopoDS_Vertex aVert;
1884     // First, netgen creates nodes on vertices in occgeo.vmap,
1885     // so node index corresponds to vertex index
1886     // but (issue 0020776) netgen does not create nodes with equal coordinates
1887     if ( i-nbInitNod <= occgeo.vmap.Extent() )
1888     {
1889       gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1890       for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1891       {
1892         aVert = TopoDS::Vertex( occgeo.vmap( iV ));
1893         gp_Pnt pV = BRep_Tool::Pnt( aVert );
1894         if ( p.SquareDistance( pV ) > 1e-20 )
1895           aVert.Nullify();
1896         else
1897           node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1898       }
1899     }
1900     if (!node) // node not found on vertex
1901     {
1902       node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1903       if (!aVert.IsNull())
1904         meshDS->SetNodeOnVertex(node, aVert);
1905     }
1906     nodeVec[i] = node;
1907   }
1908
1909   // -------------------------------------------
1910   // Create mesh segments along geometric edges
1911   // -------------------------------------------
1912
1913   int nbInitSeg = initState._nbSegments;
1914   for (i = nbInitSeg+1; i <= nbSeg; ++i )
1915   {
1916     const netgen::Segment& seg = ngMesh.LineSegment(i);
1917     TopoDS_Edge aEdge;
1918     int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1919     int nbp = 0;
1920     double param2 = 0;
1921     for (int j=0; j < 3; ++j)
1922     {
1923       int pind = pinds[j];
1924       if (pind <= 0 || !nodeVec_ACCESS(pind))
1925         break;
1926       ++nbp;
1927       double param;
1928       if (j < 2)
1929       {
1930         if (aEdge.IsNull())
1931         {
1932           int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1933           if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1934             aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1935         }
1936         param = seg.epgeominfo[j].dist;
1937         param2 += param;
1938       }
1939       else // middle point
1940       {
1941         param = param2 * 0.5;
1942       }
1943       if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1944       {
1945         meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1946       }
1947     }
1948     if ( nbp > 1 )
1949     {
1950       SMDS_MeshEdge* edge = 0;
1951       if (nbp == 2) // second order ?
1952       {
1953         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1954           continue;
1955         if ( quadHelper ) // final mesh must be quadratic
1956           edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1957         else
1958           edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1959       }
1960       else
1961       {
1962         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1963                                nodeVec_ACCESS(pinds[2])))
1964           continue;
1965         edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1966                                nodeVec_ACCESS(pinds[2]));
1967       }
1968       if (!edge)
1969       {
1970         if ( comment.empty() ) comment << "Cannot create a mesh edge";
1971         MESSAGE("Cannot create a mesh edge");
1972         nbSeg = nbFac = nbVol = 0;
1973         break;
1974       }
1975       if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1976         meshDS->SetMeshElementOnShape(edge, aEdge);
1977     }
1978     else if ( comment.empty() )
1979     {
1980       comment << "Invalid netgen segment #" << i;
1981     }
1982   }
1983
1984   // ----------------------------------------
1985   // Create mesh faces along geometric faces
1986   // ----------------------------------------
1987
1988   int nbInitFac = initState._nbFaces;
1989   int quadFaceID = ngMesh.GetNFD() + 1;
1990   if ( nbInitFac < nbFac )
1991     // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1992     // from computation of 3D mesh
1993     ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1994
1995   vector<const SMDS_MeshNode*> nodes;
1996   for (i = nbInitFac+1; i <= nbFac; ++i )
1997   {
1998     const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1999     int aGeomFaceInd = elem.GetIndex();
2000     TopoDS_Face aFace;
2001     if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2002       aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2003     nodes.clear();
2004     for (int j=1; j <= elem.GetNP(); ++j)
2005     {
2006       int pind = elem.PNum(j);
2007       if ( pind < 1 || pind >= nodeVec.size() )
2008         break;
2009       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2010       {
2011         nodes.push_back( node );
2012         if (!aFace.IsNull() && node->getshapeId() < 1)
2013         {
2014           const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2015           meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2016         }
2017       }
2018     }
2019     if ( nodes.size() != elem.GetNP() )
2020     {
2021       if ( comment.empty() )
2022         comment << "Invalid netgen 2d element #" << i;
2023       continue; // bad node ids
2024     }
2025     SMDS_MeshFace* face = NULL;
2026     switch (elem.GetType())
2027     {
2028     case netgen::TRIG:
2029       if ( quadHelper ) // final mesh must be quadratic
2030         face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2031       else
2032         face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2033       break;
2034     case netgen::QUAD:
2035       if ( quadHelper ) // final mesh must be quadratic
2036         face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2037       else
2038         face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2039       // exclude qudrangle elements from computation of 3D mesh
2040       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2041       break;
2042     case netgen::TRIG6:
2043       nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2044       nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2045       nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2046       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2047       break;
2048     case netgen::QUAD8:
2049       nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2050       nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2051       nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2052       nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2053       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2054                              nodes[4],nodes[7],nodes[5],nodes[6]);
2055       // exclude qudrangle elements from computation of 3D mesh
2056       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2057       break;
2058     default:
2059       MESSAGE("NETGEN created a face of unexpected type, ignoring");
2060       continue;
2061     }
2062     if (!face)
2063     {
2064       if ( comment.empty() ) comment << "Cannot create a mesh face";
2065       MESSAGE("Cannot create a mesh face");
2066       nbSeg = nbFac = nbVol = 0;
2067       break;
2068     }
2069     if (!aFace.IsNull())
2070       meshDS->SetMeshElementOnShape(face, aFace);
2071   }
2072
2073   // ------------------
2074   // Create tetrahedra
2075   // ------------------
2076
2077   for (i = 1; i <= nbVol; ++i)
2078   {
2079     const netgen::Element& elem = ngMesh.VolumeElement(i);      
2080     int aSolidInd = elem.GetIndex();
2081     TopoDS_Solid aSolid;
2082     if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
2083       aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2084     nodes.clear();
2085     for (int j=1; j <= elem.GetNP(); ++j)
2086     {
2087       int pind = elem.PNum(j);
2088       if ( pind < 1 || pind >= nodeVec.size() )
2089         break;
2090       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2091       {
2092         nodes.push_back(node);
2093         if ( !aSolid.IsNull() && node->getshapeId() < 1 )
2094           meshDS->SetNodeInVolume(node, aSolid);
2095       }
2096     }
2097     if ( nodes.size() != elem.GetNP() )
2098     {
2099       if ( comment.empty() )
2100         comment << "Invalid netgen 3d element #" << i;
2101       continue;
2102     }
2103     SMDS_MeshVolume* vol = NULL;
2104     switch (elem.GetType())
2105     {
2106     case netgen::TET:
2107       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2108       break;
2109     case netgen::TET10:
2110       nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2111       nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2112       nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2113       nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2114       nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2115       nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2116       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2117                               nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2118       break;
2119     default:
2120       MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2121       continue;
2122     }
2123     if (!vol)
2124     {
2125       if ( comment.empty() ) comment << "Cannot create a mesh volume";
2126       MESSAGE("Cannot create a mesh volume");
2127       nbSeg = nbFac = nbVol = 0;
2128       break;
2129     }
2130     if (!aSolid.IsNull())
2131       meshDS->SetMeshElementOnShape(vol, aSolid);
2132   }
2133   return comment.empty() ? 0 : 1;
2134 }
2135
2136 namespace
2137 {
2138   //================================================================================
2139   /*!
2140    * \brief Restrict size of elements on the given edge 
2141    */
2142   //================================================================================
2143
2144   void setLocalSize(const TopoDS_Edge& edge,
2145                     double             size,
2146                     netgen::Mesh&      mesh)
2147   {
2148     const int nb = 1000;
2149     Standard_Real u1, u2;
2150     Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
2151     if ( curve.IsNull() )
2152     {
2153       TopoDS_Iterator vIt( edge );
2154       if ( !vIt.More() ) return;
2155       gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
2156       NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2157     }
2158     else
2159     {
2160       Standard_Real delta = (u2-u1)/nb;
2161       for(int i=0; i<nb; i++)
2162       {
2163         Standard_Real u = u1 + delta*i;
2164         gp_Pnt p = curve->Value(u);
2165         NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
2166         netgen::Point3d pi(p.X(), p.Y(), p.Z());
2167         double resultSize = mesh.GetH(pi);
2168         if ( resultSize - size > 0.1*size )
2169           // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
2170           NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
2171       }
2172     }
2173   }
2174
2175   //================================================================================
2176   /*!
2177    * \brief Convert error into text
2178    */
2179   //================================================================================
2180
2181   std::string text(int err)
2182   {
2183     if ( !err )
2184       return string("");
2185     return
2186       SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2187   }
2188
2189   //================================================================================
2190   /*!
2191    * \brief Convert exception into text
2192    */
2193   //================================================================================
2194
2195   std::string text(Standard_Failure& ex)
2196   {
2197     SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2198     str << " at " << netgen::multithread.task
2199         << ": " << ex.DynamicType()->Name();
2200     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2201       str << ": " << ex.GetMessageString();
2202     return str;
2203   }
2204   //================================================================================
2205   /*!
2206    * \brief Convert exception into text
2207    */
2208   //================================================================================
2209
2210   std::string text(netgen::NgException& ex)
2211   {
2212     SMESH_Comment str("NgException");
2213     if ( strlen( netgen::multithread.task ) > 0 )
2214       str << " at " << netgen::multithread.task;
2215     str << ": " << ex.What();
2216     return str;
2217   }
2218
2219   //================================================================================
2220   /*!
2221    * \brief Looks for triangles lying on a SOLID
2222    */
2223   //================================================================================
2224
2225   bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2226                           SMESH_subMesh*                       solidSM )
2227   {
2228     TopTools_IndexedMapOfShape solidSubs;
2229     TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2230     SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2231
2232     list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2233     for ( ; e != elems.end(); ++e )
2234     {
2235       const SMDS_MeshElement* elem = *e;
2236       // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2237       //   continue;
2238       int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2239       SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2240       while ( nIt->more() )
2241       {
2242         const SMDS_MeshNode* n = nIt->next();
2243         const TopoDS_Shape&  s = mesh->IndexToShape( n->getshapeId() );
2244         nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2245         if ( nbNodesOnSolid > 2 ||
2246              nbNodesOnSolid == nbNodes)
2247           return true;
2248       }
2249     }
2250     return false;
2251   }
2252
2253   const double edgeMeshingTime = 0.001;
2254   const double faceMeshingTime = 0.019;
2255   const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2256   const double faceOptimizTime = 0.06;
2257   const double voluMeshingTime = 0.15;
2258   const double volOptimizeTime = 0.77;
2259 }
2260
2261 //=============================================================================
2262 /*!
2263  * Here we are going to use the NETGEN mesher
2264  */
2265 //=============================================================================
2266
2267 bool NETGENPlugin_Mesher::Compute()
2268 {
2269   NETGENPlugin_NetgenLibWrapper ngLib;
2270
2271   netgen::MeshingParameters& mparams = netgen::mparam;
2272   MESSAGE("Compute with:\n"
2273           " max size = " << mparams.maxh << "\n"
2274           " segments per edge = " << mparams.segmentsperedge);
2275   MESSAGE("\n"
2276           " growth rate = " << mparams.grading << "\n"
2277           " elements per radius = " << mparams.curvaturesafety << "\n"
2278           " second order = " << mparams.secondorder << "\n"
2279           " quad allowed = " << mparams.quad << "\n"
2280           " surface curvature = " << mparams.uselocalh << "\n"
2281           " fuse edges = " << netgen::merge_solids);
2282
2283   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2284   SMESH_MesherHelper quadHelper( *_mesh );
2285   quadHelper.SetIsQuadratic( mparams.secondorder );
2286
2287   static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( _ngMesh, debugFile )
2288                                                  while debugging netgen */
2289   // -------------------------
2290   // Prepare OCC geometry
2291   // -------------------------
2292
2293   netgen::OCCGeometry occgeo;
2294   list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2295   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2296   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2297   _occgeom = &occgeo;
2298
2299   _totalTime = edgeFaceMeshingTime;
2300   if ( _optimize )
2301     _totalTime += faceOptimizTime;
2302   if ( _isVolume )
2303     _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2304   double doneTime = 0;
2305   _ticTime = -1;
2306   _progressTic = 1;
2307   _curShapeIndex = -1;
2308
2309   // -------------------------
2310   // Generate the mesh
2311   // -------------------------
2312
2313   _ngMesh = NULL;
2314   NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2315
2316   SMESH_Comment comment;
2317   int err = 0;
2318
2319   // vector of nodes in which node index == netgen ID
2320   vector< const SMDS_MeshNode* > nodeVec;
2321   
2322   {
2323     // ----------------
2324     // compute 1D mesh
2325     // ----------------
2326     if ( _simpleHyp )
2327     {
2328       // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2329       mparams.uselocalh = false;
2330       mparams.grading = 0.8; // not limitited size growth
2331
2332       if ( _simpleHyp->GetNumberOfSegments() )
2333         // nb of segments
2334         mparams.maxh = occgeo.boundingbox.Diam();
2335       else
2336         // segment length
2337         mparams.maxh = _simpleHyp->GetLocalLength();
2338     }
2339
2340     if ( mparams.maxh == 0.0 )
2341       mparams.maxh = occgeo.boundingbox.Diam();
2342     if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2343       mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2344
2345     // Local size on faces
2346     occgeo.face_maxh = mparams.maxh;
2347
2348     // Let netgen create _ngMesh and calculate element size on not meshed shapes
2349 #ifndef NETGEN_V5
2350     char *optstr = 0;
2351 #endif
2352     int startWith = netgen::MESHCONST_ANALYSE;
2353     int endWith   = netgen::MESHCONST_ANALYSE;
2354     try
2355     {
2356       OCC_CATCH_SIGNALS;
2357 #ifdef NETGEN_V5
2358       err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2359 #else
2360       err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2361 #endif
2362       if(netgen::multithread.terminate)
2363         return false;
2364
2365       comment << text(err);
2366     }
2367     catch (Standard_Failure& ex)
2368     {
2369       comment << text(ex);
2370     }
2371     err = 0; //- MESHCONST_ANALYSE isn't so important step
2372     if ( !_ngMesh )
2373       return false;
2374     ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2375
2376     _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2377
2378     if ( _simpleHyp )
2379     {
2380       // Pass 1D simple parameters to NETGEN
2381       // --------------------------------
2382       int      nbSeg = _simpleHyp->GetNumberOfSegments();
2383       double segSize = _simpleHyp->GetLocalLength();
2384       for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2385       {
2386         const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2387         if ( nbSeg )
2388           segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2389         setLocalSize( e, segSize, *_ngMesh );
2390       }
2391     }
2392     else // if ( ! _simpleHyp )
2393     {
2394       // Local size on vertices and edges
2395       // --------------------------------
2396       for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2397       {
2398         int key = (*it).first;
2399         double hi = (*it).second;
2400         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2401         const TopoDS_Edge& e = TopoDS::Edge(shape);
2402         setLocalSize( e, hi, *_ngMesh );
2403       }
2404       for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2405       {
2406         int key = (*it).first;
2407         double hi = (*it).second;
2408         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2409         const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2410         gp_Pnt p = BRep_Tool::Pnt(v);
2411         NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi );
2412       }
2413       for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2414           it!=FaceId2LocalSize.end(); it++)
2415       {
2416         int key = (*it).first;
2417         double val = (*it).second;
2418         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2419         int faceNgID = occgeo.fmap.FindIndex(shape);
2420         occgeo.SetFaceMaxH(faceNgID, val);
2421         for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2422           setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh );
2423       }
2424     }
2425
2426     // Precompute internal edges (issue 0020676) in order to
2427     // add mesh on them correctly (twice) to netgen mesh
2428     if ( !err && internals.hasInternalEdges() )
2429     {
2430       // load internal shapes into OCCGeometry
2431       netgen::OCCGeometry intOccgeo;
2432       internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2433       intOccgeo.boundingbox = occgeo.boundingbox;
2434       intOccgeo.shape = occgeo.shape;
2435       intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2436       intOccgeo.face_maxh = netgen::mparam.maxh;
2437       netgen::Mesh *tmpNgMesh = NULL;
2438       try
2439       {
2440         OCC_CATCH_SIGNALS;
2441         // compute local H on internal shapes in the main mesh
2442         //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2443
2444         // let netgen create a temporary mesh
2445 #ifdef NETGEN_V5
2446         netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2447 #else
2448         netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2449 #endif
2450         if(netgen::multithread.terminate)
2451           return false;
2452
2453         // copy LocalH from the main to temporary mesh
2454         initState.transferLocalH( _ngMesh, tmpNgMesh );
2455
2456         // compute mesh on internal edges
2457         startWith = endWith = netgen::MESHCONST_MESHEDGES;
2458 #ifdef NETGEN_V5
2459         err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2460 #else
2461         err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2462 #endif
2463         comment << text(err);
2464       }
2465       catch (Standard_Failure& ex)
2466       {
2467         comment << text(ex);
2468         err = 1;
2469       }
2470       initState.restoreLocalH( tmpNgMesh );
2471
2472       // fill SMESH by netgen mesh
2473       vector< const SMDS_MeshNode* > tmpNodeVec;
2474       FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2475       err = ( err || !comment.empty() );
2476
2477       nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2478     }
2479
2480     // Fill _ngMesh with nodes and segments of computed submeshes
2481     if ( !err )
2482     {
2483       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2484                 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
2485     }
2486     initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2487
2488     // Compute 1d mesh
2489     if (!err)
2490     {
2491       startWith = endWith = netgen::MESHCONST_MESHEDGES;
2492       try
2493       {
2494         OCC_CATCH_SIGNALS;
2495 #ifdef NETGEN_V5
2496         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2497 #else
2498         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2499 #endif
2500         if(netgen::multithread.terminate)
2501           return false;
2502
2503         comment << text(err);
2504       }
2505       catch (Standard_Failure& ex)
2506       {
2507         comment << text(ex);
2508         err = 1;
2509       }
2510     }
2511     if ( _isVolume )
2512       _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
2513
2514     mparams.uselocalh = true; // restore as it is used at surface optimization
2515
2516     // ---------------------
2517     // compute surface mesh
2518     // ---------------------
2519     if (!err)
2520     {
2521       // Pass 2D simple parameters to NETGEN
2522       if ( _simpleHyp ) {
2523         if ( double area = _simpleHyp->GetMaxElementArea() ) {
2524           // face area
2525           mparams.maxh = sqrt(2. * area/sqrt(3.0));
2526           mparams.grading = 0.4; // moderate size growth
2527         }
2528         else {
2529           // length from edges
2530           if ( _ngMesh->GetNSeg() ) {
2531             double edgeLength = 0;
2532             TopTools_MapOfShape visitedEdges;
2533             for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2534               if( visitedEdges.Add(exp.Current()) )
2535                 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2536             // we have to multiply length by 2 since for each TopoDS_Edge there
2537             // are double set of NETGEN edges, in other words, we have to
2538             // divide _ngMesh->GetNSeg() by 2.
2539             mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
2540           }
2541           else {
2542             mparams.maxh = 1000;
2543           }
2544           mparams.grading = 0.2; // slow size growth
2545         }
2546         mparams.quad = _simpleHyp->GetAllowQuadrangles();
2547         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2548         _ngMesh->SetGlobalH (mparams.maxh);
2549         netgen::Box<3> bb = occgeo.GetBoundingBox();
2550         bb.Increase (bb.Diam()/20);
2551         _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2552       }
2553
2554       // Care of vertices internal in faces (issue 0020676)
2555       if ( internals.hasInternalVertexInFace() )
2556       {
2557         // store computed segments in SMESH in order not to create SMESH
2558         // edges for ng segments added by AddIntVerticesInFaces()
2559         FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2560         // add segments to faces with internal vertices
2561         AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
2562         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2563       }
2564
2565       // Build viscous layers
2566       if ( _isViscousLayers2D )
2567       {
2568         if ( !internals.hasInternalVertexInFace() ) {
2569           FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
2570           initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2571         }
2572         SMESH_ProxyMesh::Ptr viscousMesh;
2573         SMESH_MesherHelper   helper( *_mesh );
2574         for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2575         {
2576           const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2577           viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2578           if ( !viscousMesh )
2579             return false;
2580           // exclude from computation ng segments built on EDGEs of F
2581           for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
2582           {
2583             netgen::Segment & seg = _ngMesh->LineSegment(i);
2584             if (seg.si == faceID)
2585               seg.si = 0;
2586           }
2587           // add new segments to _ngMesh instead of excluded ones
2588           helper.SetSubShape( F );
2589           TSideVector wires =
2590             StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2591                                                error, viscousMesh );
2592           error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
2593
2594           if ( !error ) error = SMESH_ComputeError::New();
2595         }
2596         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2597       }
2598
2599       // Let netgen compute 2D mesh
2600       startWith = netgen::MESHCONST_MESHSURFACE;
2601       endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2602       try
2603       {
2604         OCC_CATCH_SIGNALS;
2605 #ifdef NETGEN_V5
2606         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2607 #else
2608         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2609 #endif
2610         if(netgen::multithread.terminate)
2611           return false;
2612
2613         comment << text (err);
2614       }
2615       catch (Standard_Failure& ex)
2616       {
2617         comment << text(ex);
2618         //err = 1; -- try to make volumes anyway
2619       }
2620       catch (netgen::NgException exc)
2621       {
2622         comment << text(exc);
2623         //err = 1; -- try to make volumes anyway
2624       }
2625     }
2626     if ( _isVolume )
2627     {
2628       doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
2629       _ticTime = doneTime / _totalTime / _progressTic;
2630     }
2631     // ---------------------
2632     // generate volume mesh
2633     // ---------------------
2634     // Fill _ngMesh with nodes and faces of computed 2D submeshes
2635     if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2636     {
2637       // load SMESH with computed segments and faces
2638       FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2639
2640       // compute pyramids on quadrangles
2641       SMESH_ProxyMesh::Ptr proxyMesh;
2642       if ( _mesh->NbQuadrangles() > 0 )
2643         for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2644         {
2645           StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2646           proxyMesh.reset( Adaptor );
2647
2648           int nbPyrams = _mesh->NbPyramids();
2649           Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2650           if ( nbPyrams != _mesh->NbPyramids() )
2651           {
2652             list< SMESH_subMesh* > quadFaceSM;
2653             for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2654               if ( Adaptor->GetProxySubMesh( face.Current() ))
2655               {
2656                 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2657                 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2658               }
2659             FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh);
2660           }
2661         }
2662       // fill _ngMesh with faces of sub-meshes
2663       err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
2664       initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2665       //toPython( _ngMesh, "/tmp/ngPython.py");
2666     }
2667     if (!err && _isVolume)
2668     {
2669       // Pass 3D simple parameters to NETGEN
2670       const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2671         dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2672       if ( simple3d ) {
2673         if ( double vol = simple3d->GetMaxElementVolume() ) {
2674           // max volume
2675           mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2676           mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2677         }
2678         else {
2679           // length from faces
2680           mparams.maxh = _ngMesh->AverageH();
2681         }
2682         _ngMesh->SetGlobalH (mparams.maxh);
2683         mparams.grading = 0.4;
2684 #ifdef NETGEN_V5
2685         _ngMesh->CalcLocalH(mparams.grading);
2686 #else
2687         _ngMesh->CalcLocalH();
2688 #endif
2689       }
2690       // Care of vertices internal in solids and internal faces (issue 0020676)
2691       if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2692       {
2693         // store computed faces in SMESH in order not to create SMESH
2694         // faces for ng faces added here
2695         FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2696         // add ng faces to solids with internal vertices
2697         AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
2698         // duplicate mesh faces on internal faces
2699         FixIntFaces( occgeo, *_ngMesh, internals );
2700         initState = NETGENPlugin_ngMeshInfo(_ngMesh);
2701       }
2702       // Let netgen compute 3D mesh
2703       startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2704       try
2705       {
2706         OCC_CATCH_SIGNALS;
2707 #ifdef NETGEN_V5
2708         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2709 #else
2710         err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2711 #endif
2712         if(netgen::multithread.terminate)
2713           return false;
2714
2715         if ( comment.empty() ) // do not overwrite a previos error
2716           comment << text(err);
2717       }
2718       catch (Standard_Failure& ex)
2719       {
2720         if ( comment.empty() ) // do not overwrite a previos error
2721           comment << text(ex);
2722         err = 1;
2723       }
2724       catch (netgen::NgException exc)
2725       {
2726         if ( comment.empty() ) // do not overwrite a previos error
2727           comment << text(exc);
2728         err = 1;
2729       }
2730       _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
2731
2732       // Let netgen optimize 3D mesh
2733       if ( !err && _optimize )
2734       {
2735         startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2736         try
2737         {
2738           OCC_CATCH_SIGNALS;
2739 #ifdef NETGEN_V5
2740           err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2741 #else
2742           err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2743 #endif
2744           if(netgen::multithread.terminate)
2745             return false;
2746
2747           if ( comment.empty() ) // do not overwrite a previos error
2748             comment << text(err);
2749         }
2750         catch (Standard_Failure& ex)
2751         {
2752           if ( comment.empty() ) // do not overwrite a previos error
2753             comment << text(ex);
2754         }
2755         catch (netgen::NgException exc)
2756         {
2757           if ( comment.empty() ) // do not overwrite a previos error
2758             comment << text(exc);
2759         }
2760       }
2761     }
2762     if (!err && mparams.secondorder > 0)
2763     {
2764       try
2765       {
2766         OCC_CATCH_SIGNALS;
2767         if ( !meshedSM[ MeshDim_1D ].empty() )
2768         {
2769           // remove segments not attached to geometry (IPAL0052479)
2770           for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
2771           {
2772             const netgen::Segment & seg = _ngMesh->LineSegment (i);
2773             if ( seg.epgeominfo[ 0 ].edgenr == 0 )
2774               _ngMesh->DeleteSegment( i );
2775           }
2776           _ngMesh->Compress();
2777         }
2778         // convert to quadratic
2779         netgen::OCCRefinementSurfaces ref (occgeo);
2780         ref.MakeSecondOrder (*_ngMesh);
2781
2782         // care of elements already loaded to SMESH
2783         // if ( initState._nbSegments > 0 )
2784         //   makeQuadratic( occgeo.emap, _mesh );
2785         // if ( initState._nbFaces > 0 )
2786         //   makeQuadratic( occgeo.fmap, _mesh );
2787       }
2788       catch (Standard_Failure& ex)
2789       {
2790         if ( comment.empty() ) // do not overwrite a previos error
2791           comment << "Exception in netgen at passing to 2nd order ";
2792       }
2793       catch (netgen::NgException exc)
2794       {
2795         if ( comment.empty() ) // do not overwrite a previos error
2796           comment << exc.What();
2797       }
2798     }
2799   }
2800
2801   _ticTime = 0.98 / _progressTic;
2802
2803   int nbNod = _ngMesh->GetNP();
2804   int nbSeg = _ngMesh->GetNSeg();
2805   int nbFac = _ngMesh->GetNSE();
2806   int nbVol = _ngMesh->GetNE();
2807   bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2808
2809   MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2810           ", nb nodes: "    << nbNod <<
2811           ", nb segments: " << nbSeg <<
2812           ", nb faces: "    << nbFac <<
2813           ", nb volumes: "  << nbVol);
2814
2815   // Feed back the SMESHDS with the generated Nodes and Elements
2816   if ( true /*isOK*/ ) // get whatever built
2817   {
2818     FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
2819
2820     if ( quadHelper.GetIsQuadratic() ) // remove free nodes
2821       for ( size_t i = 0; i < nodeVec.size(); ++i )
2822         if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
2823           _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
2824   }
2825   SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2826   if ( readErr && !readErr->myBadElements.empty() )
2827   {
2828     error = readErr;
2829     if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
2830     comment += readErr->myComment;
2831   }
2832   if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2833     error->myName = COMPERR_ALGO_FAILED;
2834   if ( !comment.empty() )
2835     error->myComment = comment;
2836
2837   // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2838   // appear if the geometry contains coincident sub-shape due
2839   // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2840   const int nbMaps = 2;
2841   const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2842     { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2843   for ( int iMap = 0; iMap < nbMaps; ++iMap )
2844     for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2845       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2846         if ( !sm->IsMeshComputed() )
2847           sm->SetIsAlwaysComputed( true );
2848
2849   // set bad compute error to subshapes of all failed sub-shapes
2850   if ( !error->IsOK() )
2851   {
2852     bool pb2D = false, pb3D = false;
2853     for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2854       int status = occgeo.facemeshstatus[i-1];
2855       if (status == 1 ) continue;
2856       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2857         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2858         if ( !smError || smError->IsOK() ) {
2859           if ( status == -1 )
2860             smError.reset( new SMESH_ComputeError( *error ));
2861           else
2862             smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2863           if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2864             smError->myName = COMPERR_WARNING;
2865         }
2866         pb2D = pb2D || smError->IsKO();
2867       }
2868     }
2869     if ( !pb2D ) // all faces are OK
2870       for (int i = 1; i <= occgeo.somap.Extent(); i++)
2871         if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2872         {
2873           bool smComputed = nbVol && !sm->IsEmpty();
2874           if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2875           {
2876             int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2877             SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2878             smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2879           }
2880           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2881           if ( !smComputed && ( !smError || smError->IsOK() ))
2882           {
2883             smError.reset( new SMESH_ComputeError( *error ));
2884             if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2885             {
2886               smError->myName = COMPERR_WARNING;
2887             }
2888             else if ( !smError->myBadElements.empty() ) // bad surface mesh
2889             {
2890               if ( !hasBadElemOnSolid( smError->myBadElements, sm ))
2891                 smError.reset();
2892             }
2893           }
2894           pb3D = pb3D || ( smError && smError->IsKO() );
2895         }
2896     if ( !pb2D && !pb3D )
2897       err = 0; // no fatal errors, only warnings
2898   }
2899
2900   ngLib._isComputeOk = !err;
2901
2902   return !err;
2903 }
2904
2905 //=============================================================================
2906 /*!
2907  * Evaluate
2908  */
2909 //=============================================================================
2910 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2911 {
2912   netgen::MeshingParameters& mparams = netgen::mparam;
2913
2914
2915   // -------------------------
2916   // Prepare OCC geometry
2917   // -------------------------
2918   netgen::OCCGeometry occgeo;
2919   list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2920   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2921   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2922
2923   bool tooManyElems = false;
2924   const int hugeNb = std::numeric_limits<int>::max() / 100;
2925
2926   // ----------------
2927   // evaluate 1D 
2928   // ----------------
2929   // pass 1D simple parameters to NETGEN
2930   if ( _simpleHyp )
2931   {
2932     // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2933     mparams.uselocalh = false;
2934     mparams.grading = 0.8; // not limitited size growth
2935
2936     if ( _simpleHyp->GetNumberOfSegments() )
2937       // nb of segments
2938       mparams.maxh = occgeo.boundingbox.Diam();
2939     else
2940       // segment length
2941       mparams.maxh = _simpleHyp->GetLocalLength();
2942   }
2943
2944   if ( mparams.maxh == 0.0 )
2945     mparams.maxh = occgeo.boundingbox.Diam();
2946   if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2947     mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2948
2949   // let netgen create _ngMesh and calculate element size on not meshed shapes
2950   NETGENPlugin_NetgenLibWrapper ngLib;
2951   netgen::Mesh *ngMesh = NULL;
2952 #ifndef NETGEN_V5
2953   char *optstr = 0;
2954 #endif
2955   int startWith = netgen::MESHCONST_ANALYSE;
2956   int endWith   = netgen::MESHCONST_MESHEDGES;
2957 #ifdef NETGEN_V5
2958   int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
2959 #else
2960   int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2961 #endif
2962
2963   if(netgen::multithread.terminate)
2964     return false;
2965
2966   ngLib.setMesh(( Ng_Mesh*) ngMesh );
2967   if (err) {
2968     if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2969       sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2970     return false;
2971   }
2972   if ( _simpleHyp )
2973   {
2974     // Pass 1D simple parameters to NETGEN
2975     // --------------------------------
2976     int      nbSeg = _simpleHyp->GetNumberOfSegments();
2977     double segSize = _simpleHyp->GetLocalLength();
2978     for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2979     {
2980       const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2981       if ( nbSeg )
2982         segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2983       setLocalSize( e, segSize, *ngMesh );
2984     }
2985   }
2986   else // if ( ! _simpleHyp )
2987   {
2988     // Local size on vertices and edges
2989     // --------------------------------
2990     for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2991     {
2992       int key = (*it).first;
2993       double hi = (*it).second;
2994       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2995       const TopoDS_Edge& e = TopoDS::Edge(shape);
2996       setLocalSize( e, hi, *ngMesh );
2997     }
2998     for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2999     {
3000       int key = (*it).first;
3001       double hi = (*it).second;
3002       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3003       const TopoDS_Vertex& v = TopoDS::Vertex(shape);
3004       gp_Pnt p = BRep_Tool::Pnt(v);
3005       NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
3006     }
3007     for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
3008         it!=FaceId2LocalSize.end(); it++)
3009     {
3010       int key = (*it).first;
3011       double val = (*it).second;
3012       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
3013       int faceNgID = occgeo.fmap.FindIndex(shape);
3014       occgeo.SetFaceMaxH(faceNgID, val);
3015       for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
3016         setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
3017     }
3018   }
3019   // calculate total nb of segments and length of edges
3020   double fullLen = 0.0;
3021   int fullNbSeg = 0;
3022   int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3023   TopTools_DataMapOfShapeInteger Edge2NbSeg;
3024   for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3025   {
3026     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3027     if( !Edge2NbSeg.Bind(E,0) )
3028       continue;
3029
3030     double aLen = SMESH_Algo::EdgeLength(E);
3031     fullLen += aLen;
3032
3033     vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3034     if ( aVec.empty() )
3035       aVec.resize( SMDSEntity_Last, 0);
3036     else
3037       fullNbSeg += aVec[ entity ];
3038   }
3039
3040   // store nb of segments computed by Netgen
3041   NCollection_Map<Link> linkMap;
3042   for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3043   {
3044     const netgen::Segment& seg = ngMesh->LineSegment(i);
3045     Link link(seg[0], seg[1]);
3046     if ( !linkMap.Add( link )) continue;
3047     int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3048     if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3049     {
3050       vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3051       aVec[ entity ]++;
3052     }
3053   }
3054   // store nb of nodes on edges computed by Netgen
3055   TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3056   for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3057   {
3058     vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3059     if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3060       aVec[SMDSEntity_Node] = mparams.secondorder > 0  ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3061
3062     fullNbSeg += aVec[ entity ];
3063     Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3064   }
3065   if ( fullNbSeg == 0 )
3066     return false;
3067
3068   // ----------------
3069   // evaluate 2D 
3070   // ----------------
3071   if ( _simpleHyp ) {
3072     if ( double area = _simpleHyp->GetMaxElementArea() ) {
3073       // face area
3074       mparams.maxh = sqrt(2. * area/sqrt(3.0));
3075       mparams.grading = 0.4; // moderate size growth
3076     }
3077     else {
3078       // length from edges
3079       mparams.maxh = fullLen/fullNbSeg;
3080       mparams.grading = 0.2; // slow size growth
3081     }
3082   }
3083   mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3084   mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3085
3086   for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3087   {
3088     TopoDS_Face F = TopoDS::Face( exp.Current() );
3089     SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3090     GProp_GProps G;
3091     BRepGProp::SurfaceProperties(F,G);
3092     double anArea = G.Mass();
3093     tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3094     int nb1d = 0;
3095     if ( !tooManyElems )
3096     {
3097       TopTools_MapOfShape egdes;
3098       for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3099         if ( egdes.Add( exp1.Current() ))
3100           nb1d += Edge2NbSeg.Find(exp1.Current());
3101     }
3102     int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3103     int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3104
3105     vector<int> aVec(SMDSEntity_Last, 0);
3106     if( mparams.secondorder > 0 ) {
3107       int nb1d_in = (nbFaces*3 - nb1d) / 2;
3108       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3109       aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3110     }
3111     else {
3112       aVec[SMDSEntity_Node] = Max ( nbNodes, 0  );
3113       aVec[SMDSEntity_Triangle] = nbFaces;
3114     }
3115     aResMap[sm].swap(aVec);
3116   }
3117
3118   // ----------------
3119   // evaluate 3D
3120   // ----------------
3121   if(_isVolume) {
3122     // pass 3D simple parameters to NETGEN
3123     const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3124       dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3125     if ( simple3d ) {
3126       if ( double vol = simple3d->GetMaxElementVolume() ) {
3127         // max volume
3128         mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3129         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3130       }
3131       else {
3132         // using previous length from faces
3133       }
3134       mparams.grading = 0.4;
3135       mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3136     }
3137     GProp_GProps G;
3138     BRepGProp::VolumeProperties(_shape,G);
3139     double aVolume = G.Mass();
3140     double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3141     tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3142     int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3143     int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3144     vector<int> aVec(SMDSEntity_Last, 0 );
3145     if ( tooManyElems ) // avoid FPE
3146     {
3147       aVec[SMDSEntity_Node] = hugeNb;
3148       aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3149     }
3150     else
3151     {
3152       if( mparams.secondorder > 0 ) {
3153         aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3154         aVec[SMDSEntity_Quad_Tetra] = nbVols;
3155       }
3156       else {
3157         aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3158         aVec[SMDSEntity_Tetra] = nbVols;
3159       }
3160     }
3161     SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3162     aResMap[sm].swap(aVec);
3163   }
3164
3165   return true;
3166 }
3167
3168 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3169                                         const int *       algoProgressTic,
3170                                         const double *    algoProgress) const
3171 {
3172   ((int&) _progressTic ) = *algoProgressTic + 1;
3173
3174   if ( !_occgeom ) return 0;
3175
3176   double progress = -1;
3177   if ( !_isVolume )
3178   {
3179     if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3180     {
3181       ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3182     }
3183     else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3184     {
3185       int doneShapeIndex = -1;
3186       while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3187               _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3188         doneShapeIndex++;
3189       if ( doneShapeIndex+1 != _curShapeIndex )
3190       {
3191         ((int&) _curShapeIndex) = doneShapeIndex+1;
3192         double    doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3193         double         doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3194         ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
3195         // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3196         //      << " " << doneTime / _totalTime / _progressTic << endl;
3197       }
3198     }
3199   }
3200   else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3201   {
3202     int curShapeIndex = _curShapeIndex;
3203     if ( _ngMesh->GetNE() > 0 )
3204     {
3205       netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3206       curShapeIndex = el.GetIndex();
3207     }
3208     if ( curShapeIndex != _curShapeIndex )
3209     {
3210       ((int&) _curShapeIndex) = curShapeIndex;
3211       double    doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3212       double         doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3213       ((double&)    _ticTime) = doneTime / _totalTime / _progressTic;
3214       // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3215       //      << " " << doneTime / _totalTime / _progressTic << endl;
3216     }
3217   }
3218   if ( _ticTime > 0 )
3219     progress  = Max( *algoProgressTic * _ticTime, *algoProgress );
3220   if ( progress > 0 )
3221   {
3222     ((int&) *algoProgressTic )++;
3223     ((double&) *algoProgress) = progress;
3224   }
3225   //cout << progress << " "  << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3226
3227   return Min( progress, 0.99 );
3228 }
3229
3230 //================================================================================
3231 /*!
3232  * \brief Remove "test.out" and "problemfaces" files in current directory
3233  */
3234 //================================================================================
3235
3236 void NETGENPlugin_Mesher::RemoveTmpFiles()
3237 {
3238   bool rm =  SMESH_File("test.out").remove() ;
3239 #ifndef WIN32
3240   if (rm && netgen::testout)
3241   {
3242     delete netgen::testout;
3243     netgen::testout = 0;
3244   }
3245 #endif
3246   SMESH_File("problemfaces").remove();
3247   SMESH_File("occmesh.rep").remove();
3248 }
3249
3250 //================================================================================
3251 /*!
3252  * \brief Read mesh entities preventing successful computation from "test.out" file
3253  */
3254 //================================================================================
3255
3256 SMESH_ComputeErrorPtr
3257 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3258 {
3259   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
3260     (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
3261   SMESH_File file("test.out");
3262   vector<int> two(2);
3263   vector<int> three1(3), three2(3);
3264   const char* badEdgeStr = " multiple times in surface mesh";
3265   const int   badEdgeStrLen = strlen( badEdgeStr );
3266
3267   while( !file.eof() )
3268   {
3269     if ( strncmp( file, "Edge ", 5 ) == 0 &&
3270          file.getInts( two ) &&
3271          strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3272          two[0] < nodeVec.size() && two[1] < nodeVec.size())
3273     {
3274       err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3275       file += badEdgeStrLen;
3276     }
3277     else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3278     {
3279 // Intersecting: 
3280 // openelement 18 with open element 126
3281 // 41  36  38  
3282 // 69  70  72
3283       file.getLine();
3284       const char* pos = file;
3285       bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3286       ok = ok && file.getInts( two );
3287       ok = ok && file.getInts( three1 );
3288       ok = ok && file.getInts( three2 );
3289       for ( int i = 0; ok && i < 3; ++i )
3290         ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
3291       for ( int i = 0; ok && i < 3; ++i ) 
3292         ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
3293       if ( ok )
3294       {
3295         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3296                                                             nodeVec[ three1[1]],
3297                                                             nodeVec[ three1[2]]));
3298         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3299                                                             nodeVec[ three2[1]],
3300                                                             nodeVec[ three2[2]]));
3301         err->myComment = "Intersecting triangles";
3302       }
3303       else
3304       {
3305         file.setPos( pos );
3306       }
3307     }
3308     else
3309     {
3310       ++file;
3311     }
3312   }
3313
3314 #ifdef _DEBUG_
3315   size_t nbBadElems = err->myBadElements.size();
3316   nbBadElems = 0;
3317 #endif
3318
3319   return err;
3320 }
3321
3322 //================================================================================
3323 /*!
3324  * \brief Write a python script creating an equivalent SALOME mesh.
3325  * This is useful to see what mesh is passed as input for the next step of mesh
3326  * generation (of mesh of higher dimension)
3327  */
3328 //================================================================================
3329
3330 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
3331                                     const std::string&  pyFile)
3332 {
3333   ofstream outfile(pyFile.c_str(), ios::out);
3334   if ( !outfile ) return;
3335
3336   outfile << "import SMESH" << endl
3337           << "from salome.smesh import smeshBuilder" << endl
3338           << "smesh = smeshBuilder.New(salome.myStudy)" << endl
3339           << "mesh = smesh.Mesh()" << endl << endl;
3340
3341   using namespace netgen;
3342   PointIndex pi;
3343   for (pi = PointIndex::BASE; 
3344        pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3345   {
3346     outfile << "mesh.AddNode( ";
3347     outfile << (*ngMesh)[pi](0) << ", ";
3348     outfile << (*ngMesh)[pi](1) << ", ";
3349     outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
3350   }
3351
3352   int nbDom = ngMesh->GetNDomains();
3353   for ( int i = 0; i < nbDom; ++i )
3354     outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
3355
3356   SurfaceElementIndex sei;
3357   for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3358   {
3359     outfile << "mesh.AddFace([ ";
3360     Element2d sel = (*ngMesh)[sei];
3361     for (int j = 0; j < sel.GetNP(); j++)
3362       outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3363     if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3364     outfile << endl;
3365
3366     if ((*ngMesh)[sei].GetIndex())
3367     {
3368       if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3369         outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
3370       if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3371         outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
3372     }
3373   }
3374
3375   for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3376   {
3377     Element el = (*ngMesh)[ei];
3378     outfile << "mesh.AddVolume([ ";
3379     for (int j = 0; j < el.GetNP(); j++)
3380       outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3381     outfile << endl;
3382   }
3383
3384   for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3385   {
3386     const Segment & seg = ngMesh->LineSegment (i);
3387     outfile << "mesh.AddEdge([ "
3388             << seg[0] << ", "
3389             << seg[1] << " ])" << endl;
3390   }
3391   cout << "Write " << pyFile << endl;
3392 }
3393
3394 //================================================================================
3395 /*!
3396  * \brief Constructor of NETGENPlugin_ngMeshInfo
3397  */
3398 //================================================================================
3399
3400 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3401   _copyOfLocalH(0)
3402 {
3403   if ( ngMesh )
3404   {
3405     _nbNodes    = ngMesh->GetNP();
3406     _nbSegments = ngMesh->GetNSeg();
3407     _nbFaces    = ngMesh->GetNSE();
3408     _nbVolumes  = ngMesh->GetNE();
3409   }
3410   else
3411   {
3412     _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3413   }
3414 }
3415
3416 //================================================================================
3417 /*!
3418  * \brief Copy LocalH member from one netgen mesh to another
3419  */
3420 //================================================================================
3421
3422 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3423                                               netgen::Mesh* toMesh )
3424 {
3425   if ( !fromMesh->LocalHFunctionGenerated() ) return;
3426   if ( !toMesh->LocalHFunctionGenerated() )
3427 #ifdef NETGEN_V5
3428     toMesh->CalcLocalH(netgen::mparam.grading);
3429 #else
3430     toMesh->CalcLocalH();
3431 #endif
3432
3433   const size_t size = sizeof( netgen::LocalH );
3434   _copyOfLocalH = new char[ size ];
3435   memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3436   memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3437 }
3438
3439 //================================================================================
3440 /*!
3441  * \brief Restore LocalH member of a netgen mesh
3442  */
3443 //================================================================================
3444
3445 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3446 {
3447   if ( _copyOfLocalH )
3448   {
3449     const size_t size = sizeof( netgen::LocalH );
3450     memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3451     delete [] _copyOfLocalH;
3452     _copyOfLocalH = 0;
3453   }
3454 }
3455
3456 //================================================================================
3457 /*!
3458  * \brief Find "internal" sub-shapes
3459  */
3460 //================================================================================
3461
3462 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh&         mesh,
3463                                                 const TopoDS_Shape& shape,
3464                                                 bool                is3D )
3465   : _mesh( mesh ), _is3D( is3D )
3466 {
3467   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3468
3469   TopExp_Explorer f,e;
3470   for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3471   {
3472     int faceID = meshDS->ShapeToIndex( f.Current() );
3473
3474     // find not computed internal edges
3475
3476     for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3477       if ( e.Current().Orientation() == TopAbs_INTERNAL )
3478       {
3479         SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3480         if ( eSM->IsEmpty() )
3481         {
3482           _e2face.insert( make_pair( eSM->GetId(), faceID ));
3483           for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3484             _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3485         }
3486       }
3487
3488     // find internal vertices in a face
3489     set<int> intVV; // issue 0020850 where same vertex is twice in a face
3490     for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3491       if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3492       {
3493         int vID = meshDS->ShapeToIndex( fSub.Value() );
3494         if ( intVV.insert( vID ).second )
3495           _f2v[ faceID ].push_back( vID );
3496       }
3497
3498     if ( is3D )
3499     {
3500       // find internal faces and their subshapes where nodes are to be doubled
3501       //  to make a crack with non-sewed borders
3502
3503       if ( f.Current().Orientation() == TopAbs_INTERNAL )
3504       {
3505         _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3506
3507         // egdes
3508         list< TopoDS_Shape > edges;
3509         for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3510           if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3511           {
3512             _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3513             edges.push_back( e.Current() );
3514             // find border faces
3515             PShapeIteratorPtr fIt =
3516               SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3517             while ( const TopoDS_Shape* pFace = fIt->next() )
3518               if ( !pFace->IsSame( f.Current() ))
3519                 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3520           }
3521         // vertices
3522         // we consider vertex internal if it is shared by more than one internal edge
3523         list< TopoDS_Shape >::iterator edge = edges.begin();
3524         for ( ; edge != edges.end(); ++edge )
3525           for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3526           {
3527             set<int> internalEdges;
3528             PShapeIteratorPtr eIt =
3529               SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3530             while ( const TopoDS_Shape* pEdge = eIt->next() )
3531             {
3532               int edgeID = meshDS->ShapeToIndex( *pEdge );
3533               if ( isInternalShape( edgeID ))
3534                 internalEdges.insert( edgeID );
3535             }
3536             if ( internalEdges.size() > 1 )
3537               _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3538           }
3539       }
3540     }
3541   } // loop on geom faces
3542
3543   // find vertices internal in solids
3544   if ( is3D )
3545   {
3546     for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3547     {
3548       int soID = meshDS->ShapeToIndex( so.Current() );
3549       for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3550         if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3551           _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3552     }
3553   }
3554 }
3555
3556 //================================================================================
3557 /*!
3558  * \brief Find mesh faces on non-internal geom faces sharing internal edge
3559  * some nodes of which are to be doubled to make the second border of the "crack"
3560  */
3561 //================================================================================
3562
3563 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3564 {
3565   if ( _intShapes.empty() ) return;
3566
3567   SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3568   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3569
3570   // loop on internal geom edges
3571   set<int>::const_iterator intShapeId = _intShapes.begin();
3572   for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3573   {
3574     const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3575     if ( s.ShapeType() != TopAbs_EDGE ) continue;
3576
3577     // get internal and non-internal geom faces sharing the internal edge <s>
3578     int intFace = 0;
3579     set<int>::iterator bordFace = _borderFaces.end();
3580     PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3581     while ( const TopoDS_Shape* pFace = faces->next() )
3582     {
3583       int faceID = meshDS->ShapeToIndex( *pFace );
3584       if ( isInternalShape( faceID ))
3585         intFace = faceID;
3586       else
3587         bordFace = _borderFaces.insert( faceID ).first;
3588     }
3589     if ( bordFace == _borderFaces.end() || !intFace ) continue;
3590
3591     // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3592     set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3593     list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3594     int nbSuspectFaces = 0;
3595     SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3596     if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3597     SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3598     while ( smIt->more() )
3599     {
3600       SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3601       if ( !sm ) continue;
3602       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3603       while ( nIt->more() )
3604       {
3605         const SMDS_MeshNode* nOnEdge = nIt->next();
3606         SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3607         while ( fIt->more() )
3608         {
3609           const SMDS_MeshElement* f = fIt->next();
3610           int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3611           if ( intFaceSM->Contains( f ))
3612           {
3613             for ( int i = 0; i < nbNodes; ++i )
3614               links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3615           }
3616           else
3617           {
3618             int nbDblNodes = 0;
3619             for ( int i = 0; i < nbNodes; ++i )
3620               nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3621             if ( nbDblNodes )
3622               suspectFaces[ nbDblNodes < 2 ].push_back( f );
3623             nbSuspectFaces++;
3624           }
3625         }
3626       }
3627     }
3628     // suspectFaces[0] having link with same orientation as mesh faces on
3629     // the internal geom face are <borderElems>. suspectFaces[1] have
3630     // only one node on edge <s>, we decide on them later (at the 2nd loop)
3631     // by links of <borderElems> found at the 1st and 2nd loops
3632     set< SMESH_OrientedLink > borderLinks;
3633     for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3634     {
3635       list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3636       for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3637       {
3638         const SMDS_MeshElement* f = *fIt;
3639         bool isBorder = false, linkFound = false, borderLinkFound = false;
3640         list< SMESH_OrientedLink > faceLinks;
3641         int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3642         for ( int i = 0; i < nbNodes; ++i )
3643         {
3644           SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3645           faceLinks.push_back( link );
3646           if ( !linkFound )
3647           {
3648             set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3649             if ( foundLink != links.end() )
3650             {
3651               linkFound= true;
3652               isBorder = ( foundLink->_reversed == link._reversed );
3653               if ( !isBorder && !isPostponed ) break;
3654               faceLinks.pop_back();
3655             }
3656             else if ( isPostponed && !borderLinkFound )
3657             {
3658               foundLink = borderLinks.find( link );
3659               if ( foundLink != borderLinks.end() )
3660               {
3661                 borderLinkFound = true;
3662                 isBorder = ( foundLink->_reversed != link._reversed );
3663               }
3664             }
3665           }
3666         }
3667         if ( isBorder )
3668         {
3669           borderElems.insert( f );
3670           borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3671         }
3672         else if ( !linkFound && !borderLinkFound )
3673         {
3674           suspectFaces[1].push_back( f );
3675           if ( nbF > 2 * nbSuspectFaces )
3676             break; // dead loop protection
3677         }
3678       }
3679     }
3680   }
3681 }
3682
3683 //================================================================================
3684 /*!
3685  * \brief put internal shapes in maps and fill in submeshes to precompute
3686  */
3687 //================================================================================
3688
3689 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3690                                                TopTools_IndexedMapOfShape& emap,
3691                                                TopTools_IndexedMapOfShape& vmap,
3692                                                list< SMESH_subMesh* > smToPrecompute[])
3693 {
3694   if ( !hasInternalEdges() ) return;
3695   map<int,int>::const_iterator ev_face = _e2face.begin();
3696   for ( ; ev_face != _e2face.end(); ++ev_face )
3697   {
3698     const TopoDS_Shape& ev   = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3699     const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3700
3701     ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3702     fmap.Add( face );
3703     //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3704
3705     smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3706   }
3707 }
3708
3709 //================================================================================
3710 /*!
3711  * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3712  */
3713 //================================================================================
3714
3715 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3716                                                TopTools_IndexedMapOfShape& emap,
3717                                                list< SMESH_subMesh* >&     intFaceSM,
3718                                                list< SMESH_subMesh* >&     boundarySM)
3719 {
3720   if ( !hasInternalFaces() ) return;
3721
3722   // <fmap> and <emap> are for not yet meshed shapes
3723   // <intFaceSM> is for submeshes of faces
3724   // <boundarySM> is for meshed edges and vertices
3725
3726   intFaceSM.clear();
3727   boundarySM.clear();
3728
3729   set<int> shapeIDs ( _intShapes );
3730   if ( !_borderFaces.empty() )
3731     shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3732
3733   set<int>::const_iterator intS = shapeIDs.begin();
3734   for ( ; intS != shapeIDs.end(); ++intS )
3735   {
3736     SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3737
3738     if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3739
3740     intFaceSM.push_back( sm );
3741
3742     // add submeshes of not computed internal faces
3743     if ( !sm->IsEmpty() ) continue;
3744
3745     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3746     while ( smIt->more() )
3747     {
3748       sm = smIt->next();
3749       const TopoDS_Shape& s = sm->GetSubShape();
3750
3751       if ( sm->IsEmpty() )
3752       {
3753         // not yet meshed
3754         switch ( s.ShapeType() ) {
3755         case TopAbs_FACE: fmap.Add ( s ); break;
3756         case TopAbs_EDGE: emap.Add ( s ); break;
3757         default:;
3758         }
3759       }
3760       else
3761       {
3762         if ( s.ShapeType() != TopAbs_FACE )
3763           boundarySM.push_back( sm );
3764       }
3765     }
3766   }
3767 }
3768
3769 //================================================================================
3770 /*!
3771  * \brief Return true if given shape is to be precomputed in order to be correctly
3772  * added to netgen mesh
3773  */
3774 //================================================================================
3775
3776 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3777 {
3778   int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3779   switch ( s.ShapeType() ) {
3780   case TopAbs_FACE  : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3781   case TopAbs_EDGE  : return isInternalEdge( shapeID );
3782   case TopAbs_VERTEX: break;
3783   default:;
3784   }
3785   return false;
3786 }
3787
3788 //================================================================================
3789 /*!
3790  * \brief Return SMESH
3791  */
3792 //================================================================================
3793
3794 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3795 {
3796   return const_cast<SMESH_Mesh&>( _mesh );
3797 }
3798
3799 //================================================================================
3800 /*!
3801  * \brief Initialize netgen library
3802  */
3803 //================================================================================
3804
3805 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3806 {
3807   Ng_Init();
3808
3809   _isComputeOk      = false;
3810   _coutBuffer       = NULL;
3811   if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
3812   {
3813     // redirect all netgen output (mycout,myerr,cout) to _outputFileName
3814     _outputFileName = getOutputFileName();
3815     netgen::mycout  = new ofstream ( _outputFileName.c_str() );
3816     netgen::myerr   = netgen::mycout;
3817     _coutBuffer     = std::cout.rdbuf();
3818 #ifdef _DEBUG_
3819     cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl;
3820 #else
3821     std::cout.rdbuf( netgen::mycout->rdbuf() );
3822 #endif
3823   }
3824
3825   _ngMesh = Ng_NewMesh();
3826 }
3827
3828 //================================================================================
3829 /*!
3830  * \brief Finish using netgen library
3831  */
3832 //================================================================================
3833
3834 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3835 {
3836   Ng_DeleteMesh( _ngMesh );
3837   Ng_Exit();
3838   NETGENPlugin_Mesher::RemoveTmpFiles();
3839   if ( _coutBuffer )
3840     std::cout.rdbuf( _coutBuffer );
3841 #ifdef _DEBUG_
3842   if( _isComputeOk )
3843 #endif
3844     removeOutputFile();
3845 }
3846
3847 //================================================================================
3848 /*!
3849  * \brief Set netgen mesh to delete at destruction
3850  */
3851 //================================================================================
3852
3853 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3854 {
3855   if ( _ngMesh )
3856     Ng_DeleteMesh( _ngMesh );
3857   _ngMesh = mesh;
3858 }
3859
3860 //================================================================================
3861 /*!
3862  * \brief Return a unique file name
3863  */
3864 //================================================================================
3865
3866 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
3867 {
3868   std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
3869
3870   TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
3871   aGenericName += "NETGEN_";
3872 #ifndef WIN32
3873   aGenericName += getpid();
3874 #else
3875   aGenericName += _getpid();
3876 #endif
3877   aGenericName += "_";
3878   aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
3879   aGenericName += ".out";
3880
3881   return aGenericName.ToCString();
3882 }
3883
3884 //================================================================================
3885 /*!
3886  * \brief Remove file with netgen output
3887  */
3888 //================================================================================
3889
3890 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
3891 {
3892   if ( !_outputFileName.empty() )
3893   {
3894     if ( netgen::mycout )
3895     {
3896       delete netgen::mycout;
3897       netgen::mycout = 0;
3898       netgen::myerr = 0;
3899     }
3900     string    tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
3901     string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
3902     SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
3903     aFiles->length(1);
3904     aFiles[0] = aFileName.c_str();
3905
3906     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true );
3907   }
3908 }