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