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