Salome HOME
Merge from V6_main 13/12/2012
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_Mesher.cxx
1 // Copyright (C) 2007-2012  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 <utilities.h>
50
51 #include <BRepBuilderAPI_Copy.hxx>
52 #include <BRep_Tool.hxx>
53 #include <Bnd_B3d.hxx>
54 #include <NCollection_Map.hxx>
55 #include <Standard_ErrorHandler.hxx>
56 #include <TopExp.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
59 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
60 #include <TopTools_DataMapOfShapeInteger.hxx>
61 #include <TopTools_DataMapOfShapeShape.hxx>
62 #include <TopTools_MapOfShape.hxx>
63 #include <TopoDS.hxx>
64
65 // Netgen include files
66 #ifndef OCCGEOMETRY
67 #define OCCGEOMETRY
68 #endif
69 #include <occgeom.hpp>
70 #include <meshing.hpp>
71 //#include <ngexception.hpp>
72 namespace netgen {
73   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
74   //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
75   extern MeshingParameters mparam;
76   extern volatile multithreadt multithread;
77 }
78
79 #include <vector>
80 #include <limits>
81
82 using namespace nglib;
83 using namespace std;
84
85 #ifdef _DEBUG_
86 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
87 #else
88 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
89 #endif
90
91 #ifdef NETGEN_NEW
92 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
93 #else
94 #define NGPOINT_COORDS(p) p.X(),p.Y(),p.Z()
95 #endif
96
97 // dump elements added to ng mesh
98 //#define DUMP_SEGMENTS
99 //#define DUMP_TRIANGLES
100 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
101
102 TopTools_IndexedMapOfShape ShapesWithLocalSize;
103 std::map<int,double> VertexId2LocalSize;
104 std::map<int,double> EdgeId2LocalSize;
105 std::map<int,double> FaceId2LocalSize;
106
107 //=============================================================================
108 /*!
109  *
110  */
111 //=============================================================================
112
113 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh*         mesh,
114                                           const TopoDS_Shape& aShape,
115                                           const bool          isVolume)
116   : _mesh    (mesh),
117     _shape   (aShape),
118     _isVolume(isVolume),
119     _optimize(true),
120     _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
121     _isViscousLayers2D(false),
122     _simpleHyp(NULL)
123 {
124   SetDefaultParameters();
125   ShapesWithLocalSize.Clear();
126   VertexId2LocalSize.clear();
127   EdgeId2LocalSize.clear();
128   FaceId2LocalSize.clear();
129 }
130
131 //================================================================================
132 /*!
133  * \brief Initialize global NETGEN parameters with default values
134  */
135 //================================================================================
136
137 void NETGENPlugin_Mesher::SetDefaultParameters()
138 {
139   netgen::MeshingParameters& mparams = netgen::mparam;
140   // maximal mesh edge size
141   mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
142   mparams.minh = 0;
143   // minimal number of segments per edge
144   mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
145   // rate of growth of size between elements
146   mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
147   // safety factor for curvatures (elements per radius)
148   mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
149   // create elements of second order
150   mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder() ? 1 : 0;
151   // quad-dominated surface meshing
152   if (_isVolume)
153     mparams.quad = 0;
154   else
155     mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed() ? 1 : 0;
156   _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
157 }
158
159 //=============================================================================
160 /*!
161  *
162  */
163 //=============================================================================
164 void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize)
165 {
166   TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
167   if (GeomType == TopAbs_COMPOUND) {
168     for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
169       SetLocalSize(it.Value(), LocalSize);
170     }
171     return;
172   }
173   int key;
174   if (! ShapesWithLocalSize.Contains(GeomShape))
175     key = ShapesWithLocalSize.Add(GeomShape);
176   else
177     key = ShapesWithLocalSize.FindIndex(GeomShape);
178   if (GeomType == TopAbs_VERTEX) {
179     VertexId2LocalSize[key] = LocalSize;
180   } else if (GeomType == TopAbs_EDGE) {
181     EdgeId2LocalSize[key] = LocalSize;
182   } else if (GeomType == TopAbs_FACE) {
183     FaceId2LocalSize[key] = LocalSize;
184   }
185 }
186
187 //=============================================================================
188 /*!
189  * Pass parameters to NETGEN
190  */
191 //=============================================================================
192 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
193 {
194   if (hyp)
195   {
196     netgen::MeshingParameters& mparams = netgen::mparam;
197     // Initialize global NETGEN parameters:
198     // maximal mesh segment size
199     mparams.maxh = hyp->GetMaxSize();
200     // maximal mesh element linear size
201     mparams.minh = hyp->GetMinSize();
202     // minimal number of segments per edge
203     mparams.segmentsperedge = hyp->GetNbSegPerEdge();
204     // rate of growth of size between elements
205     mparams.grading = hyp->GetGrowthRate();
206     // safety factor for curvatures (elements per radius)
207     mparams.curvaturesafety = hyp->GetNbSegPerRadius();
208     // create elements of second order
209     mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
210     // quad-dominated surface meshing
211     // only triangles are allowed for volumic mesh (before realizing IMP 0021676)
212     //if (!_isVolume)
213       mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
214     _optimize = hyp->GetOptimize();
215     _fineness = hyp->GetFineness();
216     _simpleHyp = NULL;
217
218     SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
219     CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
220     SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
221     SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId());
222     
223     const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries();
224     NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
225     for (it ; it != localSizes.end() ; it++)
226       {
227         std::string entry = (*it).first;
228         double val = (*it).second;
229         // --
230         GEOM::GEOM_Object_var aGeomObj;
231         TopoDS_Shape S = TopoDS_Shape();
232         SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
233         SALOMEDS::GenericAttribute_var anAttr;
234         if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR")) {
235           SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
236           CORBA::String_var aVal = anIOR->Value();
237           CORBA::Object_var obj = myStudy->ConvertIORToObject(aVal);
238           aGeomObj = GEOM::GEOM_Object::_narrow(obj);
239         }
240         if ( !aGeomObj->_is_nil() )
241           S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
242         // --
243         SetLocalSize(S, val);
244       }
245   }
246 }
247
248 //=============================================================================
249 /*!
250  * Pass simple parameters to NETGEN
251  */
252 //=============================================================================
253
254 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
255 {
256   _simpleHyp = hyp;
257   if ( _simpleHyp )
258     SetDefaultParameters();
259 }
260
261 //=============================================================================
262 /*!
263  *  Link - a pair of integer numbers
264  */
265 //=============================================================================
266 struct Link
267 {
268   int n1, n2;
269   Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
270   Link() : n1(0), n2(0) {}
271 };
272
273 int HashCode(const Link& aLink, int aLimit)
274 {
275   return HashCode(aLink.n1 + aLink.n2, aLimit);
276 }
277
278 Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
279 {
280   return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ||
281           aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1);
282 }
283
284 namespace
285 {
286   //================================================================================
287   /*!
288    * \brief return id of netgen point corresponding to SMDS node
289    */
290   //================================================================================
291   typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
292
293   int ngNodeId( const SMDS_MeshNode* node,
294                 netgen::Mesh&        ngMesh,
295                 TNode2IdMap&         nodeNgIdMap)
296   {
297     int newNgId = ngMesh.GetNP() + 1;
298
299     TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
300
301     if ( node_id->second == newNgId)
302     {
303 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
304       cout << "Ng " << newNgId << " - " << node;
305 #endif
306       netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
307       ngMesh.AddPoint( p );
308     }
309     return node_id->second;
310   }
311
312   //================================================================================
313   /*!
314    * \brief Return computed EDGEs connected to the given one
315    */
316   //================================================================================
317
318   list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge&                 edge,
319                                          const TopoDS_Face&                 face,
320                                          const set< SMESH_subMesh* > &      computedSM,
321                                          const SMESH_MesherHelper&          helper,
322                                          map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
323   {
324     // get ordered EDGEs
325     TopoDS_Vertex v1;
326     list< TopoDS_Edge > edges;
327     list< int > nbEdgesInWire;
328     int nbWires = SMESH_Block::GetOrderedEdges( face, v1, edges, nbEdgesInWire);
329
330     // find <edge> within <edges>
331     list< TopoDS_Edge >::iterator eItFwd = edges.begin();
332     for ( ; eItFwd != edges.end(); ++eItFwd )
333       if ( edge.IsSame( *eItFwd ))
334         break;
335     if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
336
337     if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
338     {
339       // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
340       // so treat each INTERNAL edge separately
341       TopoDS_Edge e = *eItFwd;
342       edges.clear();
343       edges.push_back( e );
344       return edges;
345     }
346
347     // get all computed EDGEs connected to <edge>
348
349     list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
350     TopoDS_Vertex vCommon;
351     TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
352     eAdded.Add( edge );
353
354     // put edges before <edge> to <edges> back
355     while ( edges.begin() != eItFwd )
356       edges.splice( edges.end(), edges, edges.begin() );
357
358     // search forward
359     ePrev = eItFwd;
360     while ( ++eItFwd != edges.end() )
361     {
362       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
363
364       bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
365       bool computed  = sm->IsMeshComputed();
366       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
367       bool doubled   = !eAdded.Add( *eItFwd );
368       bool orientOK  = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
369                         ( eItFwd->Orientation() < TopAbs_INTERNAL )    );
370       if ( !connected || !computed || !orientOK || added || doubled )
371       {
372         // stop advancement; move edges from tail to head
373         while ( edges.back() != *ePrev )
374           edges.splice( edges.begin(), edges, --edges.end() );
375         break;
376       }
377       ePrev = eItFwd;
378     }
379     // search backward
380     while ( eItBack != edges.begin() )
381     {
382       ePrev = eItBack;
383       --eItBack;
384       SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
385
386       bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
387       bool computed  = sm->IsMeshComputed();
388       bool added     = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
389       bool doubled   = !eAdded.Add( *eItBack );
390       bool orientOK  = (( ePrev  ->Orientation() < TopAbs_INTERNAL ) ==
391                         ( eItBack->Orientation() < TopAbs_INTERNAL )    );
392       if ( !connected || !computed || !orientOK || added || doubled)
393       {
394         // stop advancement
395         edges.erase( edges.begin(), ePrev );
396         break;
397       }
398     }
399     if ( edges.front() != edges.back() )
400     {
401       // assure that the 1st vertex is meshed
402       TopoDS_Edge eLast = edges.back();
403       while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
404               &&
405               edges.front() != eLast )
406         edges.splice( edges.end(), edges, edges.begin() );
407     }
408     return edges;
409   }
410
411   //================================================================================
412   /*!
413    * \brief Make triangulation of a shape precise enough
414    */
415   //================================================================================
416
417   void updateTriangulation( const TopoDS_Shape& shape )
418   {
419     // static set< Poly_Triangulation* > updated;
420
421     // TopLoc_Location loc;
422     // TopExp_Explorer fExp( shape, TopAbs_FACE );
423     // for ( ; fExp.More(); fExp.Next() )
424     // {
425     //   Handle(Poly_Triangulation) triangulation =
426     //     BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
427     //   if ( triangulation.IsNull() ||
428     //        updated.insert( triangulation.operator->() ).second )
429     //   {
430     //     BRepTools::Clean (shape);
431         try {
432 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
433           OCC_CATCH_SIGNALS;
434 #endif
435           BRepMesh_IncrementalMesh e(shape, 0.01, true);
436
437         }
438         catch (Standard_Failure)
439         {
440         }
441   //       updated.erase( triangulation.operator->() );
442   //       triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
443   //       updated.insert( triangulation.operator->() );
444   //     }
445   //   }
446   }
447 }
448
449 //================================================================================
450 /*!
451  * \brief Initialize netgen::OCCGeometry with OCCT shape
452  */
453 //================================================================================
454
455 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry&     occgeo,
456                                              const TopoDS_Shape&      shape,
457                                              SMESH_Mesh&              mesh,
458                                              list< SMESH_subMesh* > * meshedSM,
459                                              NETGENPlugin_Internals*  intern)
460 {
461   updateTriangulation( shape );
462
463   Bnd_Box bb;
464   BRepBndLib::Add (shape, bb);
465   double x1,y1,z1,x2,y2,z2;
466   bb.Get (x1,y1,z1,x2,y2,z2);
467   MESSAGE("shape bounding box:\n" <<
468           "(" << x1 << " " << y1 << " " << z1 << ") " <<
469           "(" << x2 << " " << y2 << " " << z2 << ")");
470   netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
471   netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
472   occgeo.boundingbox = netgen::Box<3> (p1,p2);
473
474   occgeo.shape = shape;
475   occgeo.changed = 1;
476
477   // fill maps of shapes of occgeo with not yet meshed subshapes
478
479   // get root submeshes
480   list< SMESH_subMesh* > rootSM;
481   if ( SMESH_subMesh* sm = mesh.GetSubMeshContaining( shape )) {
482     rootSM.push_back( sm );
483   }
484   else {
485     for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
486       rootSM.push_back( mesh.GetSubMesh( it.Value() ));
487   }
488
489   // add subshapes of empty submeshes
490   list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
491   for ( ; rootIt != rootEnd; ++rootIt ) {
492     SMESH_subMesh * root = *rootIt;
493     SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
494                                                                /*complexShapeFirst=*/true);
495     // to find a right orientation of subshapes (PAL20462)
496     TopTools_IndexedMapOfShape subShapes;
497     TopExp::MapShapes(root->GetSubShape(), subShapes);
498     while ( smIt->more() )
499     {
500       SMESH_subMesh* sm = smIt->next();
501       TopoDS_Shape shape = sm->GetSubShape();
502       if ( intern && intern->isShapeToPrecompute( shape ))
503         continue;
504       if ( !meshedSM || sm->IsEmpty() )
505       {
506         if ( shape.ShapeType() != TopAbs_VERTEX )
507           shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
508         if ( shape.Orientation() >= TopAbs_INTERNAL )
509           shape.Orientation( TopAbs_FORWARD ); // isuue 0020676
510         switch ( shape.ShapeType() ) {
511         case TopAbs_FACE  : occgeo.fmap.Add( shape ); break;
512         case TopAbs_EDGE  : occgeo.emap.Add( shape ); break;
513         case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
514         case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
515         default:;
516         }
517       }
518       // collect submeshes of meshed shapes
519       else if (meshedSM)
520       {
521         const int dim = SMESH_Gen::GetShapeDim( shape );
522         meshedSM[ dim ].push_back( sm );
523       }
524     }
525   }
526   occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent());
527   occgeo.facemeshstatus = 0;
528 #ifdef NETGEN_NEW
529   occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent());
530   occgeo.face_maxh_modified = 0;
531   occgeo.face_maxh.SetSize(occgeo.fmap.Extent());
532   occgeo.face_maxh = netgen::mparam.maxh;
533 #endif
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 = SMESH_Algo::IsReversedSubMesh
839             ( TopoDS::Face( geomFace.Oriented( faceOriInSolid )), helper.GetMeshDS() );
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     for ( int i = 0; i < nbSegments; ++i ) // loop on segments
1551     {
1552       // Add the first point of a segment
1553
1554       const SMDS_MeshNode * n = uvPtVec[ i ].node;
1555       const int posShapeID = n->getshapeId();
1556       bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
1557       bool onEdge   = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE   );
1558
1559       // skip nodes on degenerated edges
1560       if ( helper.IsDegenShape( posShapeID ) &&
1561            helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() ))
1562         continue;
1563
1564       int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
1565       if ( onVertex || ( !wasNgMeshEmpty && onEdge ))
1566         ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
1567       if ( ngID1 > ngMesh.GetNP() )
1568       {
1569         netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
1570         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1571         nodeVec.push_back( n );
1572       }
1573       else // n is in ngMesh already, and ngID2 in prev segment is wrong
1574       {
1575         ngID2 = ngMesh.GetNP() + 1;
1576         if ( i > 0 ) // prev segment belongs to same wire
1577         {
1578           netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1579           prevSeg[1] = ngID1;
1580         }
1581       }
1582
1583       // Add the segment
1584
1585       netgen::Segment seg;
1586
1587       seg[0]     = ngID1;                // ng node id
1588       seg[1]     = ngID2;                // ng node id
1589       seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
1590       seg.si     = faceID;               // = geom.fmap.FindIndex (face);
1591
1592       for ( int iEnd = 0; iEnd < 2; ++iEnd)
1593       {
1594         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
1595
1596         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
1597         seg.epgeominfo[ iEnd ].u    = pnt.u;
1598         seg.epgeominfo[ iEnd ].v    = pnt.v;
1599
1600         // find out edge id and node parameter on edge
1601         onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
1602         if ( onVertex || posShapeID != posID )
1603         {
1604           // get edge id
1605           double normParam = pnt.normParam;
1606           if ( onVertex )
1607             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
1608           int edgeIndexInWire = wire->EdgeIndex( normParam );
1609           vertexNormPar = wire->LastParameter( edgeIndexInWire );
1610           const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
1611           edgeID = geom.emap.FindIndex( edge );
1612           posID  = posShapeID;
1613           isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
1614           // if ( onVertex ) // param on curve is different on each of two edges
1615           //   seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
1616         }
1617         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
1618       }
1619
1620       ngMesh.AddSegment (seg);
1621       {
1622         // restrict size of elements near the segment
1623         SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
1624         // get an average size of adjacent segments to avoid sharp change of
1625         // element size (regression on issue 0020452, note 0010898)
1626         int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
1627         int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
1628         double avgH = ( segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ]) / 3;
1629
1630         RestrictLocalSize( ngMesh, 0.5*(np1+np2), avgH );
1631       }
1632 #ifdef DUMP_SEGMENTS
1633         cout << "Segment: " << seg.edgenr << endl
1634            << "\tp1: " << seg[0] << endl
1635            << "\tp2: " << seg[1] << endl
1636            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1637            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1638            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1639            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1640            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
1641            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1642 #endif
1643       if ( isInternalWire )
1644       {
1645         swap (seg[0], seg[1]);
1646         swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1647         seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1648         ngMesh.AddSegment (seg);
1649 #ifdef DUMP_SEGMENTS
1650         cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl;
1651 #endif
1652       }
1653     } // loop on segments on a wire
1654
1655     // close chain of segments
1656     if ( nbSegments > 0 )
1657     {
1658       netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire));
1659       const SMDS_MeshNode * lastNode = uvPtVec.back().node;
1660       lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
1661       if ( lastSeg[1] > ngMesh.GetNP() )
1662       {
1663         netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
1664         ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1665         nodeVec.push_back( lastNode );
1666       }
1667       if ( isInternalWire )
1668       {
1669         netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
1670         realLastSeg[0] = lastSeg[1];
1671       }
1672     }
1673
1674   } // loop on WIREs of a FACE
1675
1676   // add a segment instead of an internal vertex
1677   if ( wasNgMeshEmpty )
1678   {
1679     NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
1680     AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
1681   }
1682   ngMesh.CalcSurfacesOfNode();
1683
1684   return TError();
1685 }
1686
1687 //================================================================================
1688 /*!
1689  * \brief Fill SMESH mesh according to contents of netgen mesh
1690  *  \param occgeo - container of OCCT geometry to mesh
1691  *  \param ngMesh - netgen mesh
1692  *  \param initState - bn of entities in netgen mesh before computing
1693  *  \param sMesh - SMESH mesh to fill in
1694  *  \param nodeVec - vector of nodes in which node index == netgen ID
1695  *  \retval int - error
1696  */
1697 //================================================================================
1698
1699 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry&          occgeo,
1700                                    netgen::Mesh&                       ngMesh,
1701                                    const NETGENPlugin_ngMeshInfo&      initState,
1702                                    SMESH_Mesh&                         sMesh,
1703                                    std::vector<const SMDS_MeshNode*>&  nodeVec,
1704                                    SMESH_Comment&                      comment)
1705 {
1706   int nbNod = ngMesh.GetNP();
1707   int nbSeg = ngMesh.GetNSeg();
1708   int nbFac = ngMesh.GetNSE();
1709   int nbVol = ngMesh.GetNE();
1710
1711   SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
1712
1713   // -------------------------------------
1714   // Create and insert nodes into nodeVec
1715   // -------------------------------------
1716
1717   nodeVec.resize( nbNod + 1 );
1718   int i, nbInitNod = initState._nbNodes;
1719   for (i = nbInitNod+1; i <= nbNod; ++i )
1720   {
1721     const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
1722     SMDS_MeshNode* node = NULL;
1723     TopoDS_Vertex aVert;
1724     // First, netgen creates nodes on vertices in occgeo.vmap,
1725     // so node index corresponds to vertex index
1726     // but (issue 0020776) netgen does not create nodes with equal coordinates
1727     if ( i-nbInitNod <= occgeo.vmap.Extent() )
1728     {
1729       gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
1730       for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
1731       {
1732         aVert = TopoDS::Vertex( occgeo.vmap( iV ) );
1733         gp_Pnt pV = BRep_Tool::Pnt( aVert );
1734         if ( p.SquareDistance( pV ) > 1e-20 )
1735           aVert.Nullify();
1736         else
1737           node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
1738       }
1739     }
1740     if (!node) // node not found on vertex
1741     {
1742       node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
1743       if (!aVert.IsNull())
1744         meshDS->SetNodeOnVertex(node, aVert);
1745     }
1746     nodeVec[i] = node;
1747   }
1748
1749   // -------------------------------------------
1750   // Create mesh segments along geometric edges
1751   // -------------------------------------------
1752
1753   int nbInitSeg = initState._nbSegments;
1754   for (i = nbInitSeg+1; i <= nbSeg; ++i )
1755   {
1756     const netgen::Segment& seg = ngMesh.LineSegment(i);
1757     TopoDS_Edge aEdge;
1758 #ifdef NETGEN_NEW
1759     int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
1760 #else
1761     int pinds[3] = { seg.p1, seg.p2, seg.pmid };
1762 #endif
1763     int nbp = 0;
1764     double param2 = 0;
1765     for (int j=0; j < 3; ++j)
1766     {
1767       int pind = pinds[j];
1768       if (pind <= 0 || !nodeVec_ACCESS(pind))
1769         break;
1770       ++nbp;
1771       double param;
1772       if (j < 2)
1773       {
1774         if (aEdge.IsNull())
1775         {
1776           int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
1777           if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
1778             aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
1779         }
1780         param = seg.epgeominfo[j].dist;
1781         param2 += param;
1782       }
1783       else // middle point
1784       {
1785         param = param2 * 0.5;
1786       }
1787       if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1)
1788       {
1789         meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
1790       }
1791     }
1792     if ( nbp > 1 )
1793     {
1794       SMDS_MeshEdge* edge = 0;
1795       if (nbp == 2) // second order ?
1796       {
1797         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
1798           continue;
1799         edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
1800       }
1801       else
1802       {
1803         if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1804                                nodeVec_ACCESS(pinds[2])))
1805           continue;
1806         edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
1807                                nodeVec_ACCESS(pinds[2]));
1808       }
1809       if (!edge)
1810       {
1811         if ( comment.empty() ) comment << "Cannot create a mesh edge";
1812         MESSAGE("Cannot create a mesh edge");
1813         nbSeg = nbFac = nbVol = 0;
1814         break;
1815       }
1816       if ( !aEdge.IsNull() && edge->getshapeId() < 1 )
1817         meshDS->SetMeshElementOnShape(edge, aEdge);
1818     }
1819     else if ( comment.empty() )
1820     {
1821       comment << "Invalid netgen segment #" << i;
1822     }
1823   }
1824
1825   // ----------------------------------------
1826   // Create mesh faces along geometric faces
1827   // ----------------------------------------
1828
1829   int nbInitFac = initState._nbFaces;
1830   int quadFaceID = ngMesh.GetNFD() + 1;
1831   if ( nbInitFac < nbFac )
1832     // add a faces descriptor to exclude qudrangle elements generated by NETGEN
1833     // from computation of 3D mesh
1834     ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
1835
1836   for (i = nbInitFac+1; i <= nbFac; ++i )
1837   {
1838     const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1839     int aGeomFaceInd = elem.GetIndex();
1840     TopoDS_Face aFace;
1841     if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
1842       aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
1843     vector<SMDS_MeshNode*> nodes;
1844     for (int j=1; j <= elem.GetNP(); ++j)
1845     {
1846       int pind = elem.PNum(j);
1847       if ( pind < 1 || pind >= nodeVec.size() )
1848         break;
1849       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
1850       {
1851         nodes.push_back(node);
1852         if (!aFace.IsNull() && node->getshapeId() < 1)
1853         {
1854           const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
1855           meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
1856         }
1857       }
1858     }
1859     if ( nodes.size() != elem.GetNP() )
1860     {
1861       if ( comment.empty() )
1862         comment << "Invalid netgen 2d element #" << i;
1863       continue; // bad node ids
1864     }
1865     SMDS_MeshFace* face = NULL;
1866     switch (elem.GetType())
1867     {
1868     case netgen::TRIG:
1869       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
1870       break;
1871     case netgen::QUAD:
1872       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
1873       // exclude qudrangle elements from computation of 3D mesh
1874       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1875       break;
1876     case netgen::TRIG6:
1877       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
1878       break;
1879     case netgen::QUAD8:
1880       face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
1881                              nodes[4],nodes[7],nodes[5],nodes[6]);
1882       // exclude qudrangle elements from computation of 3D mesh
1883       const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
1884       break;
1885     default:
1886       MESSAGE("NETGEN created a face of unexpected type, ignoring");
1887       continue;
1888     }
1889     if (!face)
1890     {
1891       if ( comment.empty() ) comment << "Cannot create a mesh face";
1892       MESSAGE("Cannot create a mesh face");
1893       nbSeg = nbFac = nbVol = 0;
1894       break;
1895     }
1896     if (!aFace.IsNull())
1897       meshDS->SetMeshElementOnShape(face, aFace);
1898   }
1899
1900   // ------------------
1901   // Create tetrahedra
1902   // ------------------
1903
1904   for (i = 1; i <= nbVol; ++i)
1905   {
1906     const netgen::Element& elem = ngMesh.VolumeElement(i);      
1907     int aSolidInd = elem.GetIndex();
1908     TopoDS_Solid aSolid;
1909     if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent())
1910       aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
1911     vector<SMDS_MeshNode*> nodes;
1912     for (int j=1; j <= elem.GetNP(); ++j)
1913     {
1914       int pind = elem.PNum(j);
1915       if ( pind < 1 || pind >= nodeVec.size() )
1916         break;
1917       if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
1918       {
1919         nodes.push_back(node);
1920         if ( !aSolid.IsNull() && node->getshapeId() < 1 )
1921           meshDS->SetNodeInVolume(node, aSolid);
1922       }
1923     }
1924     if ( nodes.size() != elem.GetNP() )
1925     {
1926       if ( comment.empty() )
1927         comment << "Invalid netgen 3d element #" << i;
1928       continue;
1929     }
1930     SMDS_MeshVolume* vol = NULL;
1931     switch (elem.GetType())
1932     {
1933     case netgen::TET:
1934       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
1935       break;
1936     case netgen::TET10:
1937       vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
1938                               nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
1939       break;
1940     default:
1941       MESSAGE("NETGEN created a volume of unexpected type, ignoring");
1942       continue;
1943     }
1944     if (!vol)
1945     {
1946       if ( comment.empty() ) comment << "Cannot create a mesh volume";
1947       MESSAGE("Cannot create a mesh volume");
1948       nbSeg = nbFac = nbVol = 0;
1949       break;
1950     }
1951     if (!aSolid.IsNull())
1952       meshDS->SetMeshElementOnShape(vol, aSolid);
1953   }
1954   return comment.empty() ? 0 : 1;
1955 }
1956
1957 namespace
1958 {
1959   //================================================================================
1960   /*!
1961    * \brief Restrict size of elements on the given edge 
1962    */
1963   //================================================================================
1964
1965   void setLocalSize(const TopoDS_Edge& edge,
1966                     double             size,
1967                     netgen::Mesh&      mesh)
1968   {
1969     const int nb = 1000;
1970     Standard_Real u1, u2;
1971     Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
1972     if ( curve.IsNull() )
1973     {
1974       TopoDS_Iterator vIt( edge );
1975       if ( !vIt.More() ) return;
1976       gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
1977       NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
1978     }
1979     else
1980     {
1981       Standard_Real delta = (u2-u1)/nb;
1982       for(int i=0; i<nb; i++)
1983       {
1984         Standard_Real u = u1 + delta*i;
1985         gp_Pnt p = curve->Value(u);
1986         NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size );
1987         netgen::Point3d pi(p.X(), p.Y(), p.Z());
1988         double resultSize = mesh.GetH(pi);
1989         if ( resultSize - size > 0.1*size )
1990           // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
1991           NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 );
1992       }
1993     }
1994   }
1995
1996   //================================================================================
1997   /*!
1998    * \brief Convert error into text
1999    */
2000   //================================================================================
2001
2002   std::string text(int err)
2003   {
2004     if ( !err )
2005       return string("");
2006     return
2007       SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2008   }
2009
2010   //================================================================================
2011   /*!
2012    * \brief Convert exception into text
2013    */
2014   //================================================================================
2015
2016   std::string text(Standard_Failure& ex)
2017   {
2018     SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2019     str << " at " << netgen::multithread.task
2020         << ": " << ex.DynamicType()->Name();
2021     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2022       str << ": " << ex.GetMessageString();
2023     return str;
2024   }
2025   //================================================================================
2026   /*!
2027    * \brief Convert exception into text
2028    */
2029   //================================================================================
2030
2031   std::string text(netgen::NgException& ex)
2032   {
2033     SMESH_Comment str("NgException");
2034     str << " at " << netgen::multithread.task << ": " << ex.What();
2035     return str;
2036   }
2037 }
2038
2039 //=============================================================================
2040 /*!
2041  * Here we are going to use the NETGEN mesher
2042  */
2043 //=============================================================================
2044
2045 bool NETGENPlugin_Mesher::Compute()
2046 {
2047   NETGENPlugin_NetgenLibWrapper ngLib;
2048
2049   netgen::MeshingParameters& mparams = netgen::mparam;
2050   MESSAGE("Compute with:\n"
2051           " max size = " << mparams.maxh << "\n"
2052           " segments per edge = " << mparams.segmentsperedge);
2053   MESSAGE("\n"
2054           " growth rate = " << mparams.grading << "\n"
2055           " elements per radius = " << mparams.curvaturesafety << "\n"
2056           " second order = " << mparams.secondorder << "\n"
2057           " quad allowed = " << mparams.quad);
2058   //cout << " quad allowed = " << mparams.quad<<endl;
2059
2060   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2061
2062   static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( ngMesh, debugFile )
2063                                                  while debugging netgen */
2064   // -------------------------
2065   // Prepare OCC geometry
2066   // -------------------------
2067
2068   netgen::OCCGeometry occgeo;
2069   list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2070   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2071   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2072
2073   // -------------------------
2074   // Generate the mesh
2075   // -------------------------
2076
2077   netgen::Mesh *ngMesh = NULL;
2078   NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2079
2080   SMESH_Comment comment;
2081   int err = 0;
2082
2083   // vector of nodes in which node index == netgen ID
2084   vector< const SMDS_MeshNode* > nodeVec;
2085   
2086   {
2087     // ----------------
2088     // compute 1D mesh
2089     // ----------------
2090     if ( _simpleHyp )
2091     {
2092       // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2093       mparams.uselocalh = false;
2094       mparams.grading = 0.8; // not limitited size growth
2095
2096       if ( _simpleHyp->GetNumberOfSegments() )
2097         // nb of segments
2098         mparams.maxh = occgeo.boundingbox.Diam();
2099       else
2100         // segment length
2101         mparams.maxh = _simpleHyp->GetLocalLength();
2102     }
2103
2104     if ( mparams.maxh == 0.0 )
2105       mparams.maxh = occgeo.boundingbox.Diam();
2106     if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2107       mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2108
2109 #ifdef NETGEN_NEW
2110     // Local size on faces
2111     occgeo.face_maxh = mparams.maxh;
2112 #endif
2113
2114     // Let netgen create ngMesh and calculate element size on not meshed shapes
2115     char *optstr = 0;
2116     int startWith = netgen::MESHCONST_ANALYSE;
2117     int endWith   = netgen::MESHCONST_ANALYSE;
2118     try
2119     {
2120       OCC_CATCH_SIGNALS;
2121       err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2122 #ifdef WITH_SMESH_CANCEL_COMPUTE
2123       if(netgen::multithread.terminate)
2124         return false;
2125 #endif
2126       comment << text(err);
2127     }
2128     catch (Standard_Failure& ex)
2129     {
2130       comment << text(ex);
2131     }
2132     err = 0; //- MESHCONST_ANALYSE isn't so important step
2133     if ( !ngMesh )
2134       return false;
2135     ngLib.setMesh(( Ng_Mesh*) ngMesh );
2136
2137     ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2138
2139     if ( _simpleHyp )
2140     {
2141       // Pass 1D simple parameters to NETGEN
2142       // --------------------------------
2143       int      nbSeg = _simpleHyp->GetNumberOfSegments();
2144       double segSize = _simpleHyp->GetLocalLength();
2145       for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2146       {
2147         const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2148         if ( nbSeg )
2149           segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2150         setLocalSize( e, segSize, *ngMesh );
2151       }
2152     }
2153     else // if ( ! _simpleHyp )
2154     {
2155       // Local size on vertices and edges
2156       // --------------------------------
2157       for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2158       {
2159         int key = (*it).first;
2160         double hi = (*it).second;
2161         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2162         const TopoDS_Edge& e = TopoDS::Edge(shape);
2163         setLocalSize( e, hi, *ngMesh );
2164       }
2165       for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2166       {
2167         int key = (*it).first;
2168         double hi = (*it).second;
2169         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2170         const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2171         gp_Pnt p = BRep_Tool::Pnt(v);
2172         NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2173       }
2174       for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2175           it!=FaceId2LocalSize.end(); it++)
2176       {
2177         int key = (*it).first;
2178         double val = (*it).second;
2179         const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2180         int faceNgID = occgeo.fmap.FindIndex(shape);
2181         occgeo.SetFaceMaxH(faceNgID, val);
2182         for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2183           setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2184       }
2185     }
2186
2187     // Precompute internal edges (issue 0020676) in order to
2188     // add mesh on them correctly (twice) to netgen mesh
2189     if ( !err && internals.hasInternalEdges() )
2190     {
2191       // load internal shapes into OCCGeometry
2192       netgen::OCCGeometry intOccgeo;
2193       internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2194       intOccgeo.boundingbox = occgeo.boundingbox;
2195       intOccgeo.shape = occgeo.shape;
2196 #ifdef NETGEN_NEW
2197       intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2198       intOccgeo.face_maxh = netgen::mparam.maxh;
2199 #endif
2200       netgen::Mesh *tmpNgMesh = NULL;
2201       try
2202       {
2203         OCC_CATCH_SIGNALS;
2204         // compute local H on internal shapes in the main mesh
2205         //OCCSetLocalMeshSize(intOccgeo, *ngMesh); it deletes ngMesh->localH
2206
2207         // let netgen create a temporary mesh
2208         netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2209 #ifdef WITH_SMESH_CANCEL_COMPUTE
2210         if(netgen::multithread.terminate)
2211           return false;
2212 #endif
2213         // copy LocalH from the main to temporary mesh
2214         initState.transferLocalH( ngMesh, tmpNgMesh );
2215
2216         // compute mesh on internal edges
2217         startWith = endWith = netgen::MESHCONST_MESHEDGES;
2218         err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2219         comment << text(err);
2220       }
2221       catch (Standard_Failure& ex)
2222       {
2223         comment << text(ex);
2224         err = 1;
2225       }
2226       initState.restoreLocalH( tmpNgMesh );
2227
2228       // fill SMESH by netgen mesh
2229       vector< const SMDS_MeshNode* > tmpNodeVec;
2230       FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
2231       err = ( err || !comment.empty() );
2232
2233       nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
2234     }
2235
2236     // Fill ngMesh with nodes and segments of computed submeshes
2237     if ( !err )
2238     {
2239       err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
2240                 FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_1D ]));
2241     }
2242     initState = NETGENPlugin_ngMeshInfo(ngMesh);
2243
2244     // Compute 1d mesh
2245     if (!err)
2246     {
2247       startWith = endWith = netgen::MESHCONST_MESHEDGES;
2248       try
2249       {
2250         OCC_CATCH_SIGNALS;
2251         err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2252 #ifdef WITH_SMESH_CANCEL_COMPUTE
2253         if(netgen::multithread.terminate)
2254           return false;
2255 #endif
2256         comment << text(err);
2257       }
2258       catch (Standard_Failure& ex)
2259       {
2260         comment << text(ex);
2261         err = 1;
2262       }
2263     }
2264     mparams.uselocalh = true; // restore as it is used at surface optimization
2265
2266     // ---------------------
2267     // compute surface mesh
2268     // ---------------------
2269     if (!err)
2270     {
2271       // Pass 2D simple parameters to NETGEN
2272       if ( _simpleHyp ) {
2273         if ( double area = _simpleHyp->GetMaxElementArea() ) {
2274           // face area
2275           mparams.maxh = sqrt(2. * area/sqrt(3.0));
2276           mparams.grading = 0.4; // moderate size growth
2277         }
2278         else {
2279           // length from edges
2280           if ( ngMesh->GetNSeg() ) {
2281             double edgeLength = 0;
2282             TopTools_MapOfShape visitedEdges;
2283             for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
2284               if( visitedEdges.Add(exp.Current()) )
2285                 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
2286             // we have to multiply length by 2 since for each TopoDS_Edge there
2287             // are double set of NETGEN edges, in other words, we have to
2288             // divide ngMesh->GetNSeg() by 2.
2289             mparams.maxh = 2*edgeLength / ngMesh->GetNSeg();
2290           }
2291           else {
2292             mparams.maxh = 1000;
2293           }
2294           mparams.grading = 0.2; // slow size growth
2295         }
2296         mparams.quad = _simpleHyp->GetAllowQuadrangles();
2297         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2298         ngMesh->SetGlobalH (mparams.maxh);
2299         netgen::Box<3> bb = occgeo.GetBoundingBox();
2300         bb.Increase (bb.Diam()/20);
2301         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
2302       }
2303
2304       // Care of vertices internal in faces (issue 0020676)
2305       if ( internals.hasInternalVertexInFace() )
2306       {
2307         // store computed segments in SMESH in order not to create SMESH
2308         // edges for ng segments added by AddIntVerticesInFaces()
2309         FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2310         // add segments to faces with internal vertices
2311         AddIntVerticesInFaces( occgeo, *ngMesh, nodeVec, internals );
2312         initState = NETGENPlugin_ngMeshInfo(ngMesh);
2313       }
2314
2315       // Build viscous layers
2316       if ( _isViscousLayers2D )
2317       {
2318         if ( !internals.hasInternalVertexInFace() ) {
2319           FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2320           initState = NETGENPlugin_ngMeshInfo(ngMesh);
2321         }
2322         SMESH_ProxyMesh::Ptr viscousMesh;
2323         SMESH_MesherHelper   helper( *_mesh );
2324         for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
2325         {
2326           const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
2327           viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
2328           if ( !viscousMesh )
2329             return false;
2330           // exclude from computation ng segments built on EDGEs of F
2331           for (int i = 1; i <= ngMesh->GetNSeg(); i++)
2332           {
2333             netgen::Segment & seg = ngMesh->LineSegment(i);
2334             if (seg.si == faceID)
2335               seg.si = 0;
2336           }
2337           // add new segments to ngMesh instead of excluded ones
2338           helper.SetSubShape( F );
2339           TSideVector wires =
2340             StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
2341                                                error, viscousMesh );
2342           error = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
2343
2344           if ( !error ) error = SMESH_ComputeError::New();
2345         }
2346         initState = NETGENPlugin_ngMeshInfo(ngMesh);
2347       }
2348
2349       // Let netgen compute 2D mesh
2350       startWith = netgen::MESHCONST_MESHSURFACE;
2351       endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
2352       try
2353       {
2354         OCC_CATCH_SIGNALS;
2355         err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2356 #ifdef WITH_SMESH_CANCEL_COMPUTE
2357         if(netgen::multithread.terminate)
2358           return false;
2359 #endif
2360         comment << text (err);
2361       }
2362       catch (Standard_Failure& ex)
2363       {
2364         comment << text(ex);
2365         //err = 1; -- try to make volumes anyway
2366       }
2367       catch (netgen::NgException exc)
2368       {
2369         comment << text(exc);
2370         //err = 1; -- try to make volumes anyway
2371       }
2372     }
2373     // ---------------------
2374     // generate volume mesh
2375     // ---------------------
2376     // Fill ngMesh with nodes and faces of computed 2D submeshes
2377     if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad ))
2378     {
2379       // load SMESH with computed segments and faces
2380       FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2381
2382       // compute pyramids on quadrangles
2383       SMESH_ProxyMesh::Ptr proxyMesh;
2384       if ( _mesh->NbQuadrangles() > 0 )
2385         for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
2386         {
2387           StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
2388           proxyMesh.reset( Adaptor );
2389
2390           int nbPyrams = _mesh->NbPyramids();
2391           Adaptor->Compute( *_mesh, occgeo.somap(iS) );
2392           if ( nbPyrams != _mesh->NbPyramids() )
2393           {
2394             list< SMESH_subMesh* > quadFaceSM;
2395             for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
2396               if ( Adaptor->GetProxySubMesh( face.Current() ))
2397               {
2398                 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
2399                 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
2400               }
2401             FillNgMesh(occgeo, *ngMesh, nodeVec, quadFaceSM, proxyMesh);
2402           }
2403         }
2404       // fill ngMesh with faces of sub-meshes
2405       err = ! ( FillNgMesh(occgeo, *ngMesh, nodeVec, meshedSM[ MeshDim_2D ]));
2406       initState = NETGENPlugin_ngMeshInfo(ngMesh);
2407       //toPython( ngMesh, "/tmp/ngPython.py");
2408     }
2409     if (!err && _isVolume)
2410     {
2411       // Pass 3D simple parameters to NETGEN
2412       const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2413         dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2414       if ( simple3d ) {
2415         if ( double vol = simple3d->GetMaxElementVolume() ) {
2416           // max volume
2417           mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2418           mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2419         }
2420         else {
2421           // length from faces
2422           mparams.maxh = ngMesh->AverageH();
2423         }
2424         ngMesh->SetGlobalH (mparams.maxh);
2425         mparams.grading = 0.4;
2426         ngMesh->CalcLocalH();
2427       }
2428       // Care of vertices internal in solids and internal faces (issue 0020676)
2429       if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
2430       {
2431         // store computed faces in SMESH in order not to create SMESH
2432         // faces for ng faces added here
2433         FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment );
2434         // add ng faces to solids with internal vertices
2435         AddIntVerticesInSolids( occgeo, *ngMesh, nodeVec, internals );
2436         // duplicate mesh faces on internal faces
2437         FixIntFaces( occgeo, *ngMesh, internals );
2438         initState = NETGENPlugin_ngMeshInfo(ngMesh);
2439       }
2440       // Let netgen compute 3D mesh
2441       startWith = endWith = netgen::MESHCONST_MESHVOLUME;
2442       try
2443       {
2444         OCC_CATCH_SIGNALS;
2445         err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2446 #ifdef WITH_SMESH_CANCEL_COMPUTE
2447         if(netgen::multithread.terminate)
2448           return false;
2449 #endif
2450         if ( comment.empty() ) // do not overwrite a previos error
2451           comment << text(err);
2452       }
2453       catch (Standard_Failure& ex)
2454       {
2455         if ( comment.empty() ) // do not overwrite a previos error
2456           comment << text(ex);
2457         err = 1;
2458       }
2459       catch (netgen::NgException exc)
2460       {
2461         if ( comment.empty() ) // do not overwrite a previos error
2462           comment << text(exc);
2463         err = 1;
2464       }
2465       // Let netgen optimize 3D mesh
2466       if ( !err && _optimize )
2467       {
2468         startWith = endWith = netgen::MESHCONST_OPTVOLUME;
2469         try
2470         {
2471           OCC_CATCH_SIGNALS;
2472           err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2473 #ifdef WITH_SMESH_CANCEL_COMPUTE
2474           if(netgen::multithread.terminate)
2475             return false;
2476 #endif
2477           if ( comment.empty() ) // do not overwrite a previos error
2478             comment << text(err);
2479         }
2480         catch (Standard_Failure& ex)
2481         {
2482           if ( comment.empty() ) // do not overwrite a previos error
2483             comment << text(ex);
2484         }
2485         catch (netgen::NgException exc)
2486         {
2487           if ( comment.empty() ) // do not overwrite a previos error
2488             comment << text(exc);
2489         }
2490       }
2491     }
2492     if (!err && mparams.secondorder > 0)
2493     {
2494       try
2495       {
2496         OCC_CATCH_SIGNALS;
2497         netgen::OCCRefinementSurfaces ref (occgeo);
2498         ref.MakeSecondOrder (*ngMesh);
2499       }
2500       catch (Standard_Failure& ex)
2501       {
2502         if ( comment.empty() ) // do not overwrite a previos error
2503           comment << "Exception in netgen at passing to 2nd order ";
2504       }
2505       catch (netgen::NgException exc)
2506       {
2507         if ( comment.empty() ) // do not overwrite a previos error
2508           comment << exc.What();
2509       }
2510     }
2511   }
2512   int nbNod = ngMesh->GetNP();
2513   int nbSeg = ngMesh->GetNSeg();
2514   int nbFac = ngMesh->GetNSE();
2515   int nbVol = ngMesh->GetNE();
2516   bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
2517
2518   MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") <<
2519           ", nb nodes: "    << nbNod <<
2520           ", nb segments: " << nbSeg <<
2521           ", nb faces: "    << nbFac <<
2522           ", nb volumes: "  << nbVol);
2523
2524   // Feed back the SMESHDS with the generated Nodes and Elements
2525   if ( true /*isOK*/ ) // get whatever built
2526     FillSMesh( occgeo, *ngMesh, initState, *_mesh, nodeVec, comment ); //!< 
2527
2528   SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
2529   if ( readErr && !readErr->myBadElements.empty() )
2530     error = readErr;
2531
2532   if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
2533     error->myName = COMPERR_ALGO_FAILED;
2534   if ( !comment.empty() )
2535     error->myComment = comment;
2536
2537   // SetIsAlwaysComputed( true ) to empty sub-meshes, which
2538   // appear if the geometry contains coincident sub-shape due
2539   // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
2540   const int nbMaps = 2;
2541   const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
2542     { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
2543   for ( int iMap = 0; iMap < nbMaps; ++iMap )
2544     for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
2545       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
2546         if ( !sm->IsMeshComputed() )
2547           sm->SetIsAlwaysComputed( true );
2548
2549   // set bad compute error to subshapes of all failed sub-shapes
2550   if ( !error->IsOK() )
2551   {
2552     bool pb2D = false, pb3D = false;
2553     for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
2554       int status = occgeo.facemeshstatus[i-1];
2555       if (status == 1 ) continue;
2556       if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
2557         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2558         if ( !smError || smError->IsOK() ) {
2559           if ( status == -1 )
2560             smError.reset( new SMESH_ComputeError( *error ));
2561           else
2562             smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
2563           if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2564             smError->myName = COMPERR_WARNING;
2565         }
2566         pb2D = pb2D || smError->IsKO();
2567       }
2568     }
2569     if ( !pb2D ) // all faces are OK
2570       for (int i = 1; i <= occgeo.somap.Extent(); i++)
2571         if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
2572         {
2573           bool smComputed = nbVol && !sm->IsEmpty();
2574           if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
2575           {
2576             int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
2577             SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2578             smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
2579           }
2580           SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2581           if ( !smComputed && ( !smError || smError->IsOK() ))
2582           {
2583             smError.reset( new SMESH_ComputeError( *error ));
2584             if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
2585               smError->myName = COMPERR_WARNING;
2586           }
2587           pb3D = pb3D || ( smError && smError->IsKO() );
2588         }
2589     if ( !pb2D && !pb3D )
2590       err = 0; // no fatal errors, only warnings
2591   }
2592
2593   return !err;
2594 }
2595
2596 //=============================================================================
2597 /*!
2598  * Evaluate
2599  */
2600 //=============================================================================
2601 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
2602 {
2603   netgen::MeshingParameters& mparams = netgen::mparam;
2604
2605
2606   // -------------------------
2607   // Prepare OCC geometry
2608   // -------------------------
2609   netgen::OCCGeometry occgeo;
2610   list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions
2611   NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2612   PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2613
2614   bool tooManyElems = false;
2615   const int hugeNb = std::numeric_limits<int>::max() / 100;
2616
2617   // ----------------
2618   // evaluate 1D 
2619   // ----------------
2620   // pass 1D simple parameters to NETGEN
2621   if ( _simpleHyp )
2622   {
2623     // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2624     mparams.uselocalh = false;
2625     mparams.grading = 0.8; // not limitited size growth
2626
2627     if ( _simpleHyp->GetNumberOfSegments() )
2628       // nb of segments
2629       mparams.maxh = occgeo.boundingbox.Diam();
2630     else
2631       // segment length
2632       mparams.maxh = _simpleHyp->GetLocalLength();
2633   }
2634
2635   if ( mparams.maxh == 0.0 )
2636     mparams.maxh = occgeo.boundingbox.Diam();
2637   if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2638     mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2639
2640   // let netgen create ngMesh and calculate element size on not meshed shapes
2641   NETGENPlugin_NetgenLibWrapper ngLib;
2642   netgen::Mesh *ngMesh = NULL;
2643   char *optstr = 0;
2644   int startWith = netgen::MESHCONST_ANALYSE;
2645   int endWith   = netgen::MESHCONST_MESHEDGES;
2646   int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
2647 #ifdef WITH_SMESH_CANCEL_COMPUTE
2648   if(netgen::multithread.terminate)
2649     return false;
2650 #endif
2651   ngLib.setMesh(( Ng_Mesh*) ngMesh );
2652   if (err) {
2653     if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
2654       sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
2655     return false;
2656   }
2657   if ( _simpleHyp )
2658   {
2659     // Pass 1D simple parameters to NETGEN
2660     // --------------------------------
2661     int      nbSeg = _simpleHyp->GetNumberOfSegments();
2662     double segSize = _simpleHyp->GetLocalLength();
2663     for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2664     {
2665       const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2666       if ( nbSeg )
2667         segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2668       setLocalSize( e, segSize, *ngMesh );
2669     }
2670   }
2671   else // if ( ! _simpleHyp )
2672   {
2673     // Local size on vertices and edges
2674     // --------------------------------
2675     for(std::map<int,double>::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
2676     {
2677       int key = (*it).first;
2678       double hi = (*it).second;
2679       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2680       const TopoDS_Edge& e = TopoDS::Edge(shape);
2681       setLocalSize( e, hi, *ngMesh );
2682     }
2683     for(std::map<int,double>::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
2684     {
2685       int key = (*it).first;
2686       double hi = (*it).second;
2687       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2688       const TopoDS_Vertex& v = TopoDS::Vertex(shape);
2689       gp_Pnt p = BRep_Tool::Pnt(v);
2690       NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi );
2691     }
2692     for(map<int,double>::const_iterator it=FaceId2LocalSize.begin();
2693         it!=FaceId2LocalSize.end(); it++)
2694     {
2695       int key = (*it).first;
2696       double val = (*it).second;
2697       const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
2698       int faceNgID = occgeo.fmap.FindIndex(shape);
2699       occgeo.SetFaceMaxH(faceNgID, val);
2700       for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
2701         setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh );
2702     }
2703   }
2704   // calculate total nb of segments and length of edges
2705   double fullLen = 0.0;
2706   int fullNbSeg = 0;
2707   int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
2708   TopTools_DataMapOfShapeInteger Edge2NbSeg;
2709   for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
2710   {
2711     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
2712     if( !Edge2NbSeg.Bind(E,0) )
2713       continue;
2714
2715     double aLen = SMESH_Algo::EdgeLength(E);
2716     fullLen += aLen;
2717
2718     vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
2719     if ( aVec.empty() )
2720       aVec.resize( SMDSEntity_Last, 0);
2721     else
2722       fullNbSeg += aVec[ entity ];
2723   }
2724
2725   // store nb of segments computed by Netgen
2726   NCollection_Map<Link> linkMap;
2727   for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
2728   {
2729     const netgen::Segment& seg = ngMesh->LineSegment(i);
2730     Link link(seg[0], seg[1]);
2731     if ( !linkMap.Add( link )) continue;
2732     int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
2733     if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2734     {
2735       vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
2736       aVec[ entity ]++;
2737     }
2738   }
2739   // store nb of nodes on edges computed by Netgen
2740   TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
2741   for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
2742   {
2743     vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
2744     if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
2745       aVec[SMDSEntity_Node] = mparams.secondorder > 0  ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
2746
2747     fullNbSeg += aVec[ entity ];
2748     Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
2749   }
2750   if ( fullNbSeg == 0 )
2751     return false;
2752
2753   // ----------------
2754   // evaluate 2D 
2755   // ----------------
2756   if ( _simpleHyp ) {
2757     if ( double area = _simpleHyp->GetMaxElementArea() ) {
2758       // face area
2759       mparams.maxh = sqrt(2. * area/sqrt(3.0));
2760       mparams.grading = 0.4; // moderate size growth
2761     }
2762     else {
2763       // length from edges
2764       mparams.maxh = fullLen/fullNbSeg;
2765       mparams.grading = 0.2; // slow size growth
2766     }
2767   }
2768   mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2769   mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2770
2771   for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
2772   {
2773     TopoDS_Face F = TopoDS::Face( exp.Current() );
2774     SMESH_subMesh *sm = _mesh->GetSubMesh(F);
2775     GProp_GProps G;
2776     BRepGProp::SurfaceProperties(F,G);
2777     double anArea = G.Mass();
2778     tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
2779     int nb1d = 0;
2780     if ( !tooManyElems )
2781     {
2782       TopTools_MapOfShape egdes;
2783       for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
2784         if ( egdes.Add( exp1.Current() ))
2785           nb1d += Edge2NbSeg.Find(exp1.Current());
2786     }
2787     int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
2788     int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
2789
2790     vector<int> aVec(SMDSEntity_Last, 0);
2791     if( mparams.secondorder > 0 ) {
2792       int nb1d_in = (nbFaces*3 - nb1d) / 2;
2793       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
2794       aVec[SMDSEntity_Quad_Triangle] = nbFaces;
2795     }
2796     else {
2797       aVec[SMDSEntity_Node] = Max ( nbNodes, 0  );
2798       aVec[SMDSEntity_Triangle] = nbFaces;
2799     }
2800     aResMap[sm].swap(aVec);
2801   }
2802
2803   // ----------------
2804   // evaluate 3D
2805   // ----------------
2806   if(_isVolume) {
2807     // pass 3D simple parameters to NETGEN
2808     const NETGENPlugin_SimpleHypothesis_3D* simple3d =
2809       dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
2810     if ( simple3d ) {
2811       if ( double vol = simple3d->GetMaxElementVolume() ) {
2812         // max volume
2813         mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
2814         mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
2815       }
2816       else {
2817         // using previous length from faces
2818       }
2819       mparams.grading = 0.4;
2820       mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
2821     }
2822     GProp_GProps G;
2823     BRepGProp::VolumeProperties(_shape,G);
2824     double aVolume = G.Mass();
2825     double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
2826     tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
2827     int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
2828     int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
2829     vector<int> aVec(SMDSEntity_Last, 0 );
2830     if ( tooManyElems ) // avoid FPE
2831     {
2832       aVec[SMDSEntity_Node] = hugeNb;
2833       aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
2834     }
2835     else
2836     {
2837       if( mparams.secondorder > 0 ) {
2838         aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
2839         aVec[SMDSEntity_Quad_Tetra] = nbVols;
2840       }
2841       else {
2842         aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
2843         aVec[SMDSEntity_Tetra] = nbVols;
2844       }
2845     }
2846     SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
2847     aResMap[sm].swap(aVec);
2848   }
2849
2850   return true;
2851 }
2852
2853 //================================================================================
2854 /*!
2855  * \brief Remove "test.out" and "problemfaces" files in current directory
2856  */
2857 //================================================================================
2858
2859 void NETGENPlugin_Mesher::RemoveTmpFiles()
2860 {
2861   if ( SMESH_File("test.out").remove() && netgen::testout)
2862   {
2863     delete netgen::testout;
2864     netgen::testout = 0;
2865   }
2866   SMESH_File("problemfaces").remove();
2867   SMESH_File("occmesh.rep").remove();
2868 }
2869
2870 //================================================================================
2871 /*!
2872  * \brief Read mesh entities preventing successful computation from "test.out" file
2873  */
2874 //================================================================================
2875
2876 SMESH_ComputeErrorPtr
2877 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
2878 {
2879   SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
2880     (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh");
2881   SMESH_File file("test.out");
2882   vector<int> two(2);
2883   const char* badEdgeStr = " multiple times in surface mesh";
2884   const int   badEdgeStrLen = strlen( badEdgeStr );
2885   while( !file.eof() )
2886   {
2887     if ( strncmp( file, "Edge ", 5 ) == 0 &&
2888          file.getInts( two ) &&
2889          strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
2890          two[0] < nodeVec.size() && two[1] < nodeVec.size())
2891     {
2892       err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
2893       file += badEdgeStrLen;
2894     }
2895     else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
2896     {
2897 // Intersecting: 
2898 // openelement 18 with open element 126
2899 // 41  36  38  
2900 // 69  70  72
2901       vector<int> three1(3), three2(3);
2902       file.getLine();
2903       const char* pos = file;
2904       bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
2905       ok = ok && file.getInts( two );
2906       ok = ok && file.getInts( three1 );
2907       ok = ok && file.getInts( three2 );
2908       for ( int i = 0; ok && i < 3; ++i )
2909         ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]);
2910       for ( int i = 0; ok && i < 3; ++i ) 
2911         ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]);
2912       if ( ok )
2913       {
2914         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
2915                                                             nodeVec[ three1[1]],
2916                                                             nodeVec[ three1[2]]));
2917         err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
2918                                                             nodeVec[ three2[1]],
2919                                                             nodeVec[ three2[2]]));
2920         err->myComment = "Intersecting triangles";
2921       }
2922       else
2923       {
2924         file.setPos( pos );
2925       }
2926     }
2927     else
2928     {
2929       ++file;
2930     }
2931   }
2932   return err;
2933 }
2934
2935 //================================================================================
2936 /*!
2937  * \brief Write a python script creating an equivalent SALOME mesh.
2938  * This is useful to see what mesh is passed as input for the next step of mesh
2939  * generation (of mesh of higher dimension)
2940  */
2941 //================================================================================
2942
2943 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh,
2944                                     const std::string&  pyFile)
2945 {
2946   ofstream outfile(pyFile.c_str(), ios::out);
2947   if ( !outfile ) return;
2948
2949   outfile << "import smesh, SMESH" << endl
2950           << "mesh = smesh.Mesh()" << endl << endl;
2951
2952   using namespace netgen;
2953   PointIndex pi;
2954   for (pi = PointIndex::BASE; 
2955        pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
2956   {
2957     outfile << "mesh.AddNode( ";
2958     outfile << (*ngMesh)[pi](0) << ", ";
2959     outfile << (*ngMesh)[pi](1) << ", ";
2960     outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl;
2961   }
2962
2963   int nbDom = ngMesh->GetNDomains();
2964   for ( int i = 0; i < nbDom; ++i )
2965     outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl;
2966
2967   SurfaceElementIndex sei;
2968   for (sei = 0; sei < ngMesh->GetNSE(); sei++)
2969   {
2970     outfile << "mesh.AddFace([ ";
2971     Element2d sel = (*ngMesh)[sei];
2972     for (int j = 0; j < sel.GetNP(); j++)
2973       outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
2974     if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
2975     outfile << endl;
2976
2977     if ((*ngMesh)[sei].GetIndex())
2978     {
2979       if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
2980         outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl;
2981       if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
2982         outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl;
2983     }
2984   }
2985
2986   for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
2987   {
2988     Element el = (*ngMesh)[ei];
2989     outfile << "mesh.AddVolume([ ";
2990     for (int j = 0; j < el.GetNP(); j++)
2991       outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
2992     outfile << endl;
2993   }
2994
2995   for (int i = 1; i <= ngMesh->GetNSeg(); i++)
2996   {
2997     const Segment & seg = ngMesh->LineSegment (i);
2998     outfile << "mesh.AddEdge([ "
2999             << seg[0] << ", "
3000             << seg[1] << " ])" << endl;
3001   }
3002   cout << "Write " << pyFile << endl;
3003 }
3004
3005 //================================================================================
3006 /*!
3007  * \brief Constructor of NETGENPlugin_ngMeshInfo
3008  */
3009 //================================================================================
3010
3011 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh):
3012   _copyOfLocalH(0)
3013 {
3014   if ( ngMesh )
3015   {
3016     _nbNodes    = ngMesh->GetNP();
3017     _nbSegments = ngMesh->GetNSeg();
3018     _nbFaces    = ngMesh->GetNSE();
3019     _nbVolumes  = ngMesh->GetNE();
3020   }
3021   else
3022   {
3023     _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3024   }
3025 }
3026
3027 //================================================================================
3028 /*!
3029  * \brief Copy LocalH member from one netgen mesh to another
3030  */
3031 //================================================================================
3032
3033 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3034                                               netgen::Mesh* toMesh )
3035 {
3036   if ( !fromMesh->LocalHFunctionGenerated() ) return;
3037   if ( !toMesh->LocalHFunctionGenerated() )
3038     toMesh->CalcLocalH();
3039
3040   const size_t size = sizeof( netgen::LocalH );
3041   _copyOfLocalH = new char[ size ];
3042   memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3043   memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3044 }
3045
3046 //================================================================================
3047 /*!
3048  * \brief Restore LocalH member of a netgen mesh
3049  */
3050 //================================================================================
3051
3052 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3053 {
3054   if ( _copyOfLocalH )
3055   {
3056     const size_t size = sizeof( netgen::LocalH );
3057     memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3058     delete [] _copyOfLocalH;
3059     _copyOfLocalH = 0;
3060   }
3061 }
3062
3063 //================================================================================
3064 /*!
3065  * \brief Find "internal" sub-shapes
3066  */
3067 //================================================================================
3068
3069 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh&         mesh,
3070                                                 const TopoDS_Shape& shape,
3071                                                 bool                is3D )
3072   : _mesh( mesh ), _is3D( is3D )
3073 {
3074   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3075
3076   TopExp_Explorer f,e;
3077   for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
3078   {
3079     int faceID = meshDS->ShapeToIndex( f.Current() );
3080
3081     // find not computed internal edges
3082
3083     for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
3084       if ( e.Current().Orientation() == TopAbs_INTERNAL )
3085       {
3086         SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
3087         if ( eSM->IsEmpty() )
3088         {
3089           _e2face.insert( make_pair( eSM->GetId(), faceID ));
3090           for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
3091             _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
3092         }
3093       }
3094
3095     // find internal vertices in a face
3096     set<int> intVV; // issue 0020850 where same vertex is twice in a face
3097     for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
3098       if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
3099       {
3100         int vID = meshDS->ShapeToIndex( fSub.Value() );
3101         if ( intVV.insert( vID ).second )
3102           _f2v[ faceID ].push_back( vID );
3103       }
3104
3105     if ( is3D )
3106     {
3107       // find internal faces and their subshapes where nodes are to be doubled
3108       //  to make a crack with non-sewed borders
3109
3110       if ( f.Current().Orientation() == TopAbs_INTERNAL )
3111       {
3112         _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
3113
3114         // egdes
3115         list< TopoDS_Shape > edges;
3116         for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
3117           if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
3118           {
3119             _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
3120             edges.push_back( e.Current() );
3121             // find border faces
3122             PShapeIteratorPtr fIt =
3123               SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
3124             while ( const TopoDS_Shape* pFace = fIt->next() )
3125               if ( !pFace->IsSame( f.Current() ))
3126                 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
3127           }
3128         // vertices
3129         // we consider vertex internal if it is shared by more than one internal edge
3130         list< TopoDS_Shape >::iterator edge = edges.begin();
3131         for ( ; edge != edges.end(); ++edge )
3132           for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
3133           {
3134             set<int> internalEdges;
3135             PShapeIteratorPtr eIt =
3136               SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
3137             while ( const TopoDS_Shape* pEdge = eIt->next() )
3138             {
3139               int edgeID = meshDS->ShapeToIndex( *pEdge );
3140               if ( isInternalShape( edgeID ))
3141                 internalEdges.insert( edgeID );
3142             }
3143             if ( internalEdges.size() > 1 )
3144               _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
3145           }
3146       }
3147     }
3148   } // loop on geom faces
3149
3150   // find vertices internal in solids
3151   if ( is3D )
3152   {
3153     for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
3154     {
3155       int soID = meshDS->ShapeToIndex( so.Current() );
3156       for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
3157         if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
3158           _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
3159     }
3160   }
3161 }
3162
3163 //================================================================================
3164 /*!
3165  * \brief Find mesh faces on non-internal geom faces sharing internal edge
3166  * some nodes of which are to be doubled to make the second border of the "crack"
3167  */
3168 //================================================================================
3169
3170 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
3171 {
3172   if ( _intShapes.empty() ) return;
3173
3174   SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
3175   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
3176
3177   // loop on internal geom edges
3178   set<int>::const_iterator intShapeId = _intShapes.begin();
3179   for ( ; intShapeId != _intShapes.end(); ++intShapeId )
3180   {
3181     const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
3182     if ( s.ShapeType() != TopAbs_EDGE ) continue;
3183
3184     // get internal and non-internal geom faces sharing the internal edge <s>
3185     int intFace = 0;
3186     set<int>::iterator bordFace = _borderFaces.end();
3187     PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
3188     while ( const TopoDS_Shape* pFace = faces->next() )
3189     {
3190       int faceID = meshDS->ShapeToIndex( *pFace );
3191       if ( isInternalShape( faceID ))
3192         intFace = faceID;
3193       else
3194         bordFace = _borderFaces.insert( faceID ).first;
3195     }
3196     if ( bordFace == _borderFaces.end() || !intFace ) continue;
3197
3198     // get all links of mesh faces on internal geom face sharing nodes on edge <s>
3199     set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
3200     list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
3201     int nbSuspectFaces = 0;
3202     SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
3203     if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
3204     SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
3205     while ( smIt->more() )
3206     {
3207       SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
3208       if ( !sm ) continue;
3209       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3210       while ( nIt->more() )
3211       {
3212         const SMDS_MeshNode* nOnEdge = nIt->next();
3213         SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
3214         while ( fIt->more() )
3215         {
3216           const SMDS_MeshElement* f = fIt->next();
3217           int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3218           if ( intFaceSM->Contains( f ))
3219           {
3220             for ( int i = 0; i < nbNodes; ++i )
3221               links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
3222           }
3223           else
3224           {
3225             int nbDblNodes = 0;
3226             for ( int i = 0; i < nbNodes; ++i )
3227               nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() );
3228             if ( nbDblNodes )
3229               suspectFaces[ nbDblNodes < 2 ].push_back( f );
3230             nbSuspectFaces++;
3231           }
3232         }
3233       }
3234     }
3235     // suspectFaces[0] having link with same orientation as mesh faces on
3236     // the internal geom face are <borderElems>. suspectFaces[1] have
3237     // only one node on edge <s>, we decide on them later (at the 2nd loop)
3238     // by links of <borderElems> found at the 1st and 2nd loops
3239     set< SMESH_OrientedLink > borderLinks;
3240     for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
3241     {
3242       list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
3243       for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
3244       {
3245         const SMDS_MeshElement* f = *fIt;
3246         bool isBorder = false, linkFound = false, borderLinkFound = false;
3247         list< SMESH_OrientedLink > faceLinks;
3248         int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 );
3249         for ( int i = 0; i < nbNodes; ++i )
3250         {
3251           SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
3252           faceLinks.push_back( link );
3253           if ( !linkFound )
3254           {
3255             set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
3256             if ( foundLink != links.end() )
3257             {
3258               linkFound= true;
3259               isBorder = ( foundLink->_reversed == link._reversed );
3260               if ( !isBorder && !isPostponed ) break;
3261               faceLinks.pop_back();
3262             }
3263             else if ( isPostponed && !borderLinkFound )
3264             {
3265               foundLink = borderLinks.find( link );
3266               if ( foundLink != borderLinks.end() )
3267               {
3268                 borderLinkFound = true;
3269                 isBorder = ( foundLink->_reversed != link._reversed );
3270               }
3271             }
3272           }
3273         }
3274         if ( isBorder )
3275         {
3276           borderElems.insert( f );
3277           borderLinks.insert( faceLinks.begin(), faceLinks.end() );
3278         }
3279         else if ( !linkFound && !borderLinkFound )
3280         {
3281           suspectFaces[1].push_back( f );
3282           if ( nbF > 2 * nbSuspectFaces )
3283             break; // dead loop protection
3284         }
3285       }
3286     }
3287   }
3288 }
3289
3290 //================================================================================
3291 /*!
3292  * \brief put internal shapes in maps and fill in submeshes to precompute
3293  */
3294 //================================================================================
3295
3296 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
3297                                                TopTools_IndexedMapOfShape& emap,
3298                                                TopTools_IndexedMapOfShape& vmap,
3299                                                list< SMESH_subMesh* > smToPrecompute[])
3300 {
3301   if ( !hasInternalEdges() ) return;
3302   map<int,int>::const_iterator ev_face = _e2face.begin();
3303   for ( ; ev_face != _e2face.end(); ++ev_face )
3304   {
3305     const TopoDS_Shape& ev   = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
3306     const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
3307
3308     ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
3309     fmap.Add( face );
3310     //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
3311
3312     smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
3313   }
3314 }
3315
3316 //================================================================================
3317 /*!
3318  * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
3319  */
3320 //================================================================================
3321
3322 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
3323                                                TopTools_IndexedMapOfShape& emap,
3324                                                list< SMESH_subMesh* >&     intFaceSM,
3325                                                list< SMESH_subMesh* >&     boundarySM)
3326 {
3327   if ( !hasInternalFaces() ) return;
3328
3329   // <fmap> and <emap> are for not yet meshed shapes
3330   // <intFaceSM> is for submeshes of faces
3331   // <boundarySM> is for meshed edges and vertices
3332
3333   intFaceSM.clear();
3334   boundarySM.clear();
3335
3336   set<int> shapeIDs ( _intShapes );
3337   if ( !_borderFaces.empty() )
3338     shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
3339
3340   set<int>::const_iterator intS = shapeIDs.begin();
3341   for ( ; intS != shapeIDs.end(); ++intS )
3342   {
3343     SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
3344
3345     if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
3346
3347     intFaceSM.push_back( sm );
3348
3349     // add submeshes of not computed internal faces
3350     if ( !sm->IsEmpty() ) continue;
3351
3352     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
3353     while ( smIt->more() )
3354     {
3355       sm = smIt->next();
3356       const TopoDS_Shape& s = sm->GetSubShape();
3357
3358       if ( sm->IsEmpty() )
3359       {
3360         // not yet meshed
3361         switch ( s.ShapeType() ) {
3362         case TopAbs_FACE: fmap.Add ( s ); break;
3363         case TopAbs_EDGE: emap.Add ( s ); break;
3364         default:;
3365         }
3366       }
3367       else
3368       {
3369         if ( s.ShapeType() != TopAbs_FACE )
3370           boundarySM.push_back( sm );
3371       }
3372     }
3373   }
3374 }
3375
3376 //================================================================================
3377 /*!
3378  * \brief Return true if given shape is to be precomputed in order to be correctly
3379  * added to netgen mesh
3380  */
3381 //================================================================================
3382
3383 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
3384 {
3385   int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
3386   switch ( s.ShapeType() ) {
3387   case TopAbs_FACE  : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
3388   case TopAbs_EDGE  : return isInternalEdge( shapeID );
3389   case TopAbs_VERTEX: break;
3390   default:;
3391   }
3392   return false;
3393 }
3394
3395 //================================================================================
3396 /*!
3397  * \brief Return SMESH
3398  */
3399 //================================================================================
3400
3401 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
3402 {
3403   return const_cast<SMESH_Mesh&>( _mesh );
3404 }
3405
3406 //================================================================================
3407 /*!
3408  * \brief Initialize netgen library
3409  */
3410 //================================================================================
3411
3412 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
3413 {
3414   Ng_Init();
3415   _ngMesh = Ng_NewMesh();
3416 }
3417
3418 //================================================================================
3419 /*!
3420  * \brief Finish using netgen library
3421  */
3422 //================================================================================
3423
3424 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
3425 {
3426   Ng_DeleteMesh( _ngMesh );
3427   Ng_Exit();
3428   NETGENPlugin_Mesher::RemoveTmpFiles();
3429 }
3430
3431 //================================================================================
3432 /*!
3433  * \brief Set netgen mesh to delete at destruction
3434  */
3435 //================================================================================
3436
3437 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
3438 {
3439   if ( _ngMesh )
3440     Ng_DeleteMesh( _ngMesh );
3441   _ngMesh = mesh;
3442 }