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