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