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