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