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