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