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