Salome HOME
Update copyright
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2011  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Group.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42
43 #include "utilities.h"
44
45 #include <BRep_Tool.hxx>
46 #include <GCPnts_AbscissaPoint.hxx>
47 #include <GeomAdaptor_Curve.hxx>
48 #include <Geom_Curve.hxx>
49 #include <Precision.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_IndexedMapOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
54 #include <TopoDS.hxx>
55 #include <TopoDS_Edge.hxx>
56 #include <TopoDS_Face.hxx>
57 #include <TopoDS_Vertex.hxx>
58 #include <gp_Ax1.hxx>
59 #include <gp_Vec.hxx>
60 #include <gp_XY.hxx>
61 #include <gp_XYZ.hxx>
62
63 #include <list>
64 #include <string>
65 #include <math.h>
66 #include <limits>
67
68 //#define __myDEBUG
69
70 using namespace std;
71
72 //================================================================================
73 namespace VISCOUS
74 {
75   typedef int TGeomID;
76
77   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
78
79   /*!
80    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
81    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
82    */
83   struct _MeshOfSolid : public SMESH_ProxyMesh,
84                         public SMESH_subMeshEventListenerData
85   {
86     bool _n2nMapComputed;
87
88     _MeshOfSolid( SMESH_Mesh* mesh)
89       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
90     {
91       SMESH_ProxyMesh::setMesh( *mesh );
92     }
93
94     // returns submesh for a geom face
95     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
96     {
97       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
98       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
99     }
100     void setNode2Node(const SMDS_MeshNode*                 srcNode,
101                       const SMDS_MeshNode*                 proxyNode,
102                       const SMESH_ProxyMesh::SubMesh* subMesh)
103     {
104       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
105     }
106   };
107   //--------------------------------------------------------------------------------
108   /*!
109    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
110    * It is used to clear an inferior dim sub-mesh modified by viscous layers
111    */
112   class _SrinkShapeListener : SMESH_subMeshEventListener
113   {
114     _SrinkShapeListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
115     static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
116   public:
117     virtual void ProcessEvent(const int                       event,
118                               const int                       eventType,
119                               SMESH_subMesh*                  solidSM,
120                               SMESH_subMeshEventListenerData* data,
121                               const SMESH_Hypothesis*         hyp)
122     {
123       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
124       {
125         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
126       }
127     }
128     static void ToClearSubMeshWithSolid( SMESH_subMesh*      sm,
129                                          const TopoDS_Shape& solid)
130     {
131       SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
132       SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
133       if ( data )
134       {
135         if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
136              data->mySubMeshes.end())
137           data->mySubMeshes.push_back( sm );
138       }
139       else
140       {
141         data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
142         sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
143       }
144     }
145   };
146   //--------------------------------------------------------------------------------
147   /*!
148    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
149    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
150    * delete the data as soon as it has been used
151    */
152   class _ViscousListener : SMESH_subMeshEventListener
153   {
154     _ViscousListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
155     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
156   public:
157     virtual void ProcessEvent(const int                       event,
158                               const int                       eventType,
159                               SMESH_subMesh*                  subMesh,
160                               SMESH_subMeshEventListenerData* data,
161                               const SMESH_Hypothesis*         hyp)
162     {
163       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
164       {
165         // delete SMESH_ProxyMesh containing temporary faces
166         subMesh->DeleteEventListener( this );
167       }
168     }
169     // Finds or creates proxy mesh of the solid
170     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
171                                       const TopoDS_Shape& solid,
172                                       bool                toCreate=false)
173     {
174       if ( !mesh ) return 0;
175       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
176       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
177       if ( !data && toCreate )
178       {
179         data = new _MeshOfSolid(mesh);
180         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
181         sm->SetEventListener( Get(), data, sm );
182       }
183       return data;
184     }
185     // Removes proxy mesh of the solid
186     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
187     {
188       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
189     }
190   };
191   
192   //--------------------------------------------------------------------------------
193   /*!
194    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
195    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
196    * The class is used to check validity of face or volumes around a smoothed node;
197    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
198    */
199   struct _Simplex
200   {
201     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
202     _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
203       : _nPrev(nPrev), _nNext(nNext) {}
204     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
205     {
206       const double M[3][3] =
207         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
208          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
209          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
210       double determinant = ( + M[0][0]*M[1][1]*M[2][2]
211                              + M[0][1]*M[1][2]*M[2][0]
212                              + M[0][2]*M[1][0]*M[2][1]
213                              - M[0][0]*M[1][2]*M[2][1]
214                              - M[0][1]*M[1][0]*M[2][2]
215                              - M[0][2]*M[1][1]*M[2][0]);
216       return determinant > 1e-100;
217     }
218     bool IsForward(const gp_XY&        tgtUV,
219                    const TopoDS_Face&  face,
220                    SMESH_MesherHelper& helper,
221                    const double        refSign) const
222     {
223       gp_XY prevUV = helper.GetNodeUV( face, _nPrev );
224       gp_XY nextUV = helper.GetNodeUV( face, _nNext );
225       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
226       double d = v1 ^ v2;
227       return d*refSign > 1e-100;
228     }
229   };
230   //--------------------------------------------------------------------------------
231   /*!
232    * Structure used to take into account surface curvature while smoothing
233    */
234   struct _Curvature
235   {
236     double _r; // radius
237     double _k; // factor to correct node smoothed position
238   public:
239     static _Curvature* New( double avgNormProj, double avgDist )
240     {
241       _Curvature* c = 0;
242       if ( fabs( avgNormProj / avgDist ) > 1./200 )
243       {
244         c = new _Curvature;
245         c->_r = avgDist * avgDist / avgNormProj;
246         c->_k = avgDist * avgDist / c->_r / c->_r;
247         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
248       }
249       return c;
250     }
251     double lenDelta(double len) const { return _k * ( _r + len ); }
252   };
253   struct _LayerEdge;
254   //--------------------------------------------------------------------------------
255   /*!
256    * Structure used to smooth a _LayerEdge (master) based on an EDGE.
257    */
258   struct _2NearEdges
259   {
260     // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
261     const SMDS_MeshNode* _nodes[2];
262     // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
263     //gp_XYZ               _vec[2];
264     double               _wgt[2]; // weights of _nodes
265     _LayerEdge*          _edges[2];
266
267      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
268     gp_XYZ*              _plnNorm;
269
270     _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
271   };
272   //--------------------------------------------------------------------------------
273   /*!
274    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
275    * and a node of the most internal layer (_nodes.back())
276    */
277   struct _LayerEdge
278   {
279     vector< const SMDS_MeshNode*> _nodes;
280
281     gp_XYZ              _normal; // to solid surface
282     vector<gp_XYZ>      _pos; // points computed during inflation
283     double              _len; // length achived with the last step
284     double              _cosin; // of angle (_normal ^ surface)
285     double              _lenFactor; // to compute _len taking _cosin into account
286
287     // face or edge w/o layer along or near which _LayerEdge is inflated
288     TopoDS_Shape        _sWOL;
289     // simplices connected to the source node (_nodes[0]);
290     // used for smoothing and quality check of _LayerEdge's based on the FACE
291     vector<_Simplex>    _simplices;
292     // data for smoothing of _LayerEdge's based on the EDGE
293     _2NearEdges*        _2neibors;
294
295     _Curvature*         _curvature;
296     // TODO:: detele _Curvature, _plnNorm
297
298     void SetNewLength( double len, SMESH_MesherHelper& helper );
299     bool SetNewLength2d( Handle(Geom_Surface)& surface,
300                          const TopoDS_Face&    F,
301                          SMESH_MesherHelper&   helper );
302     void SetDataByNeighbors( const SMDS_MeshNode* n1,
303                              const SMDS_MeshNode* n2,
304                              SMESH_MesherHelper&  helper);
305     void InvalidateStep( int curStep );
306     bool Smooth(int& badNb);
307     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
308                       const TopoDS_Face&    F,
309                       SMESH_MesherHelper&   helper);
310     bool FindIntersection( SMESH_ElementSearcher&   searcher,
311                            double &                 distance,
312                            const double&            epsilon,
313                            const SMDS_MeshElement** face = 0);
314     bool SegTriaInter( const gp_Ax1&        lastSegment,
315                        const SMDS_MeshNode* n0,
316                        const SMDS_MeshNode* n1,
317                        const SMDS_MeshNode* n2,
318                        double&              dist,
319                        const double&        epsilon) const;
320     gp_Ax1 LastSegment(double& segLen) const;
321     bool IsOnEdge() const { return _2neibors; }
322     void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
323     void SetCosin( double cosin );
324   };
325   struct _LayerEdgeCmp
326   {
327     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
328     {
329       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
330       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
331     }
332   };
333   //--------------------------------------------------------------------------------
334
335   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
336   
337   //--------------------------------------------------------------------------------
338   /*!
339    * \brief Data of a SOLID
340    */
341   struct _SolidData
342   {
343     TopoDS_Shape                    _solid;
344     const StdMeshers_ViscousLayers* _hyp;
345     _MeshOfSolid*                   _proxyMesh;
346     set<TGeomID>                    _reversedFaceIds;
347
348     double                          _stepSize, _stepSizeCoeff;
349     const SMDS_MeshNode*            _stepSizeNodes[2];
350
351     TNode2Edge                      _n2eMap;
352     // edges of _n2eMap. We keep same data in two containers because
353     // iteration over the map is 5 time longer than over the vector
354     vector< _LayerEdge* >           _edges;
355
356     // key: an id of shape (EDGE or VERTEX) shared by a FACE with
357     // layers and a FACE w/o layers
358     // value: the shape (FACE or EDGE) to shrink mesh on.
359     // _LayerEdge's basing on nodes on key shape are inflated along the value shape
360     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
361
362     // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
363     set< TGeomID >                   _noShrinkFaces;
364
365     // end index in _edges of _LayerEdge's based on EDGE (map key) to
366     // FACE (maybe NULL) they are inflated along
367     //map< int, TopoDS_Face >          _endEdge2Face;
368
369     // end indices in _edges of _LayerEdge on one shape to smooth
370     vector< int >                    _endEdgeToSmooth;
371
372     double                           _epsilon; // precision for SegTriaInter()
373
374     int                              _index; // for debug
375
376     _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
377                const StdMeshers_ViscousLayers* h=0,
378                _MeshOfSolid*                   m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
379     ~_SolidData();
380   };
381   //--------------------------------------------------------------------------------
382   /*!
383    * \brief Data of node on a shrinked FACE
384    */
385   struct _SmoothNode
386   {
387     const SMDS_MeshNode*         _node;
388     //vector<const SMDS_MeshNode*> _nodesAround;
389     vector<_Simplex>             _simplices; // for quality check
390
391     bool Smooth(int&                  badNb,
392                 Handle(Geom_Surface)& surface,
393                 SMESH_MesherHelper&   helper,
394                 const double          refSign,
395                 bool                  set3D);
396   };
397   //--------------------------------------------------------------------------------
398   /*!
399    * \brief Builder of viscous layers
400    */
401   class _ViscousBuilder
402   {
403   public:
404     _ViscousBuilder();
405     // does it's job
406     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
407                                   const TopoDS_Shape& shape);
408
409     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
410     void RestoreListeners();
411
412     // computes SMESH_ProxyMesh::SubMesh::_n2n;
413     bool MakeN2NMap( _MeshOfSolid* pm );
414
415   private:
416
417     bool findSolidsWithLayers();
418     bool findFacesWithLayers();
419     bool makeLayer(_SolidData& data);
420     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
421                      SMESH_MesherHelper& helper, _SolidData& data);
422     bool findNeiborsOnEdge(const _LayerEdge*     edge,
423                            const SMDS_MeshNode*& n1,
424                            const SMDS_MeshNode*& n2,
425                            _SolidData&           data);
426     void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
427                        const set<TGeomID>& ingnoreShapes,
428                        const _SolidData* dataToCheckOri = 0);
429     bool sortEdges( _SolidData&                    data,
430                     vector< vector<_LayerEdge*> >& edgesByGeom);
431     void limitStepSize( _SolidData&             data,
432                         const SMDS_MeshElement* face,
433                         const double            cosin);
434     void limitStepSize( _SolidData& data, const double minSize);
435     bool inflate(_SolidData& data);
436     bool smoothAndCheck(_SolidData& data, int nbSteps, double & distToIntersection);
437     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
438     bool refine(_SolidData& data);
439     bool shrink();
440     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
441                               SMESH_MesherHelper& helper,
442                               const SMESHDS_SubMesh* faceSubMesh );
443     bool addBoundaryElements();
444
445     bool error( const string& text, int solidID=-1 );
446     SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
447
448     // debug
449     void makeGroupOfLE();
450
451     SMESH_Mesh*           _mesh;
452     SMESH_ComputeErrorPtr _error;
453
454     vector< _SolidData >  _sdVec;
455     set<TGeomID>          _ignoreShapeIds;
456     int                   _tmpFaceID;
457   };
458   //--------------------------------------------------------------------------------
459   /*!
460    * \brief Shrinker of nodes on the EDGE
461    */
462   class _Shrinker1D
463   {
464     vector<double>                _initU;
465     vector<double>                _normPar;
466     vector<const SMDS_MeshNode*>  _nodes;
467     const _LayerEdge*             _edges[2];
468     bool                          _done;
469   public:
470     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
471     void Compute(bool set3D, SMESH_MesherHelper& helper);
472     void RestoreParams();
473     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
474   };
475   //--------------------------------------------------------------------------------
476   /*!
477    * \brief Class of temporary mesh face.
478    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
479    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
480    */
481   struct TmpMeshFace : public SMDS_MeshElement
482   {
483     vector<const SMDS_MeshNode* > _nn;
484     TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
485       SMDS_MeshElement(id), _nn(nodes) {}
486     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
487     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
488     virtual vtkIdType GetVtkType() const                      { return -1; }
489     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
490     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
491     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
492   };
493   //--------------------------------------------------------------------------------
494   /*!
495    * \brief Class of temporary mesh face storing _LayerEdge it's based on
496    */
497   struct TmpMeshFaceOnEdge : public TmpMeshFace
498   {
499     _LayerEdge *_le1, *_le2;
500     TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
501       TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
502     {
503       _nn[0]=_le1->_nodes[0];
504       _nn[1]=_le1->_nodes.back();
505       _nn[2]=_le2->_nodes.back();
506       _nn[3]=_le2->_nodes[0];
507     }
508   };
509 } // namespace VISCOUS
510
511 //================================================================================
512 // StdMeshers_ViscousLayers hypothesis
513 //
514 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
515   :SMESH_Hypothesis(hypId, studyId, gen),
516    _nbLayers(1), _thickness(1), _stretchFactor(1)
517 {
518   _name = StdMeshers_ViscousLayers::GetHypType();
519   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
520 } // --------------------------------------------------------------------------------
521 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
522 {
523   if ( faceIds != _ignoreFaceIds )
524     _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
525 } // --------------------------------------------------------------------------------
526 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
527 {
528   if ( thickness != _thickness )
529     _thickness = thickness, NotifySubMeshesHypothesisModification();
530 } // --------------------------------------------------------------------------------
531 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
532 {
533   if ( _nbLayers != nb )
534     _nbLayers = nb, NotifySubMeshesHypothesisModification();
535 } // --------------------------------------------------------------------------------
536 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
537 {
538   if ( _stretchFactor != factor )
539     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
540 } // --------------------------------------------------------------------------------
541 SMESH_ProxyMesh::Ptr
542 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
543                                   const TopoDS_Shape& theShape,
544                                   const bool          toMakeN2NMap) const
545 {
546   using namespace VISCOUS;
547   _ViscousBuilder bulder;
548   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
549   if ( err && !err->IsOK() )
550     return SMESH_ProxyMesh::Ptr();
551
552   vector<SMESH_ProxyMesh::Ptr> components;
553   TopExp_Explorer exp( theShape, TopAbs_SOLID );
554   for ( ; exp.More(); exp.Next() )
555   {
556     if ( _MeshOfSolid* pm =
557          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
558     {
559       if ( toMakeN2NMap && !pm->_n2nMapComputed )
560         if ( !bulder.MakeN2NMap( pm ))
561           return SMESH_ProxyMesh::Ptr();
562       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
563       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
564     }
565     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
566   }
567   switch ( components.size() )
568   {
569   case 0: break;
570
571   case 1: return components[0];
572
573   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
574   }
575   return SMESH_ProxyMesh::Ptr();
576 } // --------------------------------------------------------------------------------
577 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
578 {
579   save << " " << _nbLayers
580        << " " << _thickness
581        << " " << _stretchFactor
582        << " " << _ignoreFaceIds.size();
583   for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
584     save << " " << _ignoreFaceIds[i];
585   return save;
586 } // --------------------------------------------------------------------------------
587 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
588 {
589   int nbFaces, faceID;
590   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
591   while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
592     _ignoreFaceIds.push_back( faceID );
593   return load;
594 } // --------------------------------------------------------------------------------
595 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
596                                                    const TopoDS_Shape& theShape)
597 {
598   // TODO
599   return false;
600 }
601 // END StdMeshers_ViscousLayers hypothesis
602 //================================================================================
603
604 namespace
605 {
606   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
607   {
608     gp_Vec dir;
609     double f,l;
610     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
611     gp_Pnt p = BRep_Tool::Pnt( fromV );
612     double distF = p.SquareDistance( c->Value( f ));
613     double distL = p.SquareDistance( c->Value( l ));
614     c->D1(( distF < distL ? f : l), p, dir );
615     if ( distL < distF ) dir.Reverse();
616     return dir.XYZ();
617   }
618   //--------------------------------------------------------------------------------
619   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
620                      SMESH_MesherHelper& helper)
621   {
622     gp_Vec dir;
623     double f,l; gp_Pnt p;
624     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
625     double u = helper.GetNodeU( E, atNode );
626     c->D1( u, p, dir );
627     return dir.XYZ();
628   }
629   //--------------------------------------------------------------------------------
630   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
631                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
632   {
633     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
634     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
635     gp_Pnt p; gp_Vec du, dv, norm;
636     surface->D1( uv.X(),uv.Y(), p, du,dv );
637     norm = du ^ dv;
638
639     double f,l;
640     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
641     double u = helper.GetNodeU( fromE, node, 0, &ok );
642     c->D1( u, p, du );
643     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
644     if ( o == TopAbs_REVERSED )
645       du.Reverse();
646
647     gp_Vec dir = norm ^ du;
648
649     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
650          helper.IsClosedEdge( fromE ))
651     {
652       if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
653       else                         c->D1( f, p, dv );
654       if ( o == TopAbs_REVERSED )
655         dv.Reverse();
656       gp_Vec dir2 = norm ^ dv;
657       dir = dir.Normalized() + dir2.Normalized();
658     }
659     return dir.XYZ();
660   }
661   //--------------------------------------------------------------------------------
662   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
663                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
664                      bool& ok, double* cosin=0)
665   {
666     double f,l; TopLoc_Location loc;
667     vector< TopoDS_Edge > edges; // sharing a vertex
668     PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
669     while ( eIt->more())
670     {
671       const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
672       if ( helper.IsSubShape( *e, F ) && BRep_Tool::Curve( *e, loc,f,l))
673         edges.push_back( *e );
674     }
675     gp_XYZ dir(0,0,0);
676     if ( !( ok = ( edges.size() > 0 ))) return dir;
677     // get average dir of edges going fromV
678     gp_Vec edgeDir;
679     for ( unsigned i = 0; i < edges.size(); ++i )
680     {
681       edgeDir = getEdgeDir( edges[i], fromV );
682       double size2 = edgeDir.SquareMagnitude();
683       if ( size2 > numeric_limits<double>::min() )
684         edgeDir /= sqrt( size2 );
685       else
686         ok = false;
687       dir += edgeDir.XYZ();
688     }
689     gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
690     if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
691       dir = fromEdgeDir;
692     else if ( dir * fromEdgeDir < 0 )
693       dir *= -1;
694     if ( ok )
695     {
696       //dir /= edges.size();
697       if ( cosin ) {
698         double angle = edgeDir.Angle( dir );
699         *cosin = cos( angle );
700       }
701     }
702     return dir;
703   }
704   //--------------------------------------------------------------------------------
705   // DEBUG. Dump intermediate node positions into a python script
706 #ifdef __myDEBUG
707   ofstream* py;
708   struct PyDump {
709     PyDump() {
710       const char* fname = "/tmp/viscous.py";
711       cout << "execfile('"<<fname<<"')"<<endl;
712       py = new ofstream(fname);
713       *py << "from smesh import *" << endl
714           << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
715           << "mesh = Mesh( meshSO.GetObject()._narrow( SMESH.SMESH_Mesh ))"<<endl;
716     }
717     ~PyDump() {
718       *py << "mesh.MakeGroup('Prisms of viscous layers',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"
719           <<endl; delete py; py=0;
720     }
721   };
722 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
723 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
724 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
725   void _dumpFunction(const string& fun, int ln)
726   { *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
727   void _dumpMove(const SMDS_MeshNode* n, int ln)
728   { *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
729        << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
730   void _dumpCmd(const string& txt, int ln)
731   { *py<< "  "<<txt<<" # "<< ln <<endl; }
732   void dumpFunctionEnd()
733   { *py<< "  return"<< endl; }
734 #else
735   struct PyDump { PyDump() {} };
736   void dumpFunction(const string& fun ){}
737   void dumpFunctionEnd() {}
738   void dumpMove(const SMDS_MeshNode* n ){}
739   void dumpCmd(const string& txt){}
740 #endif
741 }
742
743 using namespace VISCOUS;
744
745 //================================================================================
746 /*!
747  * \brief Constructor of _ViscousBuilder
748  */
749 //================================================================================
750
751 _ViscousBuilder::_ViscousBuilder()
752 {
753   _error = SMESH_ComputeError::New(COMPERR_OK);
754   _tmpFaceID = 0;
755 }
756
757 //================================================================================
758 /*!
759  * \brief Stores error description and returns false
760  */
761 //================================================================================
762
763 bool _ViscousBuilder::error(const string& text, int solidId )
764 {
765   _error->myName    = COMPERR_ALGO_FAILED;
766   _error->myComment = string("Viscous layers builder: ") + text;
767   if ( _mesh )
768   {
769     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
770     if ( !sm && !_sdVec.empty() )
771       sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
772     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
773     {
774       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
775       if ( smError && smError->myAlgo )
776         _error->myAlgo = smError->myAlgo;
777       smError = _error;
778     }
779   }
780   makeGroupOfLE(); // debug
781
782   return false;
783 }
784
785 //================================================================================
786 /*!
787  * \brief At study restoration, restore event listeners used to clear an inferior
788  *  dim sub-mesh modified by viscous layers
789  */
790 //================================================================================
791
792 void _ViscousBuilder::RestoreListeners()
793 {
794   // TODO
795 }
796
797 //================================================================================
798 /*!
799  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
800  */
801 //================================================================================
802
803 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
804 {
805   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
806   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
807   for ( ; fExp.More(); fExp.Next() )
808   {
809     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
810     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
811
812     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
813       continue;
814     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
815       continue;
816
817     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
818       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
819
820     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
821     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
822     while( prxIt->more() )
823     {
824       const SMDS_MeshElement* fSrc = srcIt->next();
825       const SMDS_MeshElement* fPrx = prxIt->next();
826       if ( fSrc->NbNodes() != fPrx->NbNodes())
827         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
828       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
829         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
830     }
831   }
832   pm->_n2nMapComputed = true;
833   return true;
834 }
835
836 //================================================================================
837 /*!
838  * \brief Does its job
839  */
840 //================================================================================
841
842 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
843                                                const TopoDS_Shape& theShape)
844 {
845   // TODO: set priority of solids during Gen::Compute()
846
847   _mesh = & theMesh;
848
849   // check if proxy mesh already computed
850   TopExp_Explorer exp( theShape, TopAbs_SOLID );
851   if ( !exp.More() )
852     return error("No SOLID's in theShape"), _error;
853
854   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
855     return SMESH_ComputeErrorPtr(); // everything already computed
856
857   PyDump debugDump;
858
859   // TODO: ignore already computed SOLIDs 
860   if ( !findSolidsWithLayers())
861     return _error;
862
863   if ( !findFacesWithLayers() )
864     return _error;
865
866   for ( unsigned i = 0; i < _sdVec.size(); ++i )
867   {
868     if ( ! makeLayer(_sdVec[i]) )
869       return _error;
870     
871     if ( ! inflate(_sdVec[i]) )
872       return _error;
873
874     if ( ! refine(_sdVec[i]) )
875       return _error;
876   }
877   if ( !shrink() )
878     return _error;
879
880   addBoundaryElements();
881   
882   makeGroupOfLE(); // debug
883
884   return _error;
885 }
886
887 //================================================================================
888 /*!
889  * \brief Finds SOLIDs to compute using viscous layers. Fill _sdVec
890  */
891 //================================================================================
892
893 bool _ViscousBuilder::findSolidsWithLayers()
894 {
895   // get all solids
896   TopTools_IndexedMapOfShape allSolids;
897   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
898   _sdVec.reserve( allSolids.Extent());
899
900   SMESH_Gen* gen = _mesh->GetGen();
901   for ( int i = 1; i <= allSolids.Extent(); ++i )
902   {
903     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
904     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
905     if ( !algo ) continue;
906     // TODO: check if algo is hidden
907     const list <const SMESHDS_Hypothesis *> & allHyps =
908       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
909     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
910     const StdMeshers_ViscousLayers* viscHyp = 0;
911     for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
912       viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
913     if ( viscHyp )
914     {
915       _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
916                                                                 allSolids(i),
917                                                                 /*toCreate=*/true);
918       _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
919       _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
920     }
921   }
922   if ( _sdVec.empty() )
923     return error
924       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
925
926   return true;
927 }
928
929 //================================================================================
930 /*!
931  * \brief 
932  */
933 //================================================================================
934
935 bool _ViscousBuilder::findFacesWithLayers()
936 {
937   // collect all faces to ignore defined by hyp
938   vector<TopoDS_Shape> ignoreFaces;
939   for ( unsigned i = 0; i < _sdVec.size(); ++i )
940   {
941     vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
942     for ( unsigned i = 0; i < ids.size(); ++i )
943     {
944       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
945       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
946       {
947         _ignoreShapeIds.insert( ids[i] );
948         ignoreFaces.push_back( s );
949       }
950     }
951   }
952
953   // ignore internal faces
954   SMESH_MesherHelper helper( *_mesh );
955   TopExp_Explorer exp;
956   for ( unsigned i = 0; i < _sdVec.size(); ++i )
957   {
958     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
959     for ( ; exp.More(); exp.Next() )
960     {
961       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
962       if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
963       {     
964         _ignoreShapeIds.insert( faceInd );
965         ignoreFaces.push_back( exp.Current() );
966         if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
967           _sdVec[i]._reversedFaceIds.insert( faceInd );
968       }
969     }
970   }
971
972   // Find faces to shrink mesh on (solution 2 in issue 0020832);
973   TopTools_IndexedMapOfShape shapes;
974   for ( unsigned i = 0; i < _sdVec.size(); ++i )
975   {
976     shapes.Clear();
977     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
978     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
979     {
980       const TopoDS_Shape& edge = shapes(iE);
981       // find 2 faces sharing an edge
982       TopoDS_Shape FF[2];
983       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
984       while ( fIt->more())
985       {
986         const TopoDS_Shape* f = fIt->next();
987         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
988           FF[ int( !FF[0].IsNull()) ] = *f;
989       }
990       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
991       // check presence of layers on them
992       int ignore[2];
993       for ( int j = 0; j < 2; ++j )
994         ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
995       if ( ignore[0] == ignore[1] ) continue; // nothing interesting
996       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
997       // add edge to maps
998       TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
999       _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1000     }
1001   }
1002   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1003   // the algo of the SOLID sharing the FACE does not support it
1004   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1005   for ( unsigned i = 0; i < _sdVec.size(); ++i )
1006   {
1007     TopTools_MapOfShape noShrinkVertices;
1008     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1009     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1010     {
1011       const TopoDS_Shape& fWOL = e2f->second;
1012       TGeomID           edgeID = e2f->first;
1013       bool notShrinkFace = false;
1014       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1015       while ( soIt->more())
1016       {
1017         const TopoDS_Shape* solid = soIt->next();
1018         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1019         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1020         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1021         notShrinkFace = true;
1022         for ( unsigned j = 0; j < _sdVec.size(); ++j )
1023         {
1024           if ( _sdVec[j]._solid.IsSame( *solid ) )
1025             if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1026               notShrinkFace = false;
1027         }
1028       }
1029       if ( notShrinkFace )
1030       {
1031         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1032         for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1033           noShrinkVertices.Add( vExp.Current() );
1034       }
1035     }
1036     // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1037     // to the found not shrinked fWOL's
1038     e2f = _sdVec[i]._shrinkShape2Shape.begin();
1039     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1040     {
1041       TGeomID edgeID = e2f->first;
1042       TopoDS_Vertex VV[2];
1043       TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1044       if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1045         _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1046       else
1047         e2f++;
1048     }
1049   }
1050       
1051   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1052
1053   for ( unsigned i = 0; i < _sdVec.size(); ++i )
1054   {
1055     shapes.Clear();
1056     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1057     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1058     {
1059       const TopoDS_Shape& vertex = shapes(iV);
1060       // find faces WOL sharing the vertex
1061       vector< TopoDS_Shape > facesWOL;
1062       int totalNbFaces = 0;
1063       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1064       while ( fIt->more())
1065       {
1066         const TopoDS_Shape* f = fIt->next();
1067         const int         fID = getMeshDS()->ShapeToIndex( *f );
1068         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1069         {
1070           totalNbFaces++;
1071           if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1072             facesWOL.push_back( *f );
1073         }
1074       }
1075       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1076         continue; // no layers at this vertex or no WOL
1077       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1078       switch ( facesWOL.size() )
1079       {
1080       case 1:
1081         {
1082           _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] )); break;
1083         }
1084       case 2:
1085         {
1086           // find an edge shared by 2 faces
1087           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1088           while ( eIt->more())
1089           {
1090             const TopoDS_Shape* e = eIt->next();
1091             if ( helper.IsSubShape( *e, facesWOL[0]) &&
1092                  helper.IsSubShape( *e, facesWOL[1]))
1093             {
1094               _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1095             }
1096           }
1097           break;
1098         }
1099       default:
1100         return error("Not yet supported case", _sdVec[i]._index);
1101       }
1102     }
1103   }
1104
1105   return true;
1106 }
1107
1108 //================================================================================
1109 /*!
1110  * \brief Create the inner surface of the viscous layer and prepare data for infation
1111  */
1112 //================================================================================
1113
1114 bool _ViscousBuilder::makeLayer(_SolidData& data)
1115 {
1116   // get all sub-shapes to make layers on
1117   set<TGeomID> subIds, faceIds;
1118   subIds = data._noShrinkFaces;
1119   TopExp_Explorer exp( data._solid, TopAbs_FACE );
1120   for ( ; exp.More(); exp.Next() )
1121     if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1122     {
1123       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1124       faceIds.insert( fSubM->GetId() );
1125       SMESH_subMeshIteratorPtr subIt =
1126         fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1127       while ( subIt->more() )
1128         subIds.insert( subIt->next()->GetId() );
1129     }
1130
1131   // make a map to find new nodes on sub-shapes shared with other SOLID
1132   map< TGeomID, TNode2Edge* > s2neMap;
1133   map< TGeomID, TNode2Edge* >::iterator s2ne;
1134   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1135   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1136   {
1137     TGeomID shapeInd = s2s->first;
1138     for ( unsigned i = 0; i < _sdVec.size(); ++i )
1139     {
1140       if ( _sdVec[i]._index == data._index ) continue;
1141       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1142       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1143            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1144       {
1145         s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1146         break;
1147       }
1148     }
1149   }
1150
1151   // Create temporary faces and _LayerEdge's
1152
1153   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
1154
1155   data._stepSize = Precision::Infinite();
1156   data._stepSizeNodes[0] = 0;
1157
1158   SMESH_MesherHelper helper( *_mesh );
1159   helper.SetSubShape( data._solid );
1160   helper.SetElementsOnShape(true);
1161
1162   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1163   TNode2Edge::iterator n2e2;
1164
1165   // collect _LayerEdge's of shapes they are based on
1166   const int nbShapes = getMeshDS()->MaxShapeIndex();
1167   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1168
1169   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1170   {
1171     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1172     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1173
1174     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1175     SMESH_ProxyMesh::SubMesh* proxySub =
1176       data._proxyMesh->getFaceSubM( F, /*create=*/true);
1177
1178     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1179     while ( eIt->more() )
1180     {
1181       const SMDS_MeshElement* face = eIt->next();
1182       newNodes.resize( face->NbCornerNodes() );
1183       double faceMaxCosin = -1;
1184       for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1185       {
1186         const SMDS_MeshNode* n = face->GetNode(i);
1187         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1188         if ( !(*n2e).second )
1189         {
1190           // add a _LayerEdge
1191           _LayerEdge* edge = new _LayerEdge();
1192           n2e->second = edge;
1193           edge->_nodes.push_back( n );
1194           const int shapeID = n->getshapeId();
1195           edgesByGeom[ shapeID ].push_back( edge );
1196
1197           // set edge data or find already refined _LayerEdge and get data from it
1198           if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1199                ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1200                ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1201           {
1202             _LayerEdge* foundEdge = (*n2e2).second;
1203             edge->Copy( *foundEdge, helper );
1204             // location of the last node is modified but we can restore
1205             // it by node position on _sWOL stored by the node
1206             const_cast< SMDS_MeshNode* >
1207               ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1208           }
1209           else
1210           {
1211             edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1212             if ( !setEdgeData( *edge, subIds, helper, data ))
1213               return false;
1214           }
1215           dumpMove(edge->_nodes.back());
1216           if ( edge->_cosin > 0.01 )
1217           {
1218             if ( edge->_cosin > faceMaxCosin )
1219               faceMaxCosin = edge->_cosin;
1220           }
1221         }
1222         newNodes[ i ] = n2e->second->_nodes.back();
1223       }
1224       // create a temporary face
1225       const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1226       proxySub->AddElement( newFace );
1227
1228       // compute inflation step size by min size of element on a convex surface
1229       if ( faceMaxCosin > 0.1 )
1230         limitStepSize( data, face, faceMaxCosin );
1231     } // loop on 2D elements on a FACE
1232   } // loop on FACEs of a SOLID
1233
1234   data._epsilon = 1e-7;
1235   if ( data._stepSize < 1. )
1236     data._epsilon *= data._stepSize;
1237
1238   // Put _LayerEdge's into a vector
1239
1240   if ( !sortEdges( data, edgesByGeom ))
1241     return false;
1242
1243   // Set target nodes into _Simplex and _2NearEdges
1244   TNode2Edge::iterator n2e;
1245   for ( unsigned i = 0; i < data._edges.size(); ++i )
1246   {
1247     if ( data._edges[i]->IsOnEdge())
1248       for ( int j = 0; j < 2; ++j )
1249       {
1250         if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1251           break; // _LayerEdge is shared by two _SolidData's
1252         const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1253         if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1254           return error("_LayerEdge not found by src node", data._index);
1255         n = (*n2e).second->_nodes.back();
1256         data._edges[i]->_2neibors->_edges[j] = n2e->second;
1257       }
1258     else
1259       for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1260       {
1261         _Simplex& s = data._edges[i]->_simplices[j];
1262         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1263         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1264       }
1265   }
1266
1267   dumpFunctionEnd();
1268   return true;
1269 }
1270
1271 //================================================================================
1272 /*!
1273  * \brief Compute inflation step size by min size of element on a convex surface
1274  */
1275 //================================================================================
1276
1277 void _ViscousBuilder::limitStepSize( _SolidData&             data,
1278                                      const SMDS_MeshElement* face,
1279                                      const double            cosin)
1280 {
1281   int iN = 0;
1282   double minSize = 10 * data._stepSize;
1283   const int nbNodes = face->NbCornerNodes();
1284   for ( int i = 0; i < nbNodes; ++i )
1285   {
1286     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1287     const SMDS_MeshNode* curN = face->GetNode( i );
1288     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1289          curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1290     {
1291       double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1292       if ( dist < minSize )
1293         minSize = dist, iN = i;
1294     }
1295   }
1296   double newStep = 0.8 * minSize / cosin;
1297   if ( newStep < data._stepSize )
1298   {
1299     data._stepSize = newStep;
1300     data._stepSizeCoeff = 0.8 / cosin;
1301     data._stepSizeNodes[0] = face->GetNode( iN );
1302     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1303   }
1304 }
1305
1306 //================================================================================
1307 /*!
1308  * \brief Compute inflation step size by min size of element on a convex surface
1309  */
1310 //================================================================================
1311
1312 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1313 {
1314   if ( minSize < data._stepSize )
1315   {
1316     data._stepSize = minSize;
1317     if ( data._stepSizeNodes[0] )
1318     {
1319       double dist =
1320         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1321       data._stepSizeCoeff = data._stepSize / dist;
1322     }
1323   }
1324 }
1325
1326 //================================================================================
1327 /*!
1328  * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1329  */
1330 //================================================================================
1331
1332 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
1333                                  vector< vector<_LayerEdge*> >& edgesByGeom)
1334 {
1335   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1336   // boundry inclined at a sharp angle to the shape
1337
1338   list< TGeomID > shapesToSmooth;
1339   
1340   SMESH_MesherHelper helper( *_mesh );
1341   bool ok;
1342
1343   for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1344   {
1345     vector<_LayerEdge*>& eS = edgesByGeom[iS];
1346     if ( eS.empty() ) continue;
1347     TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1348     bool needSmooth = false;
1349     switch ( S.ShapeType() )
1350     {
1351     case TopAbs_EDGE: {
1352
1353       bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1354       for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1355       {
1356         TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1357         vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1358         if ( eV.empty() ) continue;
1359         double cosin = eV[0]->_cosin;
1360         bool badCosin =
1361           ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1362         if ( badCosin )
1363         {
1364           gp_Vec dir1, dir2;
1365           if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1366             dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1367           else
1368             dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1369                                eV[0]->_nodes[0], helper, ok);
1370           dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1371           double angle = dir1.Angle( dir2 );
1372           cosin = cos( angle );
1373         }
1374         needSmooth = ( cosin > 0.1 );
1375       }
1376       break;
1377     }
1378     case TopAbs_FACE: {
1379
1380       for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1381       {
1382         TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1383         vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1384         if ( eE.empty() ) continue;
1385         if ( eE[0]->_sWOL.IsNull() )
1386         {
1387           for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1388             needSmooth = ( eE[i]->_cosin > 0.1 );
1389         }
1390         else
1391         {
1392           const TopoDS_Face& F1 = TopoDS::Face( S );
1393           const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1394           const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
1395           for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1396           {
1397             gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1398             gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1399             double angle = dir1.Angle( dir2 );
1400             double cosin = cos( angle );
1401             needSmooth = ( cosin > 0.1 );
1402           }
1403         }
1404       }
1405       break;
1406     }
1407     case TopAbs_VERTEX:
1408       continue;
1409     default:;
1410     }
1411     if ( needSmooth )
1412     {
1413       if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1414       else                                shapesToSmooth.push_back ( iS );
1415     }
1416
1417   } // loop on edgesByGeom
1418
1419   data._edges.reserve( data._n2eMap.size() );
1420   data._endEdgeToSmooth.clear();
1421
1422   // first we put _LayerEdge's on shapes to smooth
1423   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1424   for ( ; gIt != shapesToSmooth.end(); ++gIt )
1425   {
1426     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1427     if ( eVec.empty() ) continue;
1428     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1429     data._endEdgeToSmooth.push_back( data._edges.size() );
1430     eVec.clear();
1431   }
1432
1433   // then the rest _LayerEdge's
1434   for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1435   {
1436     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1437     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1438     eVec.clear();
1439   }
1440
1441   return ok;
1442 }
1443
1444 //================================================================================
1445 /*!
1446  * \brief Set data of _LayerEdge needed for smoothing
1447  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1448  */
1449 //================================================================================
1450
1451 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
1452                                   const set<TGeomID>& subIds,
1453                                   SMESH_MesherHelper& helper,
1454                                   _SolidData&         data)
1455 {
1456   SMESH_MeshEditor editor(_mesh);
1457
1458   const SMDS_MeshNode* node = edge._nodes[0]; // source node
1459   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1460
1461   edge._len = 0;
1462   edge._2neibors = 0;
1463   edge._curvature = 0;
1464
1465   // --------------------------
1466   // Compute _normal and _cosin
1467   // --------------------------
1468
1469   edge._cosin = 0;
1470   edge._normal.SetCoord(0,0,0);
1471
1472   int totalNbFaces = 0;
1473   gp_Pnt p;
1474   gp_Vec du, dv, geomNorm;
1475   bool normOK = true;
1476
1477   TGeomID shapeInd = node->getshapeId();
1478   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1479   bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1480   TopoDS_Shape vertEdge;
1481
1482   if ( onShrinkShape ) // one of faces the node is on has no layers
1483   {
1484     vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1485     if ( s2s->second.ShapeType() == TopAbs_EDGE )
1486     {
1487       // inflate from VERTEX along EDGE
1488       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1489     }
1490     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1491     {
1492       // inflate from VERTEX along FACE
1493       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1494                                  node, helper, normOK, &edge._cosin);
1495     }
1496     else
1497     {
1498       // inflate from EDGE along FACE
1499       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1500                                  node, helper, normOK);
1501     }
1502   }
1503   else // layers are on all faces of SOLID the node is on
1504   {
1505     // find indices of geom faces the node lies on
1506     set<TGeomID> faceIds;
1507     if  ( posType == SMDS_TOP_FACE )
1508     {
1509       faceIds.insert( node->getshapeId() );
1510     }
1511     else
1512     {
1513       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1514       while ( fIt->more() )
1515         faceIds.insert( editor.FindShape(fIt->next()));
1516     }
1517
1518     set<TGeomID>::iterator id = faceIds.begin();
1519     TopoDS_Face F;
1520     for ( ; id != faceIds.end(); ++id )
1521     {
1522       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1523       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1524         continue;
1525       totalNbFaces++;
1526       //nbLayerFaces += subIds.count( *id );
1527       F = TopoDS::Face( s );
1528
1529       gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1530       Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1531       surface->D1( uv.X(),uv.Y(), p, du,dv );
1532       geomNorm = du ^ dv;
1533       double size2 = geomNorm.SquareMagnitude();
1534       if ( size2 > numeric_limits<double>::min() )
1535         geomNorm /= sqrt( size2 );
1536       else
1537         normOK = false;
1538       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1539         geomNorm.Reverse();
1540       edge._normal += geomNorm.XYZ();
1541     }
1542     if ( totalNbFaces == 0 )
1543       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1544
1545     edge._normal /= totalNbFaces;
1546
1547     switch ( posType )
1548     {
1549     case SMDS_TOP_FACE:
1550       edge._cosin = 0; break;
1551
1552     case SMDS_TOP_EDGE: {
1553       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1554       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1555       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1556       edge._cosin = cos( angle );
1557       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1558       break;
1559     }
1560     case SMDS_TOP_VERTEX: {
1561       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1562       gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1563       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1564       edge._cosin = cos( angle );
1565       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1566       break;
1567     }
1568     default:
1569       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1570     }
1571   }
1572
1573   double normSize = edge._normal.SquareModulus();
1574   if ( normSize < numeric_limits<double>::min() )
1575     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1576
1577   edge._normal /= sqrt( normSize );
1578
1579   // TODO: if ( !normOK ) then get normal by mesh faces
1580
1581   // Set the rest data
1582   // --------------------
1583   if ( onShrinkShape )
1584   {
1585     edge._sWOL = (*s2s).second;
1586
1587     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1588     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1589       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1590
1591     // set initial position which is parameters on _sWOL in this case
1592     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1593     {
1594       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1595       edge._pos.push_back( gp_XYZ( u, 0, 0));
1596       getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1597     }
1598     else // TopAbs_FACE
1599     {
1600       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1601       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1602       getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1603     }
1604   }
1605   else
1606   {
1607     edge._pos.push_back( SMESH_TNodeXYZ( node ));
1608
1609     if ( posType == SMDS_TOP_FACE )
1610     {
1611       getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1612       double avgNormProj = 0, avgLen = 0;
1613       for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1614       {
1615         gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1616         avgNormProj += edge._normal * vec;
1617         avgLen += vec.Modulus();
1618       }
1619       avgNormProj /= edge._simplices.size();
1620       avgLen /= edge._simplices.size();
1621       edge._curvature = _Curvature::New( avgNormProj, avgLen );
1622     }
1623   }
1624
1625   // Set neighbour nodes for a _LayerEdge based on EDGE
1626
1627   if ( posType == SMDS_TOP_EDGE /*||
1628        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1629   {
1630     edge._2neibors = new _2NearEdges;
1631     // target node instead of source ones will be set later
1632     if ( ! findNeiborsOnEdge( &edge,
1633                               edge._2neibors->_nodes[0],
1634                               edge._2neibors->_nodes[1],
1635                               data))
1636       return false;
1637     edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1638                              edge._2neibors->_nodes[1],
1639                              helper);
1640   }
1641
1642   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1643
1644   return true;
1645 }
1646
1647 //================================================================================
1648 /*!
1649  * \brief Find 2 neigbor nodes of a node on EDGE
1650  */
1651 //================================================================================
1652
1653 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
1654                                         const SMDS_MeshNode*& n1,
1655                                         const SMDS_MeshNode*& n2,
1656                                         _SolidData&           data)
1657 {
1658   const SMDS_MeshNode* node = edge->_nodes[0];
1659   const int shapeInd = node->getshapeId();
1660   SMESHDS_SubMesh* edgeSM = 0;
1661   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1662   {
1663     
1664     edgeSM = getMeshDS()->MeshElements( shapeInd );
1665     if ( !edgeSM || edgeSM->NbElements() == 0 )
1666       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1667   }
1668   int iN = 0;
1669   n2 = 0;
1670   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1671   while ( eIt->more() && !n2 )
1672   {
1673     const SMDS_MeshElement* e = eIt->next();
1674     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
1675     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1676     if ( edgeSM )
1677     {
1678       if (!edgeSM->Contains(e)) continue;
1679     }
1680     else
1681     {
1682       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1683       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1684     }
1685     ( iN++ ? n2 : n1 ) = nNeibor;
1686   }
1687   if ( !n2 )
1688     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1689   return true;
1690 }
1691
1692 //================================================================================
1693 /*!
1694  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1695  */
1696 //================================================================================
1697
1698 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1699                                      const SMDS_MeshNode* n2,
1700                                      SMESH_MesherHelper&  helper)
1701 {
1702   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1703     return;
1704
1705   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1706   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1707   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1708
1709   // Set _curvature
1710
1711   double sumLen = vec1.Modulus() + vec2.Modulus();
1712   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1713   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1714   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1715   double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1716   if ( _curvature ) delete _curvature;
1717   _curvature = _Curvature::New( avgNormProj, avgLen );
1718 #ifdef __myDEBUG
1719 //     if ( _curvature )
1720 //       cout << _nodes[0]->GetID()
1721 //            << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1722 //            << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1723 //            << _curvature->lenDelta(0) << endl;
1724 #endif
1725
1726   // Set _plnNorm
1727
1728   if ( _sWOL.IsNull() )
1729   {
1730     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1731     gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1732     gp_XYZ plnNorm = dirE ^ _normal;
1733     double proj0 = plnNorm * vec1;
1734     double proj1 = plnNorm * vec2;
1735     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1736     {
1737       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1738       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1739     }
1740   }
1741 }
1742
1743 //================================================================================
1744 /*!
1745  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1746  * this and other _LayerEdge's are inflated along a FACE or an EDGE
1747  */
1748 //================================================================================
1749
1750 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1751 {
1752   _nodes     = other._nodes;
1753   _normal    = other._normal;
1754   _len       = 0;
1755   _lenFactor = other._lenFactor;
1756   _cosin     = other._cosin;
1757   _sWOL      = other._sWOL;
1758   _2neibors  = other._2neibors;
1759   _curvature = 0; std::swap( _curvature, other._curvature );
1760   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
1761
1762   if ( _sWOL.ShapeType() == TopAbs_EDGE )
1763   {
1764     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1765     _pos.push_back( gp_XYZ( u, 0, 0));
1766   }
1767   else // TopAbs_FACE
1768   {
1769     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1770     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1771   }
1772 }
1773
1774 //================================================================================
1775 /*!
1776  * \brief Set _cosin and _lenFactor
1777  */
1778 //================================================================================
1779
1780 void _LayerEdge::SetCosin( double cosin )
1781 {
1782   _cosin = cosin;
1783   _lenFactor = ( _cosin > 0.1 ) ?  1./sqrt(1-_cosin*_cosin) : 1.0;
1784 }
1785
1786 //================================================================================
1787 /*!
1788  * \brief Fills a vector<_Simplex > 
1789  */
1790 //================================================================================
1791
1792 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1793                                     vector<_Simplex>&    simplices,
1794                                     const set<TGeomID>&  ingnoreShapes,
1795                                     const _SolidData*    dataToCheckOri)
1796 {
1797   SMESH_MeshEditor editor( _mesh );
1798   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1799   while ( fIt->more() )
1800   {
1801     const SMDS_MeshElement* f = fIt->next();
1802     const TGeomID shapeInd = editor.FindShape( f );
1803     if ( ingnoreShapes.count( shapeInd )) continue;
1804     const int nbNodes = f->NbCornerNodes();
1805     int srcInd = f->GetNodeIndex( node );
1806     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1807     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1808     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1809       std::swap( nPrev, nNext );
1810     simplices.push_back( _Simplex( nPrev, nNext ));
1811   }
1812   simplices.resize( simplices.size() );
1813 }
1814
1815 //================================================================================
1816 /*!
1817  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1818  */
1819 //================================================================================
1820
1821 void _ViscousBuilder::makeGroupOfLE()
1822 {
1823 #ifdef _DEBUG_
1824   for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1825   {
1826     if ( _sdVec[i]._edges.empty() ) continue;
1827 //     string name = SMESH_Comment("_LayerEdge's_") << i;
1828 //     int id;
1829 //     SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1830 //     SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1831 //     SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1832
1833     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1834     for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1835     {
1836       _LayerEdge* le = _sdVec[i]._edges[j];
1837       for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1838         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1839                 << ", " << le->_nodes[iN]->GetID() <<"])");
1840       //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1841     }
1842     dumpFunctionEnd();
1843
1844     dumpFunction( SMESH_Comment("makeNormals") << i );
1845     for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1846     {
1847       _LayerEdge& edge = *_sdVec[i]._edges[j];
1848       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1849       nXYZ += edge._normal * _sdVec[i]._stepSize;
1850       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
1851               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
1852     }
1853     dumpFunctionEnd();
1854
1855 //     name = SMESH_Comment("tmp_faces ") << i;
1856 //     g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
1857 //     gDS = (SMESHDS_Group*)g->GetGroupDS();
1858 //     SMESH_MeshEditor editor( _mesh );
1859     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
1860     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
1861     for ( ; fExp.More(); fExp.Next() )
1862     {
1863       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
1864       {
1865         SMDS_ElemIteratorPtr fIt = sm->GetElements();
1866         while ( fIt->more())
1867         {
1868           const SMDS_MeshElement* e = fIt->next();
1869           SMESH_Comment cmd("mesh.AddFace([");
1870           for ( int j=0; j < e->NbCornerNodes(); ++j )
1871             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
1872           dumpCmd( cmd );
1873           //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
1874           //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
1875         }
1876       }
1877     }
1878     dumpFunctionEnd();
1879   }
1880 #endif
1881 }
1882
1883 //================================================================================
1884 /*!
1885  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1886  */
1887 //================================================================================
1888
1889 bool _ViscousBuilder::inflate(_SolidData& data)
1890 {
1891   SMESH_MesherHelper helper( *_mesh );
1892
1893   // Limit inflation step size by geometry size found by itersecting
1894   // normals of _LayerEdge's with mesh faces
1895   double geomSize = Precision::Infinite(), intersecDist;
1896   SMESH_MeshEditor editor( _mesh );
1897   auto_ptr<SMESH_ElementSearcher> searcher
1898     ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
1899   for ( unsigned i = 0; i < data._edges.size(); ++i )
1900   {
1901     if ( data._edges[i]->IsOnEdge() ) continue;
1902     data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
1903     if ( geomSize > intersecDist )
1904       geomSize = intersecDist;
1905   }
1906   if ( data._stepSize > 0.3 * geomSize )
1907     limitStepSize( data, 0.3 * geomSize );
1908
1909   const double tgtThick = data._hyp->GetTotalThickness();
1910   if ( data._stepSize > tgtThick )
1911     limitStepSize( data, tgtThick );
1912
1913   if ( data._stepSize < 1. )
1914     data._epsilon = data._stepSize * 1e-7;
1915
1916 #ifdef __myDEBUG
1917   cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
1918 #endif
1919
1920   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
1921   int nbSteps = 0, nbRepeats = 0;
1922   while ( 1.01 * avgThick < tgtThick )
1923   {
1924     // new target length
1925     curThick += data._stepSize;
1926     if ( curThick > tgtThick )
1927     {
1928       curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
1929       nbRepeats++;
1930     }
1931
1932     // Elongate _LayerEdge's
1933     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
1934     for ( unsigned i = 0; i < data._edges.size(); ++i )
1935     {
1936       data._edges[i]->SetNewLength( curThick, helper );
1937     }
1938     dumpFunctionEnd();
1939
1940     if ( !nbSteps )
1941       if ( !updateNormals( data, helper ) )
1942         return false;
1943
1944     // Improve and check quality
1945     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
1946     {
1947       if ( nbSteps > 0 )
1948       {
1949         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
1950         for ( unsigned i = 0; i < data._edges.size(); ++i )
1951         {
1952           data._edges[i]->InvalidateStep( nbSteps+1 );
1953         }
1954         dumpFunctionEnd();
1955       }
1956       break; // no more inflating possible
1957     }
1958     nbSteps++;
1959
1960     // Evaluate achieved thickness
1961     avgThick = 0;
1962     for ( unsigned i = 0; i < data._edges.size(); ++i )
1963       avgThick += data._edges[i]->_len;
1964     avgThick /= data._edges.size();
1965 #ifdef __myDEBUG
1966     cout << "-- Thickness " << avgThick << " reached" << endl;
1967 #endif
1968
1969     if ( distToIntersection < avgThick*1.5 )
1970     {
1971 #ifdef __myDEBUG
1972       cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
1973            << avgThick << " ) * 1.5" << endl;
1974 #endif
1975       break;
1976     }
1977     // new step size
1978     limitStepSize( data, 0.25 * distToIntersection );
1979     if ( data._stepSizeNodes[0] )
1980       data._stepSize = data._stepSizeCoeff *
1981         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1982   }
1983
1984   if (nbSteps == 0 )
1985     return error("failed at the very first inflation step", data._index);
1986
1987   return true;
1988 }
1989
1990 //================================================================================
1991 /*!
1992  * \brief Improve quality of layer inner surface and check intersection
1993  */
1994 //================================================================================
1995
1996 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
1997                                      int         nbSteps,
1998                                      double &    distToIntersection)
1999 {
2000   if ( data._endEdgeToSmooth.empty() )
2001     return true; // no shapes needing smoothing
2002
2003   bool moved, improved;
2004
2005   SMESH_MesherHelper helper(*_mesh);
2006   Handle(Geom_Surface) surface;
2007   TopoDS_Face F;
2008
2009   int iBeg, iEnd = 0;
2010   for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2011   {
2012     iBeg = iEnd;
2013     iEnd = data._endEdgeToSmooth[ iS ];
2014
2015     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2016          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2017     {
2018       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2019         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2020         helper.SetSubShape( F );
2021         surface = BRep_Tool::Surface( F );
2022       }
2023     }
2024     else
2025     {
2026       F.Nullify(); surface.Nullify();
2027     }
2028     TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2029
2030     if ( data._edges[ iBeg ]->IsOnEdge() )
2031     {
2032       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2033       // smooth on EDGE's
2034       int step = 0;
2035       do {
2036         moved = false;
2037         for ( int i = iBeg; i < iEnd; ++i )
2038         {
2039           moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2040         }
2041         dumpCmd( SMESH_Comment("# end step ")<<step);
2042       }
2043       while ( moved && step++ < 5 );
2044
2045       dumpFunctionEnd();
2046     }
2047     else
2048     {
2049       // smooth on FACE's
2050       int step = 0, badNb = 0; moved = true;
2051       while (( ++step <= 5 && moved ) || improved )
2052       {
2053         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2054                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2055         int oldBadNb = badNb;
2056         badNb = 0;
2057         moved = false;
2058         for ( int i = iBeg; i < iEnd; ++i )
2059           moved |= data._edges[i]->Smooth(badNb);
2060         improved = ( badNb < oldBadNb );
2061
2062         dumpFunctionEnd();
2063       }
2064       if ( badNb > 0 )
2065       {
2066 #ifdef __myDEBUG
2067         for ( int i = iBeg; i < iEnd; ++i )
2068         {
2069           _LayerEdge* edge = data._edges[i];
2070           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2071           for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2072             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2073             {
2074               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2075                    << " "<< edge->_simplices[j]._nPrev->GetID()
2076                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2077               return false;
2078             }
2079         }
2080 #endif
2081         return false;
2082       }
2083     }
2084   } // loop on shapes to smooth
2085
2086   // Check if the last segments of _LayerEdge intersects 2D elements;
2087   // checked elements are either temporary faces or faces on surfaces w/o the layers
2088
2089   SMESH_MeshEditor editor( _mesh );
2090   auto_ptr<SMESH_ElementSearcher> searcher
2091     ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2092
2093   distToIntersection = Precision::Infinite();
2094   double dist;
2095   const SMDS_MeshElement* intFace = 0;
2096 #ifdef __myDEBUG
2097   const SMDS_MeshElement* *closestFace = 0;
2098   int iLE = 0;
2099 #endif
2100   for ( unsigned i = 0; i < data._edges.size(); ++i )
2101   {
2102     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2103       return false;
2104     if ( distToIntersection > dist )
2105     {
2106       distToIntersection = dist;
2107 #ifdef __myDEBUG
2108       iLE = i;
2109       closestFace = intFace;
2110 #endif
2111     }
2112   }
2113 #ifdef __myDEBUG
2114   if ( closestFace )
2115   {
2116     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2117     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2118          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2119          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2120          << ") distance = " << distToIntersection<< endl;
2121   }
2122 #endif
2123
2124   return true;
2125 }
2126
2127 //================================================================================
2128 /*!
2129  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2130  * _LayerEdge's on neighbor EDGE's
2131  */
2132 //================================================================================
2133
2134 bool _ViscousBuilder::updateNormals( _SolidData&         data,
2135                                      SMESH_MesherHelper& helper )
2136 {
2137   // make temporary quadrangles got by extrusion of
2138   // mesh edges along _LayerEdge._normal's
2139
2140   vector< const SMDS_MeshElement* > tmpFaces;
2141   {
2142     set< SMESH_TLink > extrudedLinks; // contains target nodes
2143     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2144
2145     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2146     for ( unsigned i = 0; i < data._edges.size(); ++i )
2147     {
2148       _LayerEdge* edge = data._edges[i];
2149       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2150       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2151       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2152       {
2153         const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2154         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2155           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2156         if ( !link_isnew.second )
2157         {
2158           extrudedLinks.erase( link_isnew.first );
2159           continue; // already extruded and will no more encounter
2160         }
2161         // look for a _LayerEdge containg tgt2
2162 //         _LayerEdge* neiborEdge = 0;
2163 //         unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2164 //         while ( !neiborEdge && ++di <= data._edges.size() )
2165 //         {
2166 //           if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2167 //             neiborEdge = data._edges[i+di];
2168 //           else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2169 //             neiborEdge = data._edges[i-di];
2170 //         }
2171 //         if ( !neiborEdge )
2172 //           return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2173         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2174
2175         TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2176         tmpFaces.push_back( f );
2177
2178         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2179                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2180                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2181       }
2182     }
2183     dumpFunctionEnd();
2184   }
2185   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2186   // Perform two loops on _LayerEdge on EDGE's:
2187   // 1) to find and fix intersection
2188   // 2) to check that no new intersection appears as result of 1)
2189
2190   SMESH_MeshEditor editor( _mesh );
2191   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2192                                                             tmpFaces.end()));
2193   auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2194
2195   // 1) Find intersections
2196   double dist;
2197   const SMDS_MeshElement* face;
2198   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2199   TLEdge2LEdgeSet edge2CloseEdge;
2200
2201   const double eps = data._epsilon * data._epsilon;
2202   for ( unsigned i = 0; i < data._edges.size(); ++i )
2203   {
2204     _LayerEdge* edge = data._edges[i];
2205     if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2206     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2207     {
2208       const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2209       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2210       ee.insert( f->_le1 );
2211       ee.insert( f->_le2 );
2212       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
2213         edge2CloseEdge[ f->_le1 ].insert( edge );
2214       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
2215         edge2CloseEdge[ f->_le2 ].insert( edge );
2216     }
2217   }
2218
2219   // Set _LayerEdge._normal
2220
2221   if ( !edge2CloseEdge.empty() )
2222   {
2223     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2224
2225     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2226     for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2227     {
2228       _LayerEdge* edge1       = e2ee->first;
2229       _LayerEdge* edge2       = 0;
2230       set< _LayerEdge*, _LayerEdgeCmp >& ee  = e2ee->second;
2231
2232       // find EDGEs the edges reside
2233       TopoDS_Edge E1, E2;
2234       TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2235       if ( S.ShapeType() != TopAbs_EDGE )
2236         continue; // TODO: find EDGE by VERTEX
2237       E1 = TopoDS::Edge( S );
2238       set< _LayerEdge* >::iterator eIt = ee.begin();
2239       while ( E2.IsNull() && eIt != ee.end())
2240       {
2241         _LayerEdge* e2 = *eIt++;
2242         TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2243         if ( S.ShapeType() == TopAbs_EDGE )
2244           E2 = TopoDS::Edge( S ), edge2 = e2;
2245       }
2246       if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2247
2248       // find 3 FACEs sharing 2 EDGEs
2249
2250       TopoDS_Face FF1[2], FF2[2];
2251       PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2252       while ( fIt->more() && FF1[1].IsNull())
2253       {
2254         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2255         if ( helper.IsSubShape( *F, data._solid))
2256           FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2257       }
2258       fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2259       while ( fIt->more() && FF2[1].IsNull())
2260       {
2261         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2262         if ( helper.IsSubShape( *F, data._solid))
2263           FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2264       }
2265       // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2266       if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2267         std::swap( FF1[0], FF1[1] );
2268       if ( FF2[0].IsSame( FF1[0]) )
2269         std::swap( FF2[0], FF2[1] );
2270       if ( FF1[0].IsNull() || FF2[0].IsNull() )
2271         continue;
2272
2273 //       // get a new normal for edge1
2274       bool ok;
2275       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2276       if ( edge1->_cosin < 0 )
2277         dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2278       if ( edge2->_cosin < 0 )
2279         dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2280       //      gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2281 //       gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2282 //       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2283 //       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2284 //       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2285 //       newNorm.Normalize();
2286
2287       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2288       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2289       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2290       newNorm.Normalize();
2291
2292       edge1->_normal = newNorm.XYZ();
2293
2294       // update data of edge1 depending on _normal
2295       const SMDS_MeshNode *n1, *n2;
2296       n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2297       n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2298       //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2299       //continue;
2300       edge1->SetDataByNeighbors( n1, n2, helper );
2301       gp_Vec dirInFace;
2302       if ( edge1->_cosin < 0 )
2303         dirInFace = dir1;
2304       else
2305         getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2306       double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2307       edge1->SetCosin( cos( angle ));
2308
2309       // limit data._stepSize
2310       if ( edge1->_cosin > 0.1 )
2311       {
2312         SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2313         while ( fIt->more() )
2314           limitStepSize( data, fIt->next(), edge1->_cosin );
2315       }
2316       // set new XYZ of target node
2317       edge1->InvalidateStep( 1 );
2318       edge1->_len = 0;
2319       edge1->SetNewLength( data._stepSize, helper );
2320     }
2321
2322     // Update normals and other dependent data of not intersecting _LayerEdge's
2323     // neighboring the intersecting ones
2324
2325     for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2326     {
2327       _LayerEdge* edge1 = e2ee->first;
2328       if ( !edge1->_2neibors )
2329         continue;
2330       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2331       {
2332         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2333         if ( edge2CloseEdge.count ( neighbor ))
2334           continue; // j-th neighbor is also intersected
2335         _LayerEdge* prevEdge = edge1;
2336         const int nbSteps = 6;
2337         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2338         {
2339           if ( !neighbor->_2neibors )
2340             break; // neighbor is on VERTEX
2341           int iNext = 0;
2342           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2343           if ( nextEdge == prevEdge )
2344             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2345 //           const double&  wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2346 //           const double&  wgtNext = neighbor->_2neibors->_wgt[iNext];
2347           double r = double(step-1)/nbSteps;
2348           if ( !nextEdge->_2neibors )
2349             r = 0.5;
2350
2351           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2352           newNorm.Normalize();
2353
2354           neighbor->_normal = newNorm;
2355           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2356           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2357
2358           neighbor->InvalidateStep( 1 );
2359           neighbor->_len = 0;
2360           neighbor->SetNewLength( data._stepSize, helper );
2361
2362           // goto the next neighbor
2363           prevEdge = neighbor;
2364           neighbor = nextEdge;
2365         }
2366       }
2367     }
2368     dumpFunctionEnd();
2369   }
2370   // 2) Check absence of intersections
2371   // TODO?
2372
2373   for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2374     delete tmpFaces[i];
2375
2376   return true;
2377 }
2378
2379 //================================================================================
2380 /*!
2381  * \brief Looks for intersection of it's last segment with faces
2382  *  \param distance - returns shortest distance from the last node to intersection
2383  */
2384 //================================================================================
2385
2386 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
2387                                    double &                 distance,
2388                                    const double&            epsilon,
2389                                    const SMDS_MeshElement** face)
2390 {
2391   vector< const SMDS_MeshElement* > suspectFaces;
2392   double segLen;
2393   gp_Ax1 lastSegment = LastSegment(segLen);
2394   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2395
2396   bool segmentIntersected = false;
2397   distance = Precision::Infinite();
2398   int iFace = -1; // intersected face
2399   for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2400   {
2401     const SMDS_MeshElement* face = suspectFaces[j];
2402     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2403          face->GetNodeIndex( _nodes[0]     ) >= 0 )
2404       continue; // face sharing _LayerEdge node
2405     const int nbNodes = face->NbCornerNodes();
2406     bool intFound = false;
2407     double dist;
2408     SMDS_MeshElement::iterator nIt = face->begin_nodes();
2409     if ( nbNodes == 3 )
2410     {
2411       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2412     }
2413     else
2414     {
2415       const SMDS_MeshNode* tria[3];
2416       tria[0] = *nIt++;
2417       tria[1] = *nIt++;;
2418       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2419       {
2420         tria[2] = *nIt++;
2421         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2422         tria[1] = tria[2];
2423       }
2424     }
2425     if ( intFound )
2426     {
2427       if ( dist < segLen*(1.01))
2428         segmentIntersected = true;
2429       if ( distance > dist )
2430         distance = dist, iFace = j;
2431     }
2432   }
2433   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2434 //   if ( distance && iFace > -1 )
2435 //   {
2436 //     // distance is used to limit size of inflation step which depends on
2437 //     // whether the intersected face bears viscous layers or not
2438 //     bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2439 //     if ( faceHasVL )
2440 //       *distance /= 2;
2441 //   }
2442   if ( segmentIntersected )
2443   {
2444 #ifdef __myDEBUG
2445     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2446     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2447     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2448          << ", intersection with face ("
2449          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2450          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2451          << ") distance = " << distance - segLen<< endl;
2452 #endif
2453   }
2454
2455   distance -= segLen;
2456
2457   return segmentIntersected;
2458 }
2459
2460 //================================================================================
2461 /*!
2462  * \brief Returns size and direction of the last segment
2463  */
2464 //================================================================================
2465
2466 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2467 {
2468   // find two non-coincident positions
2469   gp_XYZ orig = _pos.back();
2470   gp_XYZ dir;
2471   int iPrev = _pos.size() - 2;
2472   while ( iPrev >= 0 )
2473   {
2474     dir = orig - _pos[iPrev];
2475     if ( dir.SquareModulus() > 1e-100 )
2476       break;
2477     else
2478       iPrev--;
2479   }
2480
2481   // make gp_Ax1
2482   gp_Ax1 segDir;
2483   if ( iPrev < 0 )
2484   {
2485     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2486     segDir.SetDirection( _normal );
2487     segLen = 0;
2488   }
2489   else
2490   {
2491     gp_Pnt pPrev = _pos[ iPrev ];
2492     if ( !_sWOL.IsNull() )
2493     {
2494       TopLoc_Location loc;
2495       if ( _sWOL.ShapeType() == TopAbs_EDGE )
2496       {
2497         double f,l;
2498         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2499         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2500       }
2501       else
2502       {
2503         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2504         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2505       }
2506       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2507     }
2508     segDir.SetLocation( pPrev );
2509     segDir.SetDirection( dir );
2510     segLen = dir.Modulus();
2511   }
2512
2513   return segDir;
2514 }
2515
2516 //================================================================================
2517 /*!
2518  * \brief Test intersection of the last segment with a given triangle
2519  *   using Moller-Trumbore algorithm
2520  * Intersection is detected if distance to intersection is less than _LayerEdge._len
2521  */
2522 //================================================================================
2523
2524 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
2525                                const SMDS_MeshNode* n0,
2526                                const SMDS_MeshNode* n1,
2527                                const SMDS_MeshNode* n2,
2528                                double&              t,
2529                                const double&        EPSILON) const
2530 {
2531   //const double EPSILON = 1e-6;
2532
2533   gp_XYZ orig = lastSegment.Location().XYZ();
2534   gp_XYZ dir  = lastSegment.Direction().XYZ();
2535
2536   SMESH_TNodeXYZ vert0( n0 );
2537   SMESH_TNodeXYZ vert1( n1 );
2538   SMESH_TNodeXYZ vert2( n2 );
2539
2540   /* calculate distance from vert0 to ray origin */
2541   gp_XYZ tvec = orig - vert0;
2542
2543   if ( tvec * dir > EPSILON )
2544     // intersected face is at back side of the temporary face this _LayerEdge belongs to
2545     return false;
2546
2547   gp_XYZ edge1 = vert1 - vert0;
2548   gp_XYZ edge2 = vert2 - vert0;
2549
2550   /* begin calculating determinant - also used to calculate U parameter */
2551   gp_XYZ pvec = dir ^ edge2;
2552
2553   /* if determinant is near zero, ray lies in plane of triangle */
2554   double det = edge1 * pvec;
2555
2556   if (det > -EPSILON && det < EPSILON)
2557     return 0;
2558   double inv_det = 1.0 / det;
2559
2560   /* calculate U parameter and test bounds */
2561   double u = ( tvec * pvec ) * inv_det;
2562   if (u < 0.0 || u > 1.0)
2563     return 0;
2564
2565   /* prepare to test V parameter */
2566   gp_XYZ qvec = tvec ^ edge1;
2567
2568   /* calculate V parameter and test bounds */
2569   double v = (dir * qvec) * inv_det;
2570   if ( v < 0.0 || u + v > 1.0 )
2571     return 0;
2572
2573   /* calculate t, ray intersects triangle */
2574   t = (edge2 * qvec) * inv_det;
2575
2576   //   if (det < EPSILON)
2577   //     return false;
2578
2579   //   /* calculate distance from vert0 to ray origin */
2580   //   gp_XYZ tvec = orig - vert0;
2581
2582   //   /* calculate U parameter and test bounds */
2583   //   double u = tvec * pvec;
2584   //   if (u < 0.0 || u > det)
2585 //     return 0;
2586
2587 //   /* prepare to test V parameter */
2588 //   gp_XYZ qvec = tvec ^ edge1;
2589
2590 //   /* calculate V parameter and test bounds */
2591 //   double v = dir * qvec;
2592 //   if (v < 0.0 || u + v > det)
2593 //     return 0;
2594
2595 //   /* calculate t, scale parameters, ray intersects triangle */
2596 //   double t = edge2 * qvec;
2597 //   double inv_det = 1.0 / det;
2598 //   t *= inv_det;
2599 //   //u *= inv_det;
2600 //   //v *= inv_det;
2601
2602   return true;
2603 }
2604
2605 //================================================================================
2606 /*!
2607  * \brief Perform smooth of _LayerEdge's based on EDGE's
2608  *  \retval bool - true if node has been moved
2609  */
2610 //================================================================================
2611
2612 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
2613                               const TopoDS_Face&    F,
2614                               SMESH_MesherHelper&   helper)
2615 {
2616   ASSERT( IsOnEdge() );
2617
2618   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
2619   SMESH_TNodeXYZ oldPos( tgtNode );
2620   double dist01, distNewOld;
2621   
2622   SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
2623   SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
2624   dist01 = p0.Distance( _2neibors->_nodes[1] );
2625
2626   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
2627   double lenDelta = 0;
2628   if ( _curvature )
2629   {
2630     lenDelta = _curvature->lenDelta( _len );
2631     newPos.ChangeCoord() += _normal * lenDelta;
2632   }
2633
2634   distNewOld = newPos.Distance( oldPos );
2635
2636   if ( F.IsNull() )
2637   {
2638     if ( _2neibors->_plnNorm )
2639     {
2640       // put newPos on the plane defined by source node and _plnNorm
2641       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
2642       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
2643       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
2644     }
2645     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2646     _pos.back() = newPos.XYZ();
2647   }
2648   else
2649   {
2650     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2651     gp_XY uv( Precision::Infinite(), 0 );
2652     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
2653     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2654
2655     newPos = surface->Value( uv.X(), uv.Y() );
2656     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2657   }
2658
2659   if ( _curvature && lenDelta < 0 )
2660   {
2661     gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2662     _len -= prevPos.Distance( oldPos );
2663     _len += prevPos.Distance( newPos );
2664   }
2665   bool moved = distNewOld > dist01/50;
2666   //if ( moved )
2667   dumpMove( tgtNode ); // debug
2668
2669   return moved;
2670 }
2671
2672 //================================================================================
2673 /*!
2674  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
2675  *  \retval bool - true if _tgtNode has been moved
2676  */
2677 //================================================================================
2678
2679 bool _LayerEdge::Smooth(int& badNb)
2680 {
2681   if ( _simplices.size() < 2 )
2682     return false; // _LayerEdge inflated along EDGE or FACE
2683
2684   // compute new position for the last _pos
2685   gp_XYZ newPos (0,0,0);
2686   for ( unsigned i = 0; i < _simplices.size(); ++i )
2687     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
2688   newPos /= _simplices.size();
2689
2690   if ( _curvature )
2691     newPos += _normal * _curvature->lenDelta( _len );
2692
2693   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2694 //   if ( _cosin < -0.1)
2695 //   {
2696 //     // Avoid decreasing length of edge on concave surface
2697 //     //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
2698 //     gp_Vec newMove( prevPos, newPos );
2699 //     newPos = _pos.back() + newMove.XYZ();
2700 //   }
2701 //   else if ( _cosin > 0.3 )
2702 //   {
2703 //     // Avoid increasing length of edge too much
2704
2705 //   }
2706   // count quality metrics (orientation) of tetras around _tgtNode
2707   int nbOkBefore = 0;
2708   SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
2709   for ( unsigned i = 0; i < _simplices.size(); ++i )
2710     nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
2711
2712   int nbOkAfter = 0;
2713   for ( unsigned i = 0; i < _simplices.size(); ++i )
2714     nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
2715
2716   if ( nbOkAfter < nbOkBefore )
2717     return false;
2718
2719   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
2720
2721   _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
2722   _len += prevPos.Distance(newPos);
2723
2724   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
2725   _pos.back() = newPos;
2726
2727   badNb += _simplices.size() - nbOkAfter;
2728
2729   dumpMove( n );
2730
2731   return true;
2732 }
2733
2734 //================================================================================
2735 /*!
2736  * \brief Add a new segment to _LayerEdge during inflation
2737  */
2738 //================================================================================
2739
2740 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
2741 {
2742   if ( _len - len > -1e-6 )
2743   {
2744     _pos.push_back( _pos.back() );
2745     return;
2746   }
2747
2748   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
2749   SMESH_TNodeXYZ oldXYZ( n );
2750   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
2751   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
2752
2753   _pos.push_back( nXYZ );
2754   _len = len;
2755   if ( !_sWOL.IsNull() )
2756   {
2757     double distXYZ[4];
2758     if ( _sWOL.ShapeType() == TopAbs_EDGE )
2759     {
2760       double u = Precision::Infinite(); // to force projection w/o distance check
2761       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
2762       _pos.back().SetCoord( u, 0, 0 );
2763       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
2764       pos->SetUParameter( u );
2765     }
2766     else //  TopAbs_FACE
2767     {
2768       gp_XY uv( Precision::Infinite(), 0 );
2769       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
2770       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2771       SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
2772       pos->SetUParameter( uv.X() );
2773       pos->SetVParameter( uv.Y() );
2774     }
2775     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
2776   }
2777   dumpMove( n ); //debug
2778 }
2779
2780 //================================================================================
2781 /*!
2782  * \brief Remove last inflation step
2783  */
2784 //================================================================================
2785
2786 void _LayerEdge::InvalidateStep( int curStep )
2787 {
2788   if ( _pos.size() > curStep )
2789   {
2790     _pos.resize( curStep );
2791     gp_Pnt nXYZ = _pos.back();
2792     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
2793     if ( !_sWOL.IsNull() )
2794     {
2795       TopLoc_Location loc;
2796       if ( _sWOL.ShapeType() == TopAbs_EDGE )
2797       {
2798         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
2799         pos->SetUParameter( nXYZ.X() );
2800         double f,l;
2801         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2802         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
2803       }
2804       else
2805       {
2806         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
2807         pos->SetUParameter( nXYZ.X() );
2808         pos->SetVParameter( nXYZ.Y() );
2809         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2810         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
2811       }
2812     }
2813     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
2814     dumpMove( n );
2815   }
2816 }
2817
2818 //================================================================================
2819 /*!
2820  * \brief Create layers of prisms
2821  */
2822 //================================================================================
2823
2824 bool _ViscousBuilder::refine(_SolidData& data)
2825 {
2826   SMESH_MesherHelper helper( *_mesh );
2827   helper.SetSubShape( data._solid );
2828   helper.SetElementsOnShape(false);
2829
2830   Handle(Geom_Curve) curve;
2831   Handle(Geom_Surface) surface;
2832   TopoDS_Edge geomEdge;
2833   TopoDS_Face geomFace;
2834   TopLoc_Location loc;
2835   double f,l, u/*, distXYZ[4]*/;
2836   gp_XY uv;
2837   bool isOnEdge;
2838
2839   for ( unsigned i = 0; i < data._edges.size(); ++i )
2840   {
2841     _LayerEdge& edge = *data._edges[i];
2842
2843     // get accumulated length of segments
2844     vector< double > segLen( edge._pos.size() );
2845     segLen[0] = 0.0;
2846     for ( unsigned j = 1; j < edge._pos.size(); ++j )
2847       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
2848
2849     // allocate memory for new nodes if it is not yet refined
2850     const SMDS_MeshNode* tgtNode = edge._nodes.back();
2851     if ( edge._nodes.size() == 2 )
2852     {
2853       edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
2854       edge._nodes[1] = 0;
2855       edge._nodes.back() = tgtNode;
2856     }
2857     if ( !edge._sWOL.IsNull() )
2858     {
2859       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
2860       // restore position of the last node
2861 //       gp_Pnt p;
2862       if ( isOnEdge )
2863       {
2864         geomEdge = TopoDS::Edge( edge._sWOL );
2865         curve = BRep_Tool::Curve( geomEdge, loc, f,l);
2866 //         double u = helper.GetNodeU( tgtNode );
2867 //         p = curve->Value( u );
2868       }
2869       else
2870       {
2871         geomFace = TopoDS::Face( edge._sWOL );
2872         surface = BRep_Tool::Surface( geomFace, loc );
2873 //         gp_XY uv = helper.GetNodeUV( tgtNode );
2874 //         p = surface->Value( uv.X(), uv.Y() );
2875       }
2876 //       p.Transform( loc );
2877 //       const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
2878     }
2879     // calculate height of the first layer
2880     double h0;
2881     const double T = segLen.back(); //data._hyp.GetTotalThickness();
2882     const double f = data._hyp->GetStretchFactor();
2883     const int    N = data._hyp->GetNumberLayers();
2884     const double fPowN = pow( f, N );
2885     if ( fPowN - 1 <= numeric_limits<double>::min() )
2886       h0 = T / N;
2887     else
2888       h0 = T * ( f - 1 )/( fPowN - 1 );
2889
2890     const double zeroLen = std::numeric_limits<double>::min();
2891
2892     // create intermediate nodes
2893     double hSum = 0, hi = h0/f;
2894     unsigned iSeg = 1;
2895     for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
2896     {
2897       // compute an intermediate position
2898       hi *= f;
2899       hSum += hi;
2900       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
2901         ++iSeg;
2902       int iPrevSeg = iSeg-1;
2903       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
2904         --iPrevSeg;
2905       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
2906       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
2907
2908       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
2909       if ( !edge._sWOL.IsNull() )
2910       {
2911         // compute XYZ by parameters <pos>
2912         if ( isOnEdge )
2913         {
2914           u = pos.X();
2915           pos = curve->Value( u ).Transformed(loc);
2916         }
2917         else
2918         {
2919           uv.SetCoord( pos.X(), pos.Y() );
2920           pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
2921         }
2922       }
2923       // create or update the node
2924       if ( !node )
2925       {
2926         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
2927         if ( !edge._sWOL.IsNull() )
2928         {
2929           if ( isOnEdge )
2930             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
2931           else
2932             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
2933         }
2934         else
2935         {
2936           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
2937         }
2938       }
2939       else
2940       {
2941         if ( !edge._sWOL.IsNull() )
2942         {
2943           // make average pos from new and current parameters
2944           if ( isOnEdge )
2945           {
2946             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
2947             pos = curve->Value( u ).Transformed(loc);
2948           }
2949           else
2950           {
2951             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
2952             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
2953           }
2954         }
2955         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
2956       }
2957     }
2958   }
2959
2960   // TODO: make quadratic prisms and polyhedrons(?)
2961
2962   helper.SetElementsOnShape(true);
2963
2964   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2965   for ( ; exp.More(); exp.Next() )
2966   {
2967     if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
2968       continue;
2969     SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
2970     SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
2971     vector< vector<const SMDS_MeshNode*>* > nnVec;
2972     while ( fIt->more() )
2973     {
2974       const SMDS_MeshElement* face = fIt->next();
2975       int nbNodes = face->NbCornerNodes();
2976       nnVec.resize( nbNodes );
2977       SMDS_ElemIteratorPtr nIt = face->nodesIterator();
2978       for ( int iN = 0; iN < nbNodes; ++iN )
2979       {
2980         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
2981         nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
2982       }
2983
2984       int nbZ = nnVec[0]->size();
2985       switch ( nbNodes )
2986       {
2987       case 3:
2988         for ( int iZ = 1; iZ < nbZ; ++iZ )
2989           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
2990                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
2991         break;
2992       case 4:
2993         for ( int iZ = 1; iZ < nbZ; ++iZ )
2994           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
2995                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
2996                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
2997                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
2998         break;
2999       default:
3000         return error("Not supported type of element", data._index);
3001       }
3002     }
3003   }
3004   return true;
3005 }
3006
3007 //================================================================================
3008 /*!
3009  * \brief Shrink 2D mesh on faces to let space for inflated layers
3010  */
3011 //================================================================================
3012
3013 bool _ViscousBuilder::shrink()
3014 {
3015   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3016   // inflated along FACE or EDGE)
3017   map< TGeomID, _SolidData* > f2sdMap;
3018   for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3019   {
3020     _SolidData& data = _sdVec[i];
3021     TopTools_MapOfShape FFMap;
3022     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3023     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3024       if ( s2s->second.ShapeType() == TopAbs_FACE )
3025       {
3026         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3027
3028         if ( FFMap.Add( (*s2s).second ))
3029           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3030           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3031           // by StdMeshers_QuadToTriaAdaptor
3032           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3033           {
3034             SMESH_ProxyMesh::SubMesh* proxySub =
3035               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3036             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3037             while ( fIt->more() )
3038               proxySub->AddElement( fIt->next() );
3039           }
3040       }
3041   }
3042
3043   SMESH_MesherHelper helper( *_mesh );
3044
3045   // EDGE's to shrink
3046   map< int, _Shrinker1D > e2shrMap;
3047
3048   // loop on FACES to srink mesh on
3049   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3050   for ( ; f2sd != f2sdMap.end(); ++f2sd )
3051   {
3052     _SolidData&     data = *f2sd->second;
3053     TNode2Edge&   n2eMap = data._n2eMap;
3054     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3055     const bool   reverse = ( data._reversedFaceIds.count( f2sd->first ));
3056
3057     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3058
3059     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
3060     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3061
3062     helper.SetSubShape(F);
3063
3064     // ===========================
3065     // Prepare data for shrinking
3066     // ===========================
3067
3068     // Collect nodes to smooth as src nodes are not yet replaced by tgt ones
3069     // and thus all nodes on FACE connected to 2d elements are to be smoothed
3070     vector < const SMDS_MeshNode* > smoothNodes;
3071     {
3072       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3073       while ( nIt->more() )
3074       {
3075         const SMDS_MeshNode* n = nIt->next();
3076         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3077           smoothNodes.push_back( n );
3078       }
3079     }
3080     // Find out face orientation
3081     double refSign = 1;
3082     const set<TGeomID> ignoreShapes;
3083     if ( !smoothNodes.empty() )
3084     {
3085       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0] );
3086       vector<_Simplex> simplices;
3087       getSimplices( smoothNodes[0], simplices, ignoreShapes );
3088       if ( simplices[0].IsForward(uv, F, helper,refSign) != (!reverse))
3089         refSign = -1;
3090     }
3091
3092     // Find _LayerEdge's inflated along F
3093     vector< _LayerEdge* > lEdges;
3094     {
3095       SMESH_subMeshIteratorPtr subIt =
3096         sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3097       while ( subIt->more() )
3098       {
3099         SMESH_subMesh* sub = subIt->next();
3100         SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3101         if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3102           continue;
3103         SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3104         while ( nIt->more() )
3105         {
3106           _LayerEdge* edge = n2eMap[ nIt->next() ];
3107           lEdges.push_back( edge );
3108           prepareEdgeToShrink( *edge, F, helper, smDS );
3109         }
3110       }
3111     }
3112
3113     // Replace source nodes by target nodes in mesh faces to shrink
3114     const SMDS_MeshNode* nodes[20];
3115     for ( unsigned i = 0; i < lEdges.size(); ++i )
3116     {
3117       _LayerEdge& edge = *lEdges[i];
3118       const SMDS_MeshNode* srcNode = edge._nodes[0];
3119       const SMDS_MeshNode* tgtNode = edge._nodes.back();
3120       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3121       while ( fIt->more() )
3122       {
3123         const SMDS_MeshElement* f = fIt->next();
3124         if ( !smDS->Contains( f ))
3125           continue;
3126         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3127         for ( int iN = 0; iN < f->NbNodes(); ++iN )
3128         {
3129           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3130           nodes[iN] = ( n == srcNode ? tgtNode : n );
3131         }
3132         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3133       }
3134     }
3135
3136     // Create _SmoothNode's on face F
3137     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3138     {
3139       dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3140       for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3141       {
3142         const SMDS_MeshNode* n = smoothNodes[i];
3143         nodesToSmooth[ i ]._node = n;
3144         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3145         getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes );
3146         dumpMove( n );
3147       }
3148       dumpFunctionEnd();
3149     }
3150     //if ( nodesToSmooth.empty() ) continue;
3151
3152     // Find EDGE's to shrink
3153     set< _Shrinker1D* > eShri1D;
3154     {
3155       for ( unsigned i = 0; i < lEdges.size(); ++i )
3156       {
3157         _LayerEdge* edge = lEdges[i];
3158         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3159         {
3160           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3161           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3162           eShri1D.insert( & srinker );
3163           srinker.AddEdge( edge, helper );
3164           // restore params of nodes on EGDE if the EDGE has been already
3165           // srinked while srinking another FACE
3166           srinker.RestoreParams();
3167         }
3168       }
3169     }
3170
3171     // ==================
3172     // Perform shrinking
3173     // ==================
3174
3175     bool shrinked = true;
3176     int badNb, shriStep=0, smooStep=0;
3177     while ( shrinked )
3178     {
3179       // Move boundary nodes (actually just set new UV)
3180       // -----------------------------------------------
3181       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3182       shrinked = false;
3183       for ( unsigned i = 0; i < lEdges.size(); ++i )
3184       {
3185         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3186       }
3187       dumpFunctionEnd();
3188       if ( !shrinked )
3189         break;
3190
3191       // Move nodes on EDGE's
3192       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3193       for ( ; shr != eShri1D.end(); ++shr )
3194         (*shr)->Compute( /*set3D=*/false, helper );
3195
3196       // Smoothing in 2D
3197       // -----------------
3198       int nbNoImpSteps = 0;
3199       bool moved = true;
3200       badNb = 1;
3201       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3202       {
3203         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3204
3205         int oldBadNb = badNb;
3206         badNb = 0;
3207         moved = false;
3208         for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3209         {
3210           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/false );
3211         }
3212         if ( badNb < oldBadNb )
3213           nbNoImpSteps = 0;
3214         else
3215           nbNoImpSteps++;
3216
3217         dumpFunctionEnd();
3218       }
3219       if ( badNb > 0 )
3220         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3221     }
3222     // No wrongly shaped faces remain; final smooth. Set node XYZ
3223     for ( int st = 3; st; --st )
3224     {
3225       dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3226       for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3227         nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/st==1 );
3228       dumpFunctionEnd();
3229     }
3230     // Set event listener to clear FACE sub-mesh together with SOLID sub-mesh
3231     _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3232
3233   }// loop on FACES to srink mesh on
3234
3235
3236   // Replace source nodes by target nodes in shrinked mesh edges
3237
3238   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3239   for ( ; e2shr != e2shrMap.end(); ++e2shr )
3240     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3241
3242   return true;
3243 }
3244
3245 //================================================================================
3246 /*!
3247  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3248  */
3249 //================================================================================
3250
3251 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
3252                                            const TopoDS_Face&     F,
3253                                            SMESH_MesherHelper&    helper,
3254                                            const SMESHDS_SubMesh* faceSubMesh)
3255 {
3256   const SMDS_MeshNode* srcNode = edge._nodes[0];
3257   const SMDS_MeshNode* tgtNode = edge._nodes.back();
3258
3259   edge._pos.clear();
3260
3261   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3262   {
3263     gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3264     gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3265     gp_Vec2d uvDir( srcUV, tgtUV );
3266     double uvLen = uvDir.Magnitude();
3267     uvDir /= uvLen;
3268     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3269
3270     // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3271     vector<const SMDS_MeshElement*> faces;
3272     multimap< double, const SMDS_MeshNode* > proj2node;
3273     SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3274     while ( fIt->more() )
3275     {
3276       const SMDS_MeshElement* f = fIt->next();
3277       if ( faceSubMesh->Contains( f ))
3278         faces.push_back( f );
3279     }
3280     for ( unsigned i = 0; i < faces.size(); ++i )
3281     {
3282       const int nbNodes = faces[i]->NbCornerNodes();
3283       for ( int j = 0; j < nbNodes; ++j )
3284       {
3285         const SMDS_MeshNode* n = faces[i]->GetNode(j);
3286         if ( n == srcNode ) continue;
3287         if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3288              ( faces.size() > 1 || nbNodes > 3 ))
3289           continue;
3290         gp_Pnt2d uv = helper.GetNodeUV( F, n );
3291         gp_Vec2d uvDirN( srcUV, uv );
3292         double proj = uvDirN * uvDir;
3293         proj2node.insert( make_pair( proj, n ));
3294       }
3295     }
3296
3297     multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3298     const double minProj = p2n->first;
3299     const double projThreshold = 1.1 * uvLen;
3300     if ( minProj > projThreshold )
3301     {
3302       // tgtNode is located so that it does not make faces with wrong orientation
3303       return true;
3304     }
3305     edge._pos.resize(1);
3306     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3307
3308     // store most risky nodes in _simplices
3309     p2nEnd = proj2node.lower_bound( projThreshold );
3310     int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3311     edge._simplices.resize( nbSimpl );
3312     for ( int i = 0; i < nbSimpl; ++i )
3313     {
3314       edge._simplices[i]._nPrev = p2n->second;
3315       if ( ++p2n != p2nEnd )
3316         edge._simplices[i]._nNext = p2n->second;
3317     }
3318     // set UV of source node to target node
3319     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3320     pos->SetUParameter( srcUV.X() );
3321     pos->SetVParameter( srcUV.Y() );
3322   }
3323   else // _sWOL is TopAbs_EDGE
3324   {
3325     TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3326     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3327     if ( !edgeSM || edgeSM->NbElements() == 0 )
3328       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3329
3330     const SMDS_MeshNode* n2 = 0;
3331     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3332     while ( eIt->more() && !n2 )
3333     {
3334       const SMDS_MeshElement* e = eIt->next();
3335       if ( !edgeSM->Contains(e)) continue;
3336       n2 = e->GetNode( 0 );
3337       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3338     }
3339     if ( !n2 )
3340       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3341
3342     double uSrc = helper.GetNodeU( E, srcNode, n2 );
3343     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3344     double u2   = helper.GetNodeU( E, n2,      srcNode );
3345
3346     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3347     {
3348       // tgtNode is located so that it does not make faces with wrong orientation
3349       return true;
3350     }
3351     edge._pos.resize(1);
3352     edge._pos[0].SetCoord( U_TGT, uTgt );
3353     edge._pos[0].SetCoord( U_SRC, uSrc );
3354     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3355
3356     edge._simplices.resize( 1 );
3357     edge._simplices[0]._nPrev = n2;
3358
3359     // set UV of source node to target node
3360     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3361     pos->SetUParameter( uSrc );
3362   }
3363   return true;
3364
3365   //================================================================================
3366   /*!
3367    * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3368    */
3369   //================================================================================
3370   
3371   // Compute UV to follow during shrinking
3372
3373 //   const SMDS_MeshNode* srcNode = edge._nodes[0];
3374 //   const SMDS_MeshNode* tgtNode = edge._nodes.back();
3375
3376 //   gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3377 //   gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3378 //   gp_Vec2d uvDir( srcUV, tgtUV );
3379 //   double uvLen = uvDir.Magnitude();
3380 //   uvDir /= uvLen;
3381
3382 //   // Select shrinking step such that not to make faces with wrong orientation.
3383 //   // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3384 //   const double minStepSize = uvLen / 20;
3385 //   double stepSize = uvLen;
3386 //   SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3387 //   while ( fIt->more() )
3388 //   {
3389 //     const SMDS_MeshElement* f = fIt->next();
3390 //     if ( !faceSubMesh->Contains( f )) continue;
3391 //     const int nbNodes = f->NbCornerNodes();
3392 //     for ( int i = 0; i < nbNodes; ++i )
3393 //     {
3394 //       const SMDS_MeshNode* n = f->GetNode(i);
3395 //       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3396 //         continue;
3397 //       gp_XY uv = helper.GetNodeUV( F, n );
3398 //       gp_Vec2d uvDirN( srcUV, uv );
3399 //       double proj = uvDirN * uvDir;
3400 //       if ( proj < stepSize && proj > minStepSize )
3401 //         stepSize = proj;
3402 //     }
3403 //   }
3404 //   stepSize *= 0.8;
3405
3406 //   const int nbSteps = ceil( uvLen / stepSize );
3407 //   gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3408 //   gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3409 //   edge._pos.resize( nbSteps );
3410 //   edge._pos[0] = tgtUV0;
3411 //   for ( int i = 1; i < nbSteps; ++i )
3412 //   {
3413 //     double r = i / double( nbSteps );
3414 //     edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3415 //   }
3416 //   return true;
3417 }
3418
3419 //================================================================================
3420 /*!
3421  * \brief Move target node to it's final position on the FACE during shrinking
3422  */
3423 //================================================================================
3424
3425 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3426                                  const TopoDS_Face&    F,
3427                                  SMESH_MesherHelper&   helper )
3428 {
3429   if ( _pos.empty() )
3430     return false; // already at the target position
3431
3432   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3433
3434   if ( _sWOL.ShapeType() == TopAbs_FACE )
3435   {
3436     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
3437     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3438     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
3439     const double uvLen = tgtUV.Distance( curUV );
3440
3441     // Select shrinking step such that not to make faces with wrong orientation.
3442     const double kSafe = 0.8;
3443     const double minStepSize = uvLen / 10;
3444     double stepSize = uvLen;
3445     for ( unsigned i = 0; i < _simplices.size(); ++i )
3446     {
3447       const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
3448       for ( int j = 0; j < 2; ++j )
3449         if ( const SMDS_MeshNode* n = nn[j] )
3450         {
3451           gp_XY uv = helper.GetNodeUV( F, n );
3452           gp_Vec2d uvDirN( curUV, uv );
3453           double proj = uvDirN * uvDir * kSafe;
3454           if ( proj < stepSize && proj > minStepSize )
3455             stepSize = proj;
3456         }
3457     }
3458
3459     gp_Pnt2d newUV;
3460     if ( stepSize == uvLen )
3461     {
3462       newUV = tgtUV;
3463       _pos.clear();
3464     }
3465     else
3466     {
3467       newUV = curUV + uvDir.XY() * stepSize;
3468     }
3469
3470     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3471     pos->SetUParameter( newUV.X() );
3472     pos->SetVParameter( newUV.Y() );
3473
3474 #ifdef __myDEBUG
3475     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3476     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3477     dumpMove( tgtNode );
3478 #endif
3479   }
3480   else // _sWOL is TopAbs_EDGE
3481   {
3482     TopoDS_Edge E = TopoDS::Edge( _sWOL );
3483     const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
3484
3485     const double u2 = helper.GetNodeU( E, n2, tgtNode );
3486     const double uSrc   = _pos[0].Coord( U_SRC );
3487     const double lenTgt = _pos[0].Coord( LEN_TGT );
3488
3489     double newU = _pos[0].Coord( U_TGT );
3490     if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
3491     {
3492       _pos.clear();
3493     }
3494     else
3495     {
3496       newU = 0.1 * uSrc + 0.9 * u2;
3497     }
3498     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3499     pos->SetUParameter( newU );
3500 #ifdef __myDEBUG
3501     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
3502     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3503     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3504     dumpMove( tgtNode );
3505 #endif
3506   }
3507   return true;
3508 }
3509
3510 //================================================================================
3511 /*!
3512  * \brief Perform laplacian smooth on the FACE
3513  *  \retval bool - true if the node has been moved
3514  */
3515 //================================================================================
3516
3517 bool _SmoothNode::Smooth(int&                  badNb,
3518                          Handle(Geom_Surface)& surface,
3519                          SMESH_MesherHelper&   helper,
3520                          const double          refSign,
3521                          bool                  set3D)
3522 {
3523   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
3524
3525   // compute new UV for the node
3526   gp_XY newPos (0,0);
3527   for ( unsigned i = 0; i < _simplices.size(); ++i )
3528     newPos += helper.GetNodeUV( face, _simplices[i]._nPrev );
3529   newPos /= _simplices.size();
3530
3531   // count quality metrics (orientation) of triangles around the node
3532   int nbOkBefore = 0;
3533   gp_XY tgtUV = helper.GetNodeUV( face, _node );
3534   for ( unsigned i = 0; i < _simplices.size(); ++i )
3535     nbOkBefore += _simplices[i].IsForward( tgtUV, face, helper, refSign );
3536
3537   int nbOkAfter = 0;
3538   for ( unsigned i = 0; i < _simplices.size(); ++i )
3539     nbOkAfter += _simplices[i].IsForward( newPos, face, helper, refSign );
3540
3541   if ( nbOkAfter < nbOkBefore )
3542     return false;
3543
3544   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
3545   pos->SetUParameter( newPos.X() );
3546   pos->SetVParameter( newPos.Y() );
3547
3548 #ifdef __myDEBUG
3549   set3D = true;
3550 #endif
3551   if ( set3D )
3552   {
3553     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
3554     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
3555     dumpMove( _node );
3556   }
3557
3558   badNb += _simplices.size() - nbOkAfter;
3559   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
3560 }
3561
3562 //================================================================================
3563 /*!
3564  * \brief Delete _SolidData
3565  */
3566 //================================================================================
3567
3568 _SolidData::~_SolidData()
3569 {
3570   for ( unsigned i = 0; i < _edges.size(); ++i )
3571   {
3572     if ( _edges[i] && _edges[i]->_2neibors )
3573       delete _edges[i]->_2neibors;
3574     delete _edges[i];
3575   }
3576   _edges.clear();
3577 }
3578 //================================================================================
3579 /*!
3580  * \brief Add a _LayerEdge inflated along the EDGE
3581  */
3582 //================================================================================
3583
3584 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
3585 {
3586   // init
3587   if ( _nodes.empty() )
3588   {
3589     _edges[0] = _edges[1] = 0;
3590     _done = false;
3591   }
3592   // check _LayerEdge
3593   if ( e == _edges[0] || e == _edges[1] )
3594     return;
3595   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
3596     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3597   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
3598     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3599
3600   // store _LayerEdge
3601   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3602   double f,l;
3603   BRep_Tool::Range( E, f,l );
3604   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
3605   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
3606
3607   // Update _nodes
3608
3609   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
3610   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
3611
3612   if ( _nodes.empty() )
3613   {
3614     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
3615     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
3616       return;
3617     TopLoc_Location loc;
3618     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
3619     GeomAdaptor_Curve aCurve(C);
3620     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
3621
3622     int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
3623     _initU  .reserve( nbExpectNodes );
3624     _normPar.reserve( nbExpectNodes );
3625     _nodes  .reserve( nbExpectNodes );
3626     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
3627     while ( nIt->more() )
3628     {
3629       const SMDS_MeshNode* node = nIt->next();
3630       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
3631            node == tgtNode0 || node == tgtNode1 )
3632         continue; // refinement nodes
3633       _nodes.push_back( node );
3634       _initU.push_back( helper.GetNodeU( E, node ));
3635       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
3636       _normPar.push_back(  len / totLen );
3637     }
3638   }
3639   else
3640   {
3641     // remove target node of the _LayerEdge from _nodes
3642     int nbFound = 0;
3643     for ( unsigned i = 0; i < _nodes.size(); ++i )
3644       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
3645         _nodes[i] = 0, nbFound++;
3646     if ( nbFound == _nodes.size() )
3647       _nodes.clear();
3648   }
3649 }
3650
3651 //================================================================================
3652 /*!
3653  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
3654  */
3655 //================================================================================
3656
3657 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
3658 {
3659   if ( _done || _nodes.empty())
3660     return;
3661   const _LayerEdge* e = _edges[0];
3662   if ( !e ) e = _edges[1];
3663   if ( !e ) return;
3664
3665   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
3666             ( !_edges[1] || _edges[1]->_pos.empty() ));
3667
3668   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3669   double f,l;
3670   if ( set3D || _done )
3671   {
3672     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
3673     GeomAdaptor_Curve aCurve(C);
3674
3675     if ( _edges[0] )
3676       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3677     if ( _edges[1] )
3678       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3679     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
3680
3681     for ( unsigned i = 0; i < _nodes.size(); ++i )
3682     {
3683       if ( !_nodes[i] ) continue;
3684       double len = totLen * _normPar[i];
3685       GCPnts_AbscissaPoint discret( aCurve, len, f );
3686       if ( !discret.IsDone() )
3687         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
3688       double u = discret.Parameter();
3689       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3690       pos->SetUParameter( u );
3691       gp_Pnt p = C->Value( u );
3692       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
3693     }
3694   }
3695   else
3696   {
3697     BRep_Tool::Range( E, f,l );
3698     if ( _edges[0] )
3699       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3700     if ( _edges[1] )
3701       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3702     
3703     for ( unsigned i = 0; i < _nodes.size(); ++i )
3704     {
3705       if ( !_nodes[i] ) continue;
3706       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
3707       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3708       pos->SetUParameter( u );
3709     }
3710   }
3711 }
3712
3713 //================================================================================
3714 /*!
3715  * \brief Restore initial parameters of nodes on EDGE
3716  */
3717 //================================================================================
3718
3719 void _Shrinker1D::RestoreParams()
3720 {
3721   if ( _done )
3722     for ( unsigned i = 0; i < _nodes.size(); ++i )
3723     {
3724       if ( !_nodes[i] ) continue;
3725       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3726       pos->SetUParameter( _initU[i] );
3727     }
3728   _done = false;
3729 }
3730 //================================================================================
3731 /*!
3732  * \brief Replace source nodes by target nodes in shrinked mesh edges
3733  */
3734 //================================================================================
3735
3736 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
3737 {
3738   const SMDS_MeshNode* nodes[3];
3739   for ( int i = 0; i < 2; ++i )
3740   {
3741     if ( !_edges[i] ) continue;
3742
3743     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
3744     if ( !eSubMesh ) return;
3745     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
3746     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
3747     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3748     while ( eIt->more() )
3749     {
3750       const SMDS_MeshElement* e = eIt->next();
3751       if ( !eSubMesh->Contains( e ))
3752           continue;
3753       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3754       for ( int iN = 0; iN < e->NbNodes(); ++iN )
3755       {
3756         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3757         nodes[iN] = ( n == srcNode ? tgtNode : n );
3758       }
3759       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
3760     }
3761   }
3762 }
3763
3764 //================================================================================
3765 /*!
3766  * \brief Creates 2D and 1D elements on boundaries of new prisms
3767  */
3768 //================================================================================
3769
3770 bool _ViscousBuilder::addBoundaryElements()
3771 {
3772   SMESH_MesherHelper helper( *_mesh );
3773
3774   for ( unsigned i = 0; i < _sdVec.size(); ++i )
3775   {
3776     _SolidData& data = _sdVec[i];
3777     TopTools_IndexedMapOfShape geomEdges;
3778     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
3779     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
3780     {
3781       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
3782
3783       // Get _LayerEdge's based on E
3784
3785       map< double, const SMDS_MeshNode* > u2nodes;
3786       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
3787         continue;
3788
3789       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
3790       TNode2Edge & n2eMap = data._n2eMap;
3791       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
3792       {
3793         //check if 2D elements are needed on E
3794         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
3795         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
3796         ledges.push_back( n2e->second );
3797         u2n++;
3798         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
3799           continue; // no layers on E
3800         ledges.push_back( n2eMap[ u2n->second ]);
3801
3802         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
3803         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
3804         int nbSharedPyram = 0;
3805         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
3806         while ( vIt->more() )
3807         {
3808           const SMDS_MeshElement* v = vIt->next();
3809           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
3810         }
3811         if ( nbSharedPyram > 1 )
3812           continue; // not free border of the pyramid
3813
3814         if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
3815                                     ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
3816           continue; // faces already created
3817       }
3818       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
3819         ledges.push_back( n2eMap[ u2n->second ]);
3820
3821       // Find out orientation and type of face to create
3822
3823       bool reverse = false, isOnFace;
3824       
3825       map< TGeomID, TopoDS_Shape >::iterator e2f =
3826         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
3827       TopoDS_Shape F;
3828       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
3829       {
3830         F = e2f->second.Oriented( TopAbs_FORWARD );
3831         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
3832         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
3833           reverse = !reverse;
3834       }
3835       else
3836       {
3837         // find FACE with layers sharing E
3838         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
3839         while ( fIt->more() && F.IsNull() )
3840         {
3841           const TopoDS_Shape* pF = fIt->next();
3842           if ( helper.IsSubShape( *pF, data._solid) &&
3843                !_ignoreShapeIds.count( e2f->first ))
3844             F = *pF;
3845         }
3846       }
3847       // Find the sub-mesh to add new faces
3848       SMESHDS_SubMesh* sm = 0;
3849       if ( isOnFace )
3850         sm = getMeshDS()->MeshElements( F );
3851       else
3852         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
3853       if ( !sm )
3854         return error("error in addBoundaryElements()", data._index);
3855
3856       // Make faces
3857       const int dj1 = reverse ? 0 : 1;
3858       const int dj2 = reverse ? 1 : 0;
3859       for ( unsigned j = 1; j < ledges.size(); ++j )
3860       {
3861         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
3862         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
3863         if ( isOnFace )
3864           for ( unsigned z = 1; z < nn1.size(); ++z )
3865             sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
3866         else
3867           for ( unsigned z = 1; z < nn1.size(); ++z )
3868             sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
3869       }
3870     }
3871   }
3872
3873   return true;
3874 }