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