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