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