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