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