Salome HOME
22580: EDF 8049 SMESH: Problems with viscous layer
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
53 #include <ElCLib.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
68 #include <TopExp.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
73 #include <TopoDS.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
77 #include <gp_Ax1.hxx>
78 #include <gp_Vec.hxx>
79 #include <gp_XY.hxx>
80
81 #include <list>
82 #include <string>
83 #include <cmath>
84 #include <limits>
85
86 //#define __myDEBUG
87
88 using namespace std;
89
90 //================================================================================
91 namespace VISCOUS_3D
92 {
93   typedef int TGeomID;
94
95   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
96
97   const double theMinSmoothCosin = 0.1;
98
99   /*!
100    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
101    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
102    */
103   struct _MeshOfSolid : public SMESH_ProxyMesh,
104                         public SMESH_subMeshEventListenerData
105   {
106     bool _n2nMapComputed;
107
108     _MeshOfSolid( SMESH_Mesh* mesh)
109       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
110     {
111       SMESH_ProxyMesh::setMesh( *mesh );
112     }
113
114     // returns submesh for a geom face
115     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
116     {
117       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
118       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
119     }
120     void setNode2Node(const SMDS_MeshNode*                 srcNode,
121                       const SMDS_MeshNode*                 proxyNode,
122                       const SMESH_ProxyMesh::SubMesh* subMesh)
123     {
124       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
125     }
126   };
127   //--------------------------------------------------------------------------------
128   /*!
129    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
130    * It is used to clear an inferior dim sub-meshes modified by viscous layers
131    */
132   class _ShrinkShapeListener : SMESH_subMeshEventListener
133   {
134     _ShrinkShapeListener()
135       : SMESH_subMeshEventListener(/*isDeletable=*/false,
136                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
137   public:
138     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
139     virtual void ProcessEvent(const int                       event,
140                               const int                       eventType,
141                               SMESH_subMesh*                  solidSM,
142                               SMESH_subMeshEventListenerData* data,
143                               const SMESH_Hypothesis*         hyp)
144     {
145       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
146       {
147         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
148       }
149     }
150   };
151   //--------------------------------------------------------------------------------
152   /*!
153    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
154    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
155    * delete the data as soon as it has been used
156    */
157   class _ViscousListener : SMESH_subMeshEventListener
158   {
159     _ViscousListener():
160       SMESH_subMeshEventListener(/*isDeletable=*/false,
161                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
162     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
163   public:
164     virtual void ProcessEvent(const int                       event,
165                               const int                       eventType,
166                               SMESH_subMesh*                  subMesh,
167                               SMESH_subMeshEventListenerData* data,
168                               const SMESH_Hypothesis*         hyp)
169     {
170       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
171       {
172         // delete SMESH_ProxyMesh containing temporary faces
173         subMesh->DeleteEventListener( this );
174       }
175     }
176     // Finds or creates proxy mesh of the solid
177     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
178                                       const TopoDS_Shape& solid,
179                                       bool                toCreate=false)
180     {
181       if ( !mesh ) return 0;
182       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
183       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
184       if ( !data && toCreate )
185       {
186         data = new _MeshOfSolid(mesh);
187         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
188         sm->SetEventListener( Get(), data, sm );
189       }
190       return data;
191     }
192     // Removes proxy mesh of the solid
193     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
194     {
195       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
196     }
197   };
198   
199   //================================================================================
200   /*!
201    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
202    * the main shape when sub-mesh of the main shape is cleared,
203    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
204    * is cleared
205    */
206   //================================================================================
207
208   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
209   {
210     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
211     SMESH_subMeshEventListenerData* data =
212       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
213     if ( data )
214     {
215       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
216            data->mySubMeshes.end())
217         data->mySubMeshes.push_back( sub );
218     }
219     else
220     {
221       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
222       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
223     }
224   }
225   //--------------------------------------------------------------------------------
226   /*!
227    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
228    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
229    * The class is used to check validity of face or volumes around a smoothed node;
230    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
231    */
232   struct _Simplex
233   {
234     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
235     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
236     _Simplex(const SMDS_MeshNode* nPrev=0,
237              const SMDS_MeshNode* nNext=0,
238              const SMDS_MeshNode* nOpp=0)
239       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
240     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
241     {
242       const double M[3][3] =
243         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
244          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
245          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
246       double determinant = ( + M[0][0]*M[1][1]*M[2][2]
247                              + M[0][1]*M[1][2]*M[2][0]
248                              + M[0][2]*M[1][0]*M[2][1]
249                              - M[0][0]*M[1][2]*M[2][1]
250                              - M[0][1]*M[1][0]*M[2][2]
251                              - M[0][2]*M[1][1]*M[2][0]);
252       return determinant > 1e-100;
253     }
254     bool IsForward(const gp_XY&         tgtUV,
255                    const SMDS_MeshNode* smoothedNode,
256                    const TopoDS_Face&   face,
257                    SMESH_MesherHelper&  helper,
258                    const double         refSign) const
259     {
260       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
261       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
262       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
263       double d = v1 ^ v2;
264       return d*refSign > 1e-100;
265     }
266     bool IsNeighbour(const _Simplex& other) const
267     {
268       return _nPrev == other._nNext || _nNext == other._nPrev;
269     }
270   };
271   //--------------------------------------------------------------------------------
272   /*!
273    * Structure used to take into account surface curvature while smoothing
274    */
275   struct _Curvature
276   {
277     double _r; // radius
278     double _k; // factor to correct node smoothed position
279     double _h2lenRatio; // avgNormProj / (2*avgDist)
280   public:
281     static _Curvature* New( double avgNormProj, double avgDist )
282     {
283       _Curvature* c = 0;
284       if ( fabs( avgNormProj / avgDist ) > 1./200 )
285       {
286         c = new _Curvature;
287         c->_r = avgDist * avgDist / avgNormProj;
288         c->_k = avgDist * avgDist / c->_r / c->_r;
289         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
290         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
291       }
292       return c;
293     }
294     double lenDelta(double len) const { return _k * ( _r + len ); }
295     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
296   };
297   struct _LayerEdge;
298   //--------------------------------------------------------------------------------
299   /*!
300    * Structure used to smooth a _LayerEdge (master) based on an EDGE.
301    */
302   struct _2NearEdges
303   {
304     // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
305     const SMDS_MeshNode* _nodes[2];
306     // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
307     //gp_XYZ               _vec[2];
308     double               _wgt[2]; // weights of _nodes
309     _LayerEdge*          _edges[2];
310
311      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
312     gp_XYZ*              _plnNorm;
313
314     _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
315     void reverse() {
316       std::swap( _nodes[0], _nodes[1] );
317       std::swap( _wgt  [0], _wgt  [1] );
318       std::swap( _edges[0], _edges[1] );
319     }
320   };
321   //--------------------------------------------------------------------------------
322   /*!
323    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
324    * and a node of the most internal layer (_nodes.back())
325    */
326   struct _LayerEdge
327   {
328     vector< const SMDS_MeshNode*> _nodes;
329
330     gp_XYZ              _normal; // to solid surface
331     vector<gp_XYZ>      _pos; // points computed during inflation
332     double              _len; // length achived with the last inflation step
333     double              _cosin; // of angle (_normal ^ surface)
334     double              _lenFactor; // to compute _len taking _cosin into account
335
336     // face or edge w/o layer along or near which _LayerEdge is inflated
337     TopoDS_Shape        _sWOL;
338     // simplices connected to the source node (_nodes[0]);
339     // used for smoothing and quality check of _LayerEdge's based on the FACE
340     vector<_Simplex>    _simplices;
341     // data for smoothing of _LayerEdge's based on the EDGE
342     _2NearEdges*        _2neibors;
343
344     _Curvature*         _curvature;
345     // TODO:: detele _Curvature, _plnNorm
346
347     void SetNewLength( double len, SMESH_MesherHelper& helper );
348     bool SetNewLength2d( Handle(Geom_Surface)& surface,
349                          const TopoDS_Face&    F,
350                          SMESH_MesherHelper&   helper );
351     void SetDataByNeighbors( const SMDS_MeshNode* n1,
352                              const SMDS_MeshNode* n2,
353                              SMESH_MesherHelper&  helper);
354     void InvalidateStep( int curStep, bool restoreLength=false );
355     bool Smooth(int& badNb);
356     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
357                       const TopoDS_Face&    F,
358                       SMESH_MesherHelper&   helper);
359     bool FindIntersection( SMESH_ElementSearcher&   searcher,
360                            double &                 distance,
361                            const double&            epsilon,
362                            const SMDS_MeshElement** face = 0);
363     bool SegTriaInter( const gp_Ax1&        lastSegment,
364                        const SMDS_MeshNode* n0,
365                        const SMDS_MeshNode* n1,
366                        const SMDS_MeshNode* n2,
367                        double&              dist,
368                        const double&        epsilon) const;
369     gp_Ax1 LastSegment(double& segLen) const;
370     bool   IsOnEdge() const { return _2neibors; }
371     gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
372     void   SetCosin( double cosin );
373   };
374   struct _LayerEdgeCmp
375   {
376     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
377     {
378       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
379       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
380     }
381   };
382   //--------------------------------------------------------------------------------
383   /*!
384    * \brief Convex FACE whose radius of curvature is less than the thickness of 
385    *        layers. It is used to detect distortion of prisms based on a convex
386    *        FACE and to update normals to enable further increasing the thickness
387    */
388   struct _ConvexFace
389   {
390     TopoDS_Face                     _face;
391
392     // edges whose _simplices are used to detect prism destorsion
393     vector< _LayerEdge* >           _simplexTestEdges;
394
395     // map a sub-shape to it's index in _SolidData::_endEdgeOnShape vector
396     map< TGeomID, int >             _subIdToEdgeEnd;
397
398     bool                            _normalsFixed;
399
400     bool GetCenterOfCurvature( _LayerEdge*         ledge,
401                                BRepLProp_SLProps&  surfProp,
402                                SMESH_MesherHelper& helper,
403                                gp_Pnt &            center ) const;
404     bool CheckPrisms() const;
405   };
406
407   //--------------------------------------------------------------------------------
408
409   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
410   
411   //--------------------------------------------------------------------------------
412   /*!
413    * \brief Data of a SOLID
414    */
415   struct _SolidData
416   {
417     TopoDS_Shape                    _solid;
418     const StdMeshers_ViscousLayers* _hyp;
419     TopoDS_Shape                    _hypShape;
420     _MeshOfSolid*                   _proxyMesh;
421     set<TGeomID>                    _reversedFaceIds;
422     set<TGeomID>                    _ignoreFaceIds;
423
424     double                          _stepSize, _stepSizeCoeff;
425     const SMDS_MeshNode*            _stepSizeNodes[2];
426
427     TNode2Edge                      _n2eMap;
428     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
429     map< TGeomID, TNode2Edge* >     _s2neMap;
430     // edges of _n2eMap. We keep same data in two containers because
431     // iteration over the map is 5 time longer than over the vector
432     vector< _LayerEdge* >           _edges;
433
434     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
435     //        layers and a FACE w/o layers
436     // value: the shape (FACE or EDGE) to shrink mesh on.
437     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
438     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
439
440     // Convex FACEs whose radius of curvature is less than the thickness of layers
441     map< TGeomID, _ConvexFace >      _convexFaces;
442
443     // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
444     set< TGeomID >                   _noShrinkFaces;
445
446     // <EDGE to smooth on> to <it's curve> -- for analytic smooth
447     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
448
449     // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
450     vector< int >                    _endEdgeOnShape;
451     int                              _nbShapesToSmooth;
452
453     double                           _epsilon; // precision for SegTriaInter()
454
455     int                              _index; // for debug
456
457     _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
458                const StdMeshers_ViscousLayers* h=0,
459                const TopoDS_Shape&             hs=TopoDS_Shape(),
460                _MeshOfSolid*                   m=0)
461       :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
462     ~_SolidData();
463
464     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
465                                        const int             iFrom,
466                                        const int             iTo,
467                                        Handle(Geom_Surface)& surface,
468                                        const TopoDS_Face&    F,
469                                        SMESH_MesherHelper&   helper);
470
471     void SortOnEdge( const TopoDS_Edge&  E,
472                      const int           iFrom,
473                      const int           iTo,
474                      SMESH_MesherHelper& helper);
475
476     _ConvexFace* GetConvexFace( const TGeomID faceID )
477     {
478       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
479       return id2face == _convexFaces.end() ? 0 : & id2face->second;
480     }
481     void GetEdgesOnShape( size_t end, int &  iBeg, int &  iEnd )
482     {
483       iBeg = end > 0 ? _endEdgeOnShape[ end-1 ] : 0;
484       iEnd = _endEdgeOnShape[ end ];
485     }
486
487     bool GetShapeEdges(const TGeomID shapeID, size_t& edgeEnd, int* iBeg=0, int* iEnd=0 ) const;
488
489     void AddFacesToSmooth( const set< TGeomID >& faceIDs );
490   };
491   //--------------------------------------------------------------------------------
492   /*!
493    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
494    */
495   struct _CentralCurveOnEdge
496   {
497     bool                  _isDegenerated;
498     vector< gp_Pnt >      _curvaCenters;
499     vector< _LayerEdge* > _ledges;
500     vector< gp_XYZ >      _normals; // new normal for each of _ledges
501     vector< double >      _segLength2;
502
503     TopoDS_Edge           _edge;
504     TopoDS_Face           _adjFace;
505     bool                  _adjFaceToSmooth;
506
507     void Append( const gp_Pnt& center, _LayerEdge* ledge )
508     {
509       if ( _curvaCenters.size() > 0 )
510         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
511       _curvaCenters.push_back( center );
512       _ledges.push_back( ledge );
513       _normals.push_back( ledge->_normal );
514     }
515     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
516     void SetShapes( const TopoDS_Edge&  edge,
517                     const _ConvexFace&  convFace,
518                     const _SolidData&   data,
519                     SMESH_MesherHelper& helper);
520   };
521   //--------------------------------------------------------------------------------
522   /*!
523    * \brief Data of node on a shrinked FACE
524    */
525   struct _SmoothNode
526   {
527     const SMDS_MeshNode*         _node;
528     vector<_Simplex>             _simplices; // for quality check
529
530     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
531
532     bool Smooth(int&                  badNb,
533                 Handle(Geom_Surface)& surface,
534                 SMESH_MesherHelper&   helper,
535                 const double          refSign,
536                 SmoothType            how,
537                 bool                  set3D);
538
539     gp_XY computeAngularPos(vector<gp_XY>& uv,
540                             const gp_XY&   uvToFix,
541                             const double   refSign );
542   };
543   //--------------------------------------------------------------------------------
544   /*!
545    * \brief Builder of viscous layers
546    */
547   class _ViscousBuilder
548   {
549   public:
550     _ViscousBuilder();
551     // does it's job
552     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
553                                   const TopoDS_Shape& shape);
554
555     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
556     void RestoreListeners();
557
558     // computes SMESH_ProxyMesh::SubMesh::_n2n;
559     bool MakeN2NMap( _MeshOfSolid* pm );
560
561   private:
562
563     bool findSolidsWithLayers();
564     bool findFacesWithLayers();
565     bool makeLayer(_SolidData& data);
566     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
567                      SMESH_MesherHelper& helper, _SolidData& data);
568     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
569                          const TopoDS_Face&   face,
570                          SMESH_MesherHelper&  helper,
571                          bool&                isOK,
572                          bool                 shiftInside=false);
573     gp_XYZ getWeigthedNormal( const SMDS_MeshNode*         n,
574                               std::pair< TGeomID, gp_XYZ > fId2Normal[],
575                               const int                    nbFaces );
576     bool findNeiborsOnEdge(const _LayerEdge*     edge,
577                            const SMDS_MeshNode*& n1,
578                            const SMDS_MeshNode*& n2,
579                            _SolidData&           data);
580     void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
581                        const set<TGeomID>& ingnoreShapes,
582                        const _SolidData*   dataToCheckOri = 0,
583                        const bool          toSort = false);
584     void findSimplexTestEdges( _SolidData&                    data,
585                                vector< vector<_LayerEdge*> >& edgesByGeom);
586     bool sortEdges( _SolidData&                    data,
587                     vector< vector<_LayerEdge*> >& edgesByGeom);
588     void limitStepSizeByCurvature( _SolidData&  data );
589     void limitStepSize( _SolidData&             data,
590                         const SMDS_MeshElement* face,
591                         const double            cosin);
592     void limitStepSize( _SolidData& data, const double minSize);
593     bool inflate(_SolidData& data);
594     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
595     bool smoothAnalyticEdge( _SolidData&           data,
596                              const int             iFrom,
597                              const int             iTo,
598                              Handle(Geom_Surface)& surface,
599                              const TopoDS_Face&    F,
600                              SMESH_MesherHelper&   helper);
601     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
602     bool updateNormalsOfConvexFaces( _SolidData&         data,
603                                      SMESH_MesherHelper& helper,
604                                      int                 stepNb );
605     bool refine(_SolidData& data);
606     bool shrink();
607     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
608                               SMESH_MesherHelper& helper,
609                               const SMESHDS_SubMesh* faceSubMesh );
610     void fixBadFaces(const TopoDS_Face&          F,
611                      SMESH_MesherHelper&         helper,
612                      const bool                  is2D,
613                      const int                   step,
614                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
615     bool addBoundaryElements();
616
617     bool error( const string& text, int solidID=-1 );
618     SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
619
620     // debug
621     void makeGroupOfLE();
622
623     SMESH_Mesh*           _mesh;
624     SMESH_ComputeErrorPtr _error;
625
626     vector< _SolidData >  _sdVec;
627     int                   _tmpFaceID;
628   };
629   //--------------------------------------------------------------------------------
630   /*!
631    * \brief Shrinker of nodes on the EDGE
632    */
633   class _Shrinker1D
634   {
635     vector<double>                _initU;
636     vector<double>                _normPar;
637     vector<const SMDS_MeshNode*>  _nodes;
638     const _LayerEdge*             _edges[2];
639     bool                          _done;
640   public:
641     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
642     void Compute(bool set3D, SMESH_MesherHelper& helper);
643     void RestoreParams();
644     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
645   };
646   //--------------------------------------------------------------------------------
647   /*!
648    * \brief Class of temporary mesh face.
649    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
650    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
651    */
652   struct _TmpMeshFace : public SMDS_MeshElement
653   {
654     vector<const SMDS_MeshNode* > _nn;
655     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
656       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
657     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
658     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
659     virtual vtkIdType GetVtkType() const                      { return -1; }
660     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
661     virtual SMDSAbs_GeometryType GetGeomType() const          { return SMDSGeom_TRIANGLE; }
662     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
663     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
664   };
665   //--------------------------------------------------------------------------------
666   /*!
667    * \brief Class of temporary mesh face storing _LayerEdge it's based on
668    */
669   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
670   {
671     _LayerEdge *_le1, *_le2;
672     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
673       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
674     {
675       _nn[0]=_le1->_nodes[0];
676       _nn[1]=_le1->_nodes.back();
677       _nn[2]=_le2->_nodes.back();
678       _nn[3]=_le2->_nodes[0];
679     }
680   };
681   //--------------------------------------------------------------------------------
682   /*!
683    * \brief Retriever of node coordinates either directly of from a surface by node UV.
684    * \warning Location of a surface is ignored
685    */
686   struct _NodeCoordHelper
687   {
688     SMESH_MesherHelper&        _helper;
689     const TopoDS_Face&         _face;
690     Handle(Geom_Surface)       _surface;
691     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
692
693     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
694       : _helper( helper ), _face( F )
695     {
696       if ( is2D )
697       {
698         TopLoc_Location loc;
699         _surface = BRep_Tool::Surface( _face, loc );
700       }
701       if ( _surface.IsNull() )
702         _fun = & _NodeCoordHelper::direct;
703       else
704         _fun = & _NodeCoordHelper::byUV;
705     }
706     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
707
708   private:
709     gp_XYZ direct(const SMDS_MeshNode* n) const
710     {
711       return SMESH_TNodeXYZ( n );
712     }
713     gp_XYZ byUV  (const SMDS_MeshNode* n) const
714     {
715       gp_XY uv = _helper.GetNodeUV( _face, n );
716       return _surface->Value( uv.X(), uv.Y() ).XYZ();
717     }
718   };
719 } // namespace VISCOUS_3D
720
721
722
723 //================================================================================
724 // StdMeshers_ViscousLayers hypothesis
725 //
726 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
727   :SMESH_Hypothesis(hypId, studyId, gen),
728    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
729 {
730   _name = StdMeshers_ViscousLayers::GetHypType();
731   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
732 } // --------------------------------------------------------------------------------
733 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
734 {
735   if ( faceIds != _shapeIds )
736     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
737   if ( _isToIgnoreShapes != toIgnore )
738     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
739 } // --------------------------------------------------------------------------------
740 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
741 {
742   if ( thickness != _thickness )
743     _thickness = thickness, NotifySubMeshesHypothesisModification();
744 } // --------------------------------------------------------------------------------
745 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
746 {
747   if ( _nbLayers != nb )
748     _nbLayers = nb, NotifySubMeshesHypothesisModification();
749 } // --------------------------------------------------------------------------------
750 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
751 {
752   if ( _stretchFactor != factor )
753     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
754 } // --------------------------------------------------------------------------------
755 SMESH_ProxyMesh::Ptr
756 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
757                                   const TopoDS_Shape& theShape,
758                                   const bool          toMakeN2NMap) const
759 {
760   using namespace VISCOUS_3D;
761   _ViscousBuilder bulder;
762   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
763   if ( err && !err->IsOK() )
764     return SMESH_ProxyMesh::Ptr();
765
766   vector<SMESH_ProxyMesh::Ptr> components;
767   TopExp_Explorer exp( theShape, TopAbs_SOLID );
768   for ( ; exp.More(); exp.Next() )
769   {
770     if ( _MeshOfSolid* pm =
771          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
772     {
773       if ( toMakeN2NMap && !pm->_n2nMapComputed )
774         if ( !bulder.MakeN2NMap( pm ))
775           return SMESH_ProxyMesh::Ptr();
776       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
777       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
778     }
779     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
780   }
781   switch ( components.size() )
782   {
783   case 0: break;
784
785   case 1: return components[0];
786
787   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
788   }
789   return SMESH_ProxyMesh::Ptr();
790 } // --------------------------------------------------------------------------------
791 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
792 {
793   save << " " << _nbLayers
794        << " " << _thickness
795        << " " << _stretchFactor
796        << " " << _shapeIds.size();
797   for ( size_t i = 0; i < _shapeIds.size(); ++i )
798     save << " " << _shapeIds[i];
799   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
800   return save;
801 } // --------------------------------------------------------------------------------
802 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
803 {
804   int nbFaces, faceID, shapeToTreat;
805   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
806   while ( _shapeIds.size() < nbFaces && load >> faceID )
807     _shapeIds.push_back( faceID );
808   if ( load >> shapeToTreat )
809     _isToIgnoreShapes = !shapeToTreat;
810   else
811     _isToIgnoreShapes = true; // old behavior
812   return load;
813 } // --------------------------------------------------------------------------------
814 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
815                                                    const TopoDS_Shape& theShape)
816 {
817   // TODO
818   return false;
819 }
820 // END StdMeshers_ViscousLayers hypothesis
821 //================================================================================
822
823 namespace
824 {
825   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
826   {
827     gp_Vec dir;
828     double f,l;
829     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
830     gp_Pnt p = BRep_Tool::Pnt( fromV );
831     double distF = p.SquareDistance( c->Value( f ));
832     double distL = p.SquareDistance( c->Value( l ));
833     c->D1(( distF < distL ? f : l), p, dir );
834     if ( distL < distF ) dir.Reverse();
835     return dir.XYZ();
836   }
837   //--------------------------------------------------------------------------------
838   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
839                      SMESH_MesherHelper& helper)
840   {
841     gp_Vec dir;
842     double f,l; gp_Pnt p;
843     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
844     double u = helper.GetNodeU( E, atNode );
845     c->D1( u, p, dir );
846     return dir.XYZ();
847   }
848   //--------------------------------------------------------------------------------
849   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
850                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
851   {
852     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
853     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
854     gp_Pnt p; gp_Vec du, dv, norm;
855     surface->D1( uv.X(),uv.Y(), p, du,dv );
856     norm = du ^ dv;
857
858     double f,l;
859     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
860     double u = helper.GetNodeU( fromE, node, 0, &ok );
861     c->D1( u, p, du );
862     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
863     if ( o == TopAbs_REVERSED )
864       du.Reverse();
865
866     gp_Vec dir = norm ^ du;
867
868     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
869          helper.IsClosedEdge( fromE ))
870     {
871       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
872       else                        c->D1( f, p, dv );
873       if ( o == TopAbs_REVERSED )
874         dv.Reverse();
875       gp_Vec dir2 = norm ^ dv;
876       dir = dir.Normalized() + dir2.Normalized();
877     }
878     return dir.XYZ();
879   }
880   //--------------------------------------------------------------------------------
881   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
882                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
883                      bool& ok, double* cosin=0)
884   {
885     TopoDS_Face faceFrw = F;
886     faceFrw.Orientation( TopAbs_FORWARD );
887     double f,l; TopLoc_Location loc;
888     TopoDS_Edge edges[2]; // sharing a vertex
889     int nbEdges = 0;
890     {
891       TopoDS_Vertex VV[2];
892       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
893       for ( ; exp.More() && nbEdges < 2; exp.Next() )
894       {
895         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
896         if ( SMESH_Algo::isDegenerated( e )) continue;
897         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
898         if ( VV[1].IsSame( fromV )) {
899           edges[ 0 ] = e;
900           nbEdges++;
901         }
902         else if ( VV[0].IsSame( fromV )) {
903           edges[ 1 ] = e;
904           nbEdges++;
905         }
906       }
907     }
908     gp_XYZ dir(0,0,0), edgeDir[2];
909     if ( nbEdges == 2 )
910     {
911       // get dirs of edges going fromV
912       ok = true;
913       for ( size_t i = 0; i < nbEdges && ok; ++i )
914       {
915         edgeDir[i] = getEdgeDir( edges[i], fromV );
916         double size2 = edgeDir[i].SquareModulus();
917         if (( ok = size2 > numeric_limits<double>::min() ))
918           edgeDir[i] /= sqrt( size2 );
919       }
920       if ( !ok ) return dir;
921
922       // get angle between the 2 edges
923       gp_Vec faceNormal;
924       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, &faceNormal );
925       if ( Abs( angle ) < 5 * M_PI/180 )
926       {
927         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
928       }
929       else
930       {
931         dir = edgeDir[0] + edgeDir[1];
932         if ( angle < 0 )
933           dir.Reverse();
934       }
935       if ( cosin ) {
936         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
937         *cosin = Cos( angle );
938       }
939     }
940     else if ( nbEdges == 1 )
941     {
942       dir = getFaceDir( faceFrw, edges[0], node, helper, ok );
943       if ( cosin ) *cosin = 1.;
944     }
945     else
946     {
947       ok = false;
948     }
949
950     return dir;
951   }
952   //================================================================================
953   /*!
954    * \brief Returns true if a FACE is bound by a concave EDGE
955    */
956   //================================================================================
957
958   bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
959   {
960     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
961     //   return true;
962     gp_Vec2d drv1, drv2;
963     gp_Pnt2d p;
964     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
965     for ( ; eExp.More(); eExp.Next() )
966     {
967       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
968       if ( SMESH_Algo::isDegenerated( E )) continue;
969       // check if 2D curve is concave
970       BRepAdaptor_Curve2d curve( E, F );
971       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
972       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
973       curve.Intervals( intervals, GeomAbs_C2 );
974       bool isConvex = true;
975       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
976       {
977         double u1 = intervals( i );
978         double u2 = intervals( i+1 );
979         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
980         double cross = drv2 ^ drv1;
981         if ( E.Orientation() == TopAbs_REVERSED )
982           cross = -cross;
983         isConvex = ( cross > 0.1 ); //-1e-9 );
984       }
985       if ( !isConvex )
986       {
987         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
988         return true;
989       }
990     }
991     // check angles at VERTEXes
992     TError error;
993     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
994     for ( size_t iW = 0; iW < wires.size(); ++iW )
995     {
996       const int nbEdges = wires[iW]->NbEdges();
997       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
998         continue;
999       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1000       {
1001         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1002         int iE2 = ( iE1 + 1 ) % nbEdges;
1003         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1004           iE2 = ( iE2 + 1 ) % nbEdges;
1005         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1006                                         wires[iW]->Edge( iE2 ), F );
1007         if ( angle < -5. * M_PI / 180. )
1008           return true;
1009       }
1010     }
1011     return false;
1012   }
1013   //--------------------------------------------------------------------------------
1014   // DEBUG. Dump intermediate node positions into a python script
1015 #ifdef __myDEBUG
1016   ofstream* py;
1017   struct PyDump {
1018     PyDump() {
1019       const char* fname = "/tmp/viscous.py";
1020       cout << "execfile('"<<fname<<"')"<<endl;
1021       py = new ofstream(fname);
1022       *py << "import SMESH" << endl
1023           << "from salome.smesh import smeshBuilder" << endl
1024           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1025           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
1026           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1027     }
1028     void Finish() {
1029       if (py)
1030         *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
1031       delete py; py=0;
1032     }
1033     ~PyDump() { Finish(); }
1034   };
1035 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1036 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1037 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1038   void _dumpFunction(const string& fun, int ln)
1039   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
1040   void _dumpMove(const SMDS_MeshNode* n, int ln)
1041   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1042                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
1043   void _dumpCmd(const string& txt, int ln)
1044   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1045   void dumpFunctionEnd()
1046   { if (py) *py<< "  return"<< endl; }
1047   void dumpChangeNodes( const SMDS_MeshElement* f )
1048   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1049       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1050       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1051 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1052 #else
1053   struct PyDump { void Finish() {} };
1054 #define dumpFunction(f) f
1055 #define dumpMove(n)
1056 #define dumpCmd(txt)
1057 #define dumpFunctionEnd()
1058 #define dumpChangeNodes(f)
1059 #define debugMsg( txt ) {}
1060 #endif
1061 }
1062
1063 using namespace VISCOUS_3D;
1064
1065 //================================================================================
1066 /*!
1067  * \brief Constructor of _ViscousBuilder
1068  */
1069 //================================================================================
1070
1071 _ViscousBuilder::_ViscousBuilder()
1072 {
1073   _error = SMESH_ComputeError::New(COMPERR_OK);
1074   _tmpFaceID = 0;
1075 }
1076
1077 //================================================================================
1078 /*!
1079  * \brief Stores error description and returns false
1080  */
1081 //================================================================================
1082
1083 bool _ViscousBuilder::error(const string& text, int solidId )
1084 {
1085   _error->myName    = COMPERR_ALGO_FAILED;
1086   _error->myComment = string("Viscous layers builder: ") + text;
1087   if ( _mesh )
1088   {
1089     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1090     if ( !sm && !_sdVec.empty() )
1091       sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1092     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1093     {
1094       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1095       if ( smError && smError->myAlgo )
1096         _error->myAlgo = smError->myAlgo;
1097       smError = _error;
1098     }
1099   }
1100   makeGroupOfLE(); // debug
1101
1102   return false;
1103 }
1104
1105 //================================================================================
1106 /*!
1107  * \brief At study restoration, restore event listeners used to clear an inferior
1108  *  dim sub-mesh modified by viscous layers
1109  */
1110 //================================================================================
1111
1112 void _ViscousBuilder::RestoreListeners()
1113 {
1114   // TODO
1115 }
1116
1117 //================================================================================
1118 /*!
1119  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1120  */
1121 //================================================================================
1122
1123 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1124 {
1125   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1126   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1127   for ( ; fExp.More(); fExp.Next() )
1128   {
1129     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1130     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1131
1132     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1133       continue;
1134     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1135       continue;
1136
1137     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1138       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1139
1140     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1141     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1142     while( prxIt->more() )
1143     {
1144       const SMDS_MeshElement* fSrc = srcIt->next();
1145       const SMDS_MeshElement* fPrx = prxIt->next();
1146       if ( fSrc->NbNodes() != fPrx->NbNodes())
1147         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1148       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1149         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1150     }
1151   }
1152   pm->_n2nMapComputed = true;
1153   return true;
1154 }
1155
1156 //================================================================================
1157 /*!
1158  * \brief Does its job
1159  */
1160 //================================================================================
1161
1162 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1163                                                const TopoDS_Shape& theShape)
1164 {
1165   // TODO: set priority of solids during Gen::Compute()
1166
1167   _mesh = & theMesh;
1168
1169   // check if proxy mesh already computed
1170   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1171   if ( !exp.More() )
1172     return error("No SOLID's in theShape"), _error;
1173
1174   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1175     return SMESH_ComputeErrorPtr(); // everything already computed
1176
1177   PyDump debugDump;
1178
1179   // TODO: ignore already computed SOLIDs 
1180   if ( !findSolidsWithLayers())
1181     return _error;
1182
1183   if ( !findFacesWithLayers() )
1184     return _error;
1185
1186   for ( size_t i = 0; i < _sdVec.size(); ++i )
1187   {
1188     if ( ! makeLayer(_sdVec[i]) )
1189       return _error;
1190
1191     if ( _sdVec[i]._edges.size() == 0 )
1192       continue;
1193     
1194     if ( ! inflate(_sdVec[i]) )
1195       return _error;
1196
1197     if ( ! refine(_sdVec[i]) )
1198       return _error;
1199   }
1200   if ( !shrink() )
1201     return _error;
1202
1203   addBoundaryElements();
1204
1205   makeGroupOfLE(); // debug
1206   debugDump.Finish();
1207
1208   return _error;
1209 }
1210
1211 //================================================================================
1212 /*!
1213  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1214  */
1215 //================================================================================
1216
1217 bool _ViscousBuilder::findSolidsWithLayers()
1218 {
1219   // get all solids
1220   TopTools_IndexedMapOfShape allSolids;
1221   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1222   _sdVec.reserve( allSolids.Extent());
1223
1224   SMESH_Gen* gen = _mesh->GetGen();
1225   SMESH_HypoFilter filter;
1226   for ( int i = 1; i <= allSolids.Extent(); ++i )
1227   {
1228     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1229     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1230     if ( !algo ) continue;
1231     // TODO: check if algo is hidden
1232     const list <const SMESHDS_Hypothesis *> & allHyps =
1233       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1234     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1235     const StdMeshers_ViscousLayers* viscHyp = 0;
1236     for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1237       viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1238     if ( viscHyp )
1239     {
1240       TopoDS_Shape hypShape;
1241       filter.Init( filter.Is( viscHyp ));
1242       _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1243
1244       _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1245                                                                 allSolids(i),
1246                                                                 /*toCreate=*/true);
1247       _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1248       _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1249     }
1250   }
1251   if ( _sdVec.empty() )
1252     return error
1253       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1254
1255   return true;
1256 }
1257
1258 //================================================================================
1259 /*!
1260  * \brief 
1261  */
1262 //================================================================================
1263
1264 bool _ViscousBuilder::findFacesWithLayers()
1265 {
1266   SMESH_MesherHelper helper( *_mesh );
1267   TopExp_Explorer exp;
1268   TopTools_IndexedMapOfShape solids;
1269
1270   // collect all faces to ignore defined by hyp
1271   for ( size_t i = 0; i < _sdVec.size(); ++i )
1272   {
1273     solids.Add( _sdVec[i]._solid );
1274
1275     vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1276     if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1277     {
1278       for ( size_t ii = 0; ii < ids.size(); ++ii )
1279       {
1280         const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1281         if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1282           _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1283       }
1284     }
1285     else // FACEs with layers are given
1286     {
1287       exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1288       for ( ; exp.More(); exp.Next() )
1289       {
1290         TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1291         if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1292           _sdVec[i]._ignoreFaceIds.insert( faceInd );
1293       }
1294     }
1295
1296     // ignore internal FACEs if inlets and outlets are specified
1297     {
1298       TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1299       if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1300         TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1301                                        TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1302
1303       exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1304       for ( ; exp.More(); exp.Next() )
1305       {
1306         const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1307         if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1308           continue;
1309
1310         const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1311         if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1312         {
1313           int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1314           if ( nbSolids > 1 )
1315             _sdVec[i]._ignoreFaceIds.insert( faceInd );
1316         }
1317
1318         if ( helper.IsReversedSubMesh( face ))
1319         {
1320           _sdVec[i]._reversedFaceIds.insert( faceInd );
1321         }
1322       }
1323     }
1324   }
1325
1326   // Find faces to shrink mesh on (solution 2 in issue 0020832);
1327   TopTools_IndexedMapOfShape shapes;
1328   for ( size_t i = 0; i < _sdVec.size(); ++i )
1329   {
1330     shapes.Clear();
1331     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1332     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1333     {
1334       const TopoDS_Shape& edge = shapes(iE);
1335       // find 2 faces sharing an edge
1336       TopoDS_Shape FF[2];
1337       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1338       while ( fIt->more())
1339       {
1340         const TopoDS_Shape* f = fIt->next();
1341         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1342           FF[ int( !FF[0].IsNull()) ] = *f;
1343       }
1344       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1345       // check presence of layers on them
1346       int ignore[2];
1347       for ( int j = 0; j < 2; ++j )
1348         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1349       if ( ignore[0] == ignore[1] )
1350         continue; // nothing interesting
1351       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1352       // check presence of layers on fWOL within an adjacent SOLID
1353       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1354       while ( const TopoDS_Shape* solid = sIt->next() )
1355         if ( !solid->IsSame( _sdVec[i]._solid ))
1356         {
1357           int iSolid = solids.FindIndex( *solid );
1358           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
1359           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1360           {
1361             _sdVec[i]._noShrinkFaces.insert( iFace );
1362             fWOL.Nullify();
1363           }
1364         }
1365       // add edge to maps
1366       if ( !fWOL.IsNull())
1367       {
1368         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1369         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1370       }
1371     }
1372   }
1373   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1374   // the algo of the SOLID sharing the FACE does not support it
1375   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1376   for ( size_t i = 0; i < _sdVec.size(); ++i )
1377   {
1378     TopTools_MapOfShape noShrinkVertices;
1379     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1380     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1381     {
1382       const TopoDS_Shape& fWOL = e2f->second;
1383       TGeomID           edgeID = e2f->first;
1384       bool notShrinkFace = false;
1385       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1386       while ( soIt->more())
1387       {
1388         const TopoDS_Shape* solid = soIt->next();
1389         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1390         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1391         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1392         notShrinkFace = true;
1393         for ( size_t j = 0; j < _sdVec.size(); ++j )
1394         {
1395           if ( _sdVec[j]._solid.IsSame( *solid ) )
1396             if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1397               notShrinkFace = false;
1398         }
1399       }
1400       if ( notShrinkFace )
1401       {
1402         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1403         for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1404           noShrinkVertices.Add( vExp.Current() );
1405       }
1406     }
1407     // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1408     // to the found not shrinked fWOL's
1409     e2f = _sdVec[i]._shrinkShape2Shape.begin();
1410     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1411     {
1412       TGeomID edgeID = e2f->first;
1413       TopoDS_Vertex VV[2];
1414       TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1415       if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1416       {
1417         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1418         _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1419       }
1420       else
1421       {
1422         e2f++;
1423       }
1424     }
1425   }
1426
1427   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1428
1429   for ( size_t i = 0; i < _sdVec.size(); ++i )
1430   {
1431     shapes.Clear();
1432     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1433     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1434     {
1435       const TopoDS_Shape& vertex = shapes(iV);
1436       // find faces WOL sharing the vertex
1437       vector< TopoDS_Shape > facesWOL;
1438       int totalNbFaces = 0;
1439       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1440       while ( fIt->more())
1441       {
1442         const TopoDS_Shape* f = fIt->next();
1443         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1444         {
1445           totalNbFaces++;
1446           const int fID = getMeshDS()->ShapeToIndex( *f );
1447           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1448                !_sdVec[i]._noShrinkFaces.count( fID ))
1449             facesWOL.push_back( *f );
1450         }
1451       }
1452       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1453         continue; // no layers at this vertex or no WOL
1454       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1455       switch ( facesWOL.size() )
1456       {
1457       case 1:
1458       {
1459         helper.SetSubShape( facesWOL[0] );
1460         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1461         {
1462           TopoDS_Shape seamEdge;
1463           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1464           while ( eIt->more() && seamEdge.IsNull() )
1465           {
1466             const TopoDS_Shape* e = eIt->next();
1467             if ( helper.IsRealSeam( *e ) )
1468               seamEdge = *e;
1469           }
1470           if ( !seamEdge.IsNull() )
1471           {
1472             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1473             break;
1474           }
1475         }
1476         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1477         break;
1478       }
1479       case 2:
1480       {
1481         // find an edge shared by 2 faces
1482         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1483         while ( eIt->more())
1484         {
1485           const TopoDS_Shape* e = eIt->next();
1486           if ( helper.IsSubShape( *e, facesWOL[0]) &&
1487                helper.IsSubShape( *e, facesWOL[1]))
1488           {
1489             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1490           }
1491         }
1492         break;
1493       }
1494       default:
1495         return error("Not yet supported case", _sdVec[i]._index);
1496       }
1497     }
1498   }
1499
1500   // add FACEs of other SOLIDs to _ignoreFaceIds
1501   for ( size_t i = 0; i < _sdVec.size(); ++i )
1502   {
1503     shapes.Clear();
1504     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1505
1506     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1507     {
1508       if ( !shapes.Contains( exp.Current() ))
1509         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1510     }
1511   }
1512
1513   return true;
1514 }
1515
1516 //================================================================================
1517 /*!
1518  * \brief Create the inner surface of the viscous layer and prepare data for infation
1519  */
1520 //================================================================================
1521
1522 bool _ViscousBuilder::makeLayer(_SolidData& data)
1523 {
1524   // get all sub-shapes to make layers on
1525   set<TGeomID> subIds, faceIds;
1526   subIds = data._noShrinkFaces;
1527   TopExp_Explorer exp( data._solid, TopAbs_FACE );
1528   for ( ; exp.More(); exp.Next() )
1529     {
1530       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1531       if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1532         faceIds.insert( fSubM->GetId() );
1533       SMESH_subMeshIteratorPtr subIt =
1534         fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1535       while ( subIt->more() )
1536         subIds.insert( subIt->next()->GetId() );
1537     }
1538
1539   // make a map to find new nodes on sub-shapes shared with other SOLID
1540   map< TGeomID, TNode2Edge* >::iterator s2ne;
1541   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1542   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1543   {
1544     TGeomID shapeInd = s2s->first;
1545     for ( size_t i = 0; i < _sdVec.size(); ++i )
1546     {
1547       if ( _sdVec[i]._index == data._index ) continue;
1548       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1549       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1550            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1551       {
1552         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1553         break;
1554       }
1555     }
1556   }
1557
1558   // Create temporary faces and _LayerEdge's
1559
1560   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
1561
1562   data._stepSize = Precision::Infinite();
1563   data._stepSizeNodes[0] = 0;
1564
1565   SMESH_MesherHelper helper( *_mesh );
1566   helper.SetSubShape( data._solid );
1567   helper.SetElementsOnShape(true);
1568
1569   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1570   TNode2Edge::iterator n2e2;
1571
1572   // collect _LayerEdge's of shapes they are based on
1573   const int nbShapes = getMeshDS()->MaxShapeIndex();
1574   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1575
1576   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1577   {
1578     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1579     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1580
1581     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1582     SMESH_ProxyMesh::SubMesh* proxySub =
1583       data._proxyMesh->getFaceSubM( F, /*create=*/true);
1584
1585     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1586     while ( eIt->more() )
1587     {
1588       const SMDS_MeshElement* face = eIt->next();
1589       newNodes.resize( face->NbCornerNodes() );
1590       double faceMaxCosin = -1;
1591       for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1592       {
1593         const SMDS_MeshNode* n = face->GetNode(i);
1594         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1595         if ( !(*n2e).second )
1596         {
1597           // add a _LayerEdge
1598           _LayerEdge* edge = new _LayerEdge();
1599           n2e->second = edge;
1600           edge->_nodes.push_back( n );
1601           const int shapeID = n->getshapeId();
1602           edgesByGeom[ shapeID ].push_back( edge );
1603
1604           SMESH_TNodeXYZ xyz( n );
1605
1606           // set edge data or find already refined _LayerEdge and get data from it
1607           if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1608                ( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() &&
1609                ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1610           {
1611             _LayerEdge* foundEdge = (*n2e2).second;
1612             gp_XYZ        lastPos = edge->Copy( *foundEdge, helper );
1613             foundEdge->_pos.push_back( lastPos );
1614             // location of the last node is modified and we restore it by foundEdge->_pos.back()
1615             const_cast< SMDS_MeshNode* >
1616               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
1617           }
1618           else
1619           {
1620             edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
1621             if ( !setEdgeData( *edge, subIds, helper, data ))
1622               return false;
1623           }
1624           dumpMove(edge->_nodes.back());
1625           if ( edge->_cosin > 0.01 )
1626           {
1627             if ( edge->_cosin > faceMaxCosin )
1628               faceMaxCosin = edge->_cosin;
1629           }
1630         }
1631         newNodes[ i ] = n2e->second->_nodes.back();
1632       }
1633       // create a temporary face
1634       const SMDS_MeshElement* newFace =
1635         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
1636       proxySub->AddElement( newFace );
1637
1638       // compute inflation step size by min size of element on a convex surface
1639       if ( faceMaxCosin > theMinSmoothCosin )
1640         limitStepSize( data, face, faceMaxCosin );
1641     } // loop on 2D elements on a FACE
1642   } // loop on FACEs of a SOLID
1643
1644   data._epsilon = 1e-7;
1645   if ( data._stepSize < 1. )
1646     data._epsilon *= data._stepSize;
1647
1648   // Put _LayerEdge's into the vector data._edges
1649   if ( !sortEdges( data, edgesByGeom ))
1650     return false;
1651
1652   // limit data._stepSize depending on surface curvature and fill data._convexFaces
1653   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
1654
1655   // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1656   TNode2Edge::iterator n2e;
1657   for ( size_t i = 0; i < data._edges.size(); ++i )
1658   {
1659     if ( data._edges[i]->IsOnEdge())
1660       for ( int j = 0; j < 2; ++j )
1661       {
1662         if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1663           break; // _LayerEdge is shared by two _SolidData's
1664         const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1665         if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1666           return error("_LayerEdge not found by src node", data._index);
1667         n = (*n2e).second->_nodes.back();
1668         data._edges[i]->_2neibors->_edges[j] = n2e->second;
1669       }
1670     //else
1671     for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1672     {
1673       _Simplex& s = data._edges[i]->_simplices[j];
1674       s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1675       s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1676     }
1677   }
1678
1679   dumpFunctionEnd();
1680   return true;
1681 }
1682
1683 //================================================================================
1684 /*!
1685  * \brief Compute inflation step size by min size of element on a convex surface
1686  */
1687 //================================================================================
1688
1689 void _ViscousBuilder::limitStepSize( _SolidData&             data,
1690                                      const SMDS_MeshElement* face,
1691                                      const double            cosin)
1692 {
1693   int iN = 0;
1694   double minSize = 10 * data._stepSize;
1695   const int nbNodes = face->NbCornerNodes();
1696   for ( int i = 0; i < nbNodes; ++i )
1697   {
1698     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1699     const SMDS_MeshNode* curN = face->GetNode( i );
1700     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1701          curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1702     {
1703       double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1704       if ( dist < minSize )
1705         minSize = dist, iN = i;
1706     }
1707   }
1708   double newStep = 0.8 * minSize / cosin;
1709   if ( newStep < data._stepSize )
1710   {
1711     data._stepSize = newStep;
1712     data._stepSizeCoeff = 0.8 / cosin;
1713     data._stepSizeNodes[0] = face->GetNode( iN );
1714     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1715   }
1716 }
1717
1718 //================================================================================
1719 /*!
1720  * \brief Compute inflation step size by min size of element on a convex surface
1721  */
1722 //================================================================================
1723
1724 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1725 {
1726   if ( minSize < data._stepSize )
1727   {
1728     data._stepSize = minSize;
1729     if ( data._stepSizeNodes[0] )
1730     {
1731       double dist =
1732         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1733       data._stepSizeCoeff = data._stepSize / dist;
1734     }
1735   }
1736 }
1737
1738 //================================================================================
1739 /*!
1740  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
1741  */
1742 //================================================================================
1743
1744 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
1745 {
1746   const int nbTestPnt = 5; // on a FACE sub-shape
1747   const double minCurvature = 0.9 / data._hyp->GetTotalThickness();
1748
1749   BRepLProp_SLProps surfProp( 2, 1e-6 );
1750   SMESH_MesherHelper helper( *_mesh );
1751
1752   data._convexFaces.clear();
1753
1754   TopExp_Explorer face( data._solid, TopAbs_FACE );
1755   for ( ; face.More(); face.Next() )
1756   {
1757     const TopoDS_Face& F = TopoDS::Face( face.Current() );
1758     BRepAdaptor_Surface surface( F, false );
1759     surfProp.SetSurface( surface );
1760
1761     bool isTooCurved = false;
1762     int iBeg, iEnd;
1763
1764     _ConvexFace cnvFace;
1765     SMESH_subMesh *            sm = _mesh->GetSubMesh( F );
1766     const TGeomID          faceID = sm->GetId();
1767     if ( data._ignoreFaceIds.count( faceID )) continue;
1768     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
1769     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1770     while ( smIt->more() )
1771     {
1772       sm = smIt->next();
1773       const TGeomID subID = sm->GetId();
1774       // find _LayerEdge's of a sub-shape
1775       size_t edgesEnd;
1776       if ( data.GetShapeEdges( subID, edgesEnd, &iBeg, &iEnd ))
1777         cnvFace._subIdToEdgeEnd.insert( make_pair( subID, edgesEnd ));
1778       else
1779         continue;
1780       // check concavity and curvature and limit data._stepSize
1781       int nbLEdges = iEnd - iBeg;
1782       int step = Max( 1, nbLEdges / nbTestPnt );
1783       for ( ; iBeg < iEnd; iBeg += step )
1784       {
1785         gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
1786         surfProp.SetParameters( uv.X(), uv.Y() );
1787         if ( !surfProp.IsCurvatureDefined() )
1788           continue;
1789         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
1790         {
1791           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
1792           isTooCurved = true;
1793         }
1794         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
1795         {
1796           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
1797           isTooCurved = true;
1798         }
1799       }
1800     } // loop on sub-shapes of the FACE
1801
1802     if ( !isTooCurved ) continue;
1803
1804     _ConvexFace & convFace =
1805       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
1806
1807     convFace._face = F;
1808     convFace._normalsFixed = false;
1809
1810     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
1811     // prism distortion.
1812     map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
1813     if ( id2end != convFace._subIdToEdgeEnd.end() )
1814     {
1815       // there are _LayerEdge's on the FACE it-self;
1816       // select _LayerEdge's near EDGEs
1817       data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
1818       for ( ; iBeg < iEnd; ++iBeg )
1819       {
1820         _LayerEdge* ledge = data._edges[ iBeg ];
1821         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
1822           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
1823           {
1824             convFace._simplexTestEdges.push_back( ledge );
1825             break;
1826           }
1827       }
1828     }
1829     else
1830     {
1831       // where there are no _LayerEdge's on a _ConvexFace,
1832       // as e.g. on a fillet surface with no internal nodes - issue 22580,
1833       // so that collision of viscous internal faces is not detected by check of
1834       // intersection of _LayerEdge's with the viscous internal faces.
1835
1836       set< const SMDS_MeshNode* > usedNodes;
1837
1838       // look for _LayerEdge's with null _sWOL
1839       map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
1840       for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
1841       {
1842         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
1843         if ( iBeg >= iEnd || !data._edges[ iBeg ]->_sWOL.IsNull() )
1844           continue;
1845         for ( ; iBeg < iEnd; ++iBeg )
1846         {
1847           _LayerEdge* ledge = data._edges[ iBeg ];
1848           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1849           if ( !usedNodes.insert( srcNode ).second ) continue;
1850
1851           getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1852           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1853           {
1854             usedNodes.insert( ledge->_simplices[i]._nPrev );
1855             usedNodes.insert( ledge->_simplices[i]._nNext );
1856           }
1857           convFace._simplexTestEdges.push_back( ledge );
1858         }
1859       }
1860     }
1861   } // loop on FACEs of data._solid
1862 }
1863
1864 //================================================================================
1865 /*!
1866  * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1867  */
1868 //================================================================================
1869
1870 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
1871                                  vector< vector<_LayerEdge*> >& edgesByGeom)
1872 {
1873   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1874   // boundry inclined at a sharp angle to the shape
1875
1876   list< TGeomID > shapesToSmooth;
1877   
1878   SMESH_MesherHelper helper( *_mesh );
1879   bool ok = true;
1880
1881   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1882   {
1883     vector<_LayerEdge*>& eS = edgesByGeom[iS];
1884     if ( eS.empty() ) continue;
1885     const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1886     bool needSmooth = false;
1887     switch ( S.ShapeType() )
1888     {
1889     case TopAbs_EDGE: {
1890
1891       bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1892       for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1893       {
1894         TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1895         vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1896         if ( eV.empty() ) continue;
1897         double cosin = eV[0]->_cosin;
1898         bool badCosin =
1899           ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1900         if ( badCosin )
1901         {
1902           gp_Vec dir1, dir2;
1903           if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1904             dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1905           else
1906             dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1907                                eV[0]->_nodes[0], helper, ok);
1908           dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1909           double angle = dir1.Angle( dir2 );
1910           cosin = cos( angle );
1911         }
1912         needSmooth = ( cosin > theMinSmoothCosin );
1913       }
1914       break;
1915     }
1916     case TopAbs_FACE: {
1917
1918       for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1919       {
1920         TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1921         vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1922         if ( eE.empty() ) continue;
1923         if ( eE[0]->_sWOL.IsNull() )
1924         {
1925           for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1926             needSmooth = ( eE[i]->_cosin > theMinSmoothCosin );
1927         }
1928         else
1929         {
1930           const TopoDS_Face& F1 = TopoDS::Face( S );
1931           const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1932           const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
1933           for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1934           {
1935             gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1936             gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1937             double angle = dir1.Angle( dir2 );
1938             double cosin = cos( angle );
1939             needSmooth = ( cosin > theMinSmoothCosin );
1940           }
1941         }
1942       }
1943       break;
1944     }
1945     case TopAbs_VERTEX:
1946       continue;
1947     default:;
1948     }
1949     if ( needSmooth )
1950     {
1951       if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1952       else                                shapesToSmooth.push_back ( iS );
1953     }
1954
1955   } // loop on edgesByGeom
1956
1957   data._edges.reserve( data._n2eMap.size() );
1958   data._endEdgeOnShape.clear();
1959
1960   // first we put _LayerEdge's on shapes to smooth
1961   data._nbShapesToSmooth = 0;
1962   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1963   for ( ; gIt != shapesToSmooth.end(); ++gIt )
1964   {
1965     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1966     if ( eVec.empty() ) continue;
1967     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1968     data._endEdgeOnShape.push_back( data._edges.size() );
1969     data._nbShapesToSmooth++;
1970     eVec.clear();
1971   }
1972
1973   // then the rest _LayerEdge's
1974   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1975   {
1976     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1977     if ( eVec.empty() ) continue;
1978     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1979     data._endEdgeOnShape.push_back( data._edges.size() );
1980     //eVec.clear();
1981   }
1982
1983   return ok;
1984 }
1985
1986 //================================================================================
1987 /*!
1988  * \brief Set data of _LayerEdge needed for smoothing
1989  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1990  */
1991 //================================================================================
1992
1993 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
1994                                   const set<TGeomID>& subIds,
1995                                   SMESH_MesherHelper& helper,
1996                                   _SolidData&         data)
1997 {
1998   SMESH_MeshEditor editor(_mesh);
1999
2000   const SMDS_MeshNode* node = edge._nodes[0]; // source node
2001   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
2002
2003   edge._len = 0;
2004   edge._2neibors = 0;
2005   edge._curvature = 0;
2006
2007   // --------------------------
2008   // Compute _normal and _cosin
2009   // --------------------------
2010
2011   edge._cosin = 0;
2012   edge._normal.SetCoord(0,0,0);
2013
2014   int totalNbFaces = 0;
2015   gp_Pnt p;
2016   gp_Vec du, dv, geomNorm;
2017   bool normOK = true;
2018
2019   TGeomID shapeInd = node->getshapeId();
2020   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
2021   bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
2022   TopoDS_Shape vertEdge;
2023
2024   if ( onShrinkShape ) // one of faces the node is on has no layers
2025   {
2026     vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
2027     if ( s2s->second.ShapeType() == TopAbs_EDGE )
2028     {
2029       // inflate from VERTEX along EDGE
2030       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
2031     }
2032     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
2033     {
2034       // inflate from VERTEX along FACE
2035       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
2036                                  node, helper, normOK, &edge._cosin);
2037     }
2038     else
2039     {
2040       // inflate from EDGE along FACE
2041       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
2042                                  node, helper, normOK);
2043     }
2044   }
2045   else // layers are on all faces of SOLID the node is on
2046   {
2047     // find indices of geom faces the node lies on
2048     set<TGeomID> faceIds;
2049     if  ( posType == SMDS_TOP_FACE )
2050     {
2051       faceIds.insert( node->getshapeId() );
2052     }
2053     else
2054     {
2055       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2056       while ( fIt->more() )
2057         faceIds.insert( editor.FindShape(fIt->next()));
2058     }
2059
2060     set<TGeomID>::iterator id = faceIds.begin();
2061     TopoDS_Face F;
2062     std::pair< TGeomID, gp_XYZ > id2Norm[20];
2063     for ( ; id != faceIds.end(); ++id )
2064     {
2065       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2066       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2067         continue;
2068       F = TopoDS::Face( s );
2069       geomNorm = getFaceNormal( node, F, helper, normOK );
2070       if ( !normOK ) continue;
2071
2072       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2073         geomNorm.Reverse();
2074       id2Norm[ totalNbFaces ].first  = *id;
2075       id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
2076       totalNbFaces++;
2077       edge._normal += geomNorm.XYZ();
2078     }
2079     if ( totalNbFaces == 0 )
2080       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2081
2082     if ( normOK && edge._normal.Modulus() < 1e-3 && totalNbFaces > 1 )
2083     {
2084       // opposite normals, re-get normals at shifted positions (IPAL 52426)
2085       edge._normal.SetCoord( 0,0,0 );
2086       for ( int i = 0; i < totalNbFaces; ++i )
2087       {
2088         const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[i].first ));
2089         geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2090         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2091           geomNorm.Reverse();
2092         if ( normOK )
2093           id2Norm[ i ].second = geomNorm.XYZ();
2094         edge._normal += id2Norm[ i ].second;
2095       }
2096     }
2097
2098     if ( totalNbFaces < 3 )
2099     {
2100       //edge._normal /= totalNbFaces;
2101     }
2102     else
2103     {
2104       edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
2105     }
2106
2107     switch ( posType )
2108     {
2109     case SMDS_TOP_FACE:
2110       edge._cosin = 0; break;
2111
2112     case SMDS_TOP_EDGE: {
2113       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
2114       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2115       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2116       edge._cosin = cos( angle );
2117       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2118       break;
2119     }
2120     case SMDS_TOP_VERTEX: {
2121       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2122       gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2123       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2124       edge._cosin = cos( angle );
2125       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2126       break;
2127     }
2128     default:
2129       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2130     }
2131   } // case _sWOL.IsNull()
2132
2133   double normSize = edge._normal.SquareModulus();
2134   if ( normSize < numeric_limits<double>::min() )
2135     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2136
2137   edge._normal /= sqrt( normSize );
2138
2139   // TODO: if ( !normOK ) then get normal by mesh faces
2140
2141   // Set the rest data
2142   // --------------------
2143   if ( onShrinkShape )
2144   {
2145     edge._sWOL = (*s2s).second;
2146
2147     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2148     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2149       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2150
2151     // set initial position which is parameters on _sWOL in this case
2152     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2153     {
2154       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2155       edge._pos.push_back( gp_XYZ( u, 0, 0));
2156       getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2157     }
2158     else // TopAbs_FACE
2159     {
2160       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2161       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2162       getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2163     }
2164   }
2165   else
2166   {
2167     edge._pos.push_back( SMESH_TNodeXYZ( node ));
2168
2169     if ( posType == SMDS_TOP_FACE )
2170     {
2171       getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2172       double avgNormProj = 0, avgLen = 0;
2173       for ( size_t i = 0; i < edge._simplices.size(); ++i )
2174       {
2175         gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2176         avgNormProj += edge._normal * vec;
2177         avgLen += vec.Modulus();
2178       }
2179       avgNormProj /= edge._simplices.size();
2180       avgLen /= edge._simplices.size();
2181       edge._curvature = _Curvature::New( avgNormProj, avgLen );
2182     }
2183   }
2184
2185   // Set neighbour nodes for a _LayerEdge based on EDGE
2186
2187   if ( posType == SMDS_TOP_EDGE /*||
2188        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2189   {
2190     edge._2neibors = new _2NearEdges;
2191     // target node instead of source ones will be set later
2192     if ( ! findNeiborsOnEdge( &edge,
2193                               edge._2neibors->_nodes[0],
2194                               edge._2neibors->_nodes[1],
2195                               data))
2196       return false;
2197     edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2198                              edge._2neibors->_nodes[1],
2199                              helper);
2200   }
2201
2202   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2203
2204   return true;
2205 }
2206
2207 //================================================================================
2208 /*!
2209  * \brief Return normal to a FACE at a node
2210  *  \param [in] n - node
2211  *  \param [in] face - FACE
2212  *  \param [in] helper - helper
2213  *  \param [out] isOK - true or false
2214  *  \param [in] shiftInside - to find normal at a position shifted inside the face
2215  *  \return gp_XYZ - normal
2216  */
2217 //================================================================================
2218
2219 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
2220                                       const TopoDS_Face&   face,
2221                                       SMESH_MesherHelper&  helper,
2222                                       bool&                isOK,
2223                                       bool                 shiftInside)
2224 {
2225   gp_XY uv;
2226   if ( shiftInside )
2227   {
2228     // get a shifted position
2229     gp_Pnt p = SMESH_TNodeXYZ( node );
2230     gp_XYZ shift( 0,0,0 );
2231     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
2232     switch ( S.ShapeType() ) {
2233     case TopAbs_VERTEX:
2234     {
2235       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
2236       break;
2237     }
2238     case TopAbs_EDGE:
2239     {
2240       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
2241       break;
2242     }
2243     default:
2244       isOK = false;
2245     }
2246     if ( isOK )
2247       shift.Normalize();
2248     p.Translate( shift * 1e-5 );
2249
2250     TopLoc_Location loc;
2251     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
2252
2253     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
2254     
2255     projector.Perform( p );
2256     if ( !projector.IsDone() || projector.NbPoints() < 1 )
2257     {
2258       isOK = false;
2259       return p.XYZ();
2260     }
2261     Quantity_Parameter U,V;
2262     projector.LowerDistanceParameters(U,V);
2263     uv.SetCoord( U,V );
2264   }
2265   else
2266   {
2267     uv = helper.GetNodeUV( face, node, 0, &isOK );
2268   }
2269
2270   gp_Dir normal;
2271   isOK = false;
2272
2273   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
2274   if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
2275   {
2276     normal;
2277     isOK = true;
2278   }
2279   else // hard singularity
2280   {
2281     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
2282
2283     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2284     while ( fIt->more() )
2285     {
2286       const SMDS_MeshElement* f = fIt->next();
2287       if ( f->getshapeId() == faceID )
2288       {
2289         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
2290         if ( isOK )
2291         {
2292           if ( helper.IsReversedSubMesh( face ))
2293             normal.Reverse();
2294           break;
2295         }
2296       }
2297     }
2298   }
2299   return normal.XYZ();
2300 }
2301
2302 //================================================================================
2303 /*!
2304  * \brief Return a normal at a node weighted with angles taken by FACEs
2305  *  \param [in] n - the node
2306  *  \param [in] fId2Normal - FACE ids and normals
2307  *  \param [in] nbFaces - nb of FACEs meeting at the node
2308  *  \return gp_XYZ - computed normal
2309  */
2310 //================================================================================
2311
2312 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
2313                                            std::pair< TGeomID, gp_XYZ > fId2Normal[],
2314                                            const int                    nbFaces )
2315 {
2316   gp_XYZ resNorm(0,0,0);
2317   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2318   if ( V.ShapeType() != TopAbs_VERTEX )
2319   {
2320     for ( int i = 0; i < nbFaces; ++i )
2321       resNorm += fId2Normal[i].second / nbFaces ;
2322     return resNorm;
2323   }
2324
2325   double angles[30];
2326   for ( int i = 0; i < nbFaces; ++i )
2327   {
2328     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2329
2330     // look for two EDGEs shared by F and other FACEs within fId2Normal
2331     TopoDS_Edge ee[2];
2332     int nbE = 0;
2333     PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2334     while ( const TopoDS_Shape* E = eIt->next() )
2335     {
2336       if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2337         continue;
2338       bool isSharedEdge = false;
2339       for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2340       {
2341         if ( i == j ) continue;
2342         const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2343         isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2344       }
2345       if ( !isSharedEdge )
2346         continue;
2347       ee[ nbE ] = TopoDS::Edge( *E );
2348       ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2349       if ( ++nbE == 2 )
2350         break;
2351     }
2352
2353     // get an angle between the two EDGEs
2354     angles[i] = 0;
2355     if ( nbE < 1 ) continue;
2356     if ( nbE == 1 )
2357     {
2358       ee[ 1 ] == ee[ 0 ];
2359     }
2360     else
2361     {
2362       TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2363       TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2364       if ( !v10.IsSame( v01 ))
2365         std::swap( ee[0], ee[1] );
2366     }
2367     angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2368   }
2369
2370   // compute a weighted normal
2371   double sumAngle = 0;
2372   for ( int i = 0; i < nbFaces; ++i )
2373   {
2374     angles[i] = ( angles[i] > 2*M_PI )  ?  0  :  M_PI - angles[i];
2375     sumAngle += angles[i];
2376   }
2377   for ( int i = 0; i < nbFaces; ++i )
2378     resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2379
2380   return resNorm;
2381 }
2382
2383 //================================================================================
2384 /*!
2385  * \brief Find 2 neigbor nodes of a node on EDGE
2386  */
2387 //================================================================================
2388
2389 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
2390                                         const SMDS_MeshNode*& n1,
2391                                         const SMDS_MeshNode*& n2,
2392                                         _SolidData&           data)
2393 {
2394   const SMDS_MeshNode* node = edge->_nodes[0];
2395   const int shapeInd = node->getshapeId();
2396   SMESHDS_SubMesh* edgeSM = 0;
2397   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2398   {
2399     
2400     edgeSM = getMeshDS()->MeshElements( shapeInd );
2401     if ( !edgeSM || edgeSM->NbElements() == 0 )
2402       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2403   }
2404   int iN = 0;
2405   n2 = 0;
2406   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2407   while ( eIt->more() && !n2 )
2408   {
2409     const SMDS_MeshElement* e = eIt->next();
2410     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
2411     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2412     if ( edgeSM )
2413     {
2414       if (!edgeSM->Contains(e)) continue;
2415     }
2416     else
2417     {
2418       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2419       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2420     }
2421     ( iN++ ? n2 : n1 ) = nNeibor;
2422   }
2423   if ( !n2 )
2424     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2425   return true;
2426 }
2427
2428 //================================================================================
2429 /*!
2430  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2431  */
2432 //================================================================================
2433
2434 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2435                                      const SMDS_MeshNode* n2,
2436                                      SMESH_MesherHelper&  helper)
2437 {
2438   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2439     return;
2440
2441   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2442   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2443   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2444
2445   // Set _curvature
2446
2447   double sumLen = vec1.Modulus() + vec2.Modulus();
2448   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2449   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2450   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2451   double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2452   if ( _curvature ) delete _curvature;
2453   _curvature = _Curvature::New( avgNormProj, avgLen );
2454   // if ( _curvature )
2455   //   debugMsg( _nodes[0]->GetID()
2456   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2457   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2458   //             << _curvature->lenDelta(0) );
2459
2460   // Set _plnNorm
2461
2462   if ( _sWOL.IsNull() )
2463   {
2464     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2465     gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2466     gp_XYZ plnNorm = dirE ^ _normal;
2467     double proj0 = plnNorm * vec1;
2468     double proj1 = plnNorm * vec2;
2469     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2470     {
2471       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2472       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2473     }
2474   }
2475 }
2476
2477 //================================================================================
2478 /*!
2479  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2480  * this and other _LayerEdge's are inflated along a FACE or an EDGE
2481  */
2482 //================================================================================
2483
2484 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2485 {
2486   _nodes     = other._nodes;
2487   _normal    = other._normal;
2488   _len       = 0;
2489   _lenFactor = other._lenFactor;
2490   _cosin     = other._cosin;
2491   _sWOL      = other._sWOL;
2492   _2neibors  = other._2neibors;
2493   _curvature = 0; std::swap( _curvature, other._curvature );
2494   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
2495
2496   gp_XYZ lastPos( 0,0,0 );
2497   if ( _sWOL.ShapeType() == TopAbs_EDGE )
2498   {
2499     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2500     _pos.push_back( gp_XYZ( u, 0, 0));
2501
2502     u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
2503     lastPos.SetX( u );
2504   }
2505   else // TopAbs_FACE
2506   {
2507     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2508     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2509
2510     uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
2511     lastPos.SetX( uv.X() );
2512     lastPos.SetY( uv.Y() );
2513   }
2514   return lastPos;
2515 }
2516
2517 //================================================================================
2518 /*!
2519  * \brief Set _cosin and _lenFactor
2520  */
2521 //================================================================================
2522
2523 void _LayerEdge::SetCosin( double cosin )
2524 {
2525   _cosin = cosin;
2526   cosin = Abs( _cosin );
2527   _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ?  1./sqrt(1-cosin*cosin) : 1.0;
2528 }
2529
2530 //================================================================================
2531 /*!
2532  * \brief Fills a vector<_Simplex > 
2533  */
2534 //================================================================================
2535
2536 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2537                                     vector<_Simplex>&    simplices,
2538                                     const set<TGeomID>&  ingnoreShapes,
2539                                     const _SolidData*    dataToCheckOri,
2540                                     const bool           toSort)
2541 {
2542   simplices.clear();
2543   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2544   while ( fIt->more() )
2545   {
2546     const SMDS_MeshElement* f = fIt->next();
2547     const TGeomID    shapeInd = f->getshapeId();
2548     if ( ingnoreShapes.count( shapeInd )) continue;
2549     const int nbNodes = f->NbCornerNodes();
2550     const int  srcInd = f->GetNodeIndex( node );
2551     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2552     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2553     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2554     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2555       std::swap( nPrev, nNext );
2556     simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2557   }
2558
2559   if ( toSort )
2560   {
2561     vector<_Simplex> sortedSimplices( simplices.size() );
2562     sortedSimplices[0] = simplices[0];
2563     int nbFound = 0;
2564     for ( size_t i = 1; i < simplices.size(); ++i )
2565     {
2566       for ( size_t j = 1; j < simplices.size(); ++j )
2567         if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2568         {
2569           sortedSimplices[i] = simplices[j];
2570           nbFound++;
2571           break;
2572         }
2573     }
2574     if ( nbFound == simplices.size() - 1 )
2575       simplices.swap( sortedSimplices );
2576   }
2577 }
2578
2579 //================================================================================
2580 /*!
2581  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2582  */
2583 //================================================================================
2584
2585 void _ViscousBuilder::makeGroupOfLE()
2586 {
2587 #ifdef _DEBUG_
2588   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2589   {
2590     if ( _sdVec[i]._edges.empty() ) continue;
2591
2592     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2593     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2594     {
2595       _LayerEdge* le = _sdVec[i]._edges[j];
2596       for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2597         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2598                 << ", " << le->_nodes[iN]->GetID() <<"])");
2599     }
2600     dumpFunctionEnd();
2601
2602     dumpFunction( SMESH_Comment("makeNormals") << i );
2603     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2604     {
2605       _LayerEdge& edge = *_sdVec[i]._edges[j];
2606       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2607       nXYZ += edge._normal * _sdVec[i]._stepSize;
2608       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2609               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2610     }
2611     dumpFunctionEnd();
2612
2613     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2614     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2615     for ( ; fExp.More(); fExp.Next() )
2616     {
2617       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2618       {
2619         SMDS_ElemIteratorPtr fIt = sm->GetElements();
2620         while ( fIt->more())
2621         {
2622           const SMDS_MeshElement* e = fIt->next();
2623           SMESH_Comment cmd("mesh.AddFace([");
2624           for ( int j=0; j < e->NbCornerNodes(); ++j )
2625             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2626           dumpCmd( cmd );
2627         }
2628       }
2629     }
2630     dumpFunctionEnd();
2631   }
2632 #endif
2633 }
2634
2635 //================================================================================
2636 /*!
2637  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2638  */
2639 //================================================================================
2640
2641 bool _ViscousBuilder::inflate(_SolidData& data)
2642 {
2643   SMESH_MesherHelper helper( *_mesh );
2644
2645   // Limit inflation step size by geometry size found by itersecting
2646   // normals of _LayerEdge's with mesh faces
2647   double geomSize = Precision::Infinite(), intersecDist;
2648   auto_ptr<SMESH_ElementSearcher> searcher
2649     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2650                                            data._proxyMesh->GetFaces( data._solid )) );
2651   for ( size_t i = 0; i < data._edges.size(); ++i )
2652   {
2653     if ( data._edges[i]->IsOnEdge() ) continue;
2654     data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2655     if ( geomSize > intersecDist && intersecDist > 0 )
2656       geomSize = intersecDist;
2657   }
2658   if ( data._stepSize > 0.3 * geomSize )
2659     limitStepSize( data, 0.3 * geomSize );
2660
2661   const double tgtThick = data._hyp->GetTotalThickness();
2662   if ( data._stepSize > tgtThick )
2663     limitStepSize( data, tgtThick );
2664
2665   if ( data._stepSize < 1. )
2666     data._epsilon = data._stepSize * 1e-7;
2667
2668   debugMsg( "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize );
2669
2670   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2671   int nbSteps = 0, nbRepeats = 0;
2672   while ( 1.01 * avgThick < tgtThick )
2673   {
2674     // new target length
2675     curThick += data._stepSize;
2676     if ( curThick > tgtThick )
2677     {
2678       curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2679       nbRepeats++;
2680     }
2681
2682     // Elongate _LayerEdge's
2683     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2684     for ( size_t i = 0; i < data._edges.size(); ++i )
2685     {
2686       data._edges[i]->SetNewLength( curThick, helper );
2687     }
2688     dumpFunctionEnd();
2689
2690     if ( !updateNormals( data, helper, nbSteps ))
2691       return false;
2692
2693     // Improve and check quality
2694     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2695     {
2696       if ( nbSteps > 0 )
2697       {
2698         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2699         for ( size_t i = 0; i < data._edges.size(); ++i )
2700         {
2701           data._edges[i]->InvalidateStep( nbSteps+1 );
2702         }
2703         dumpFunctionEnd();
2704       }
2705       break; // no more inflating possible
2706     }
2707     nbSteps++;
2708
2709     // Evaluate achieved thickness
2710     avgThick = 0;
2711     for ( size_t i = 0; i < data._edges.size(); ++i )
2712       avgThick += data._edges[i]->_len;
2713     avgThick /= data._edges.size();
2714     debugMsg( "-- Thickness " << avgThick << " reached" );
2715
2716     if ( distToIntersection < avgThick*1.5 )
2717     {
2718       debugMsg( "-- Stop inflation since "
2719                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2720                 << avgThick << " ) * 1.5" );
2721       break;
2722     }
2723     // new step size
2724     limitStepSize( data, 0.25 * distToIntersection );
2725     if ( data._stepSizeNodes[0] )
2726       data._stepSize = data._stepSizeCoeff *
2727         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2728
2729   } // while ( 1.01 * avgThick < tgtThick )
2730
2731   if (nbSteps == 0 )
2732     return error("failed at the very first inflation step", data._index);
2733
2734   if ( 1.01 * avgThick < tgtThick )
2735     if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( data._index ))
2736     {
2737       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2738       if ( !smError || smError->IsOK() )
2739         smError.reset
2740           ( new SMESH_ComputeError (COMPERR_WARNING,
2741                                     SMESH_Comment("Thickness ") << tgtThick <<
2742                                     " of viscous layers not reached,"
2743                                     " average reached thickness is " << avgThick ));
2744     }
2745
2746   return true;
2747 }
2748
2749 //================================================================================
2750 /*!
2751  * \brief Improve quality of layer inner surface and check intersection
2752  */
2753 //================================================================================
2754
2755 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2756                                      const int   nbSteps,
2757                                      double &    distToIntersection)
2758 {
2759   if ( data._nbShapesToSmooth == 0 )
2760     return true; // no shapes needing smoothing
2761
2762   bool moved, improved;
2763
2764   SMESH_MesherHelper helper(*_mesh);
2765   Handle(Geom_Surface) surface;
2766   TopoDS_Face F;
2767
2768   int iBeg, iEnd = 0;
2769   for ( int iS = 0; iS < data._nbShapesToSmooth; ++iS )
2770   {
2771     iBeg = iEnd;
2772     iEnd = data._endEdgeOnShape[ iS ];
2773
2774     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2775          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2776     {
2777       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2778         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2779         helper.SetSubShape( F );
2780         surface = BRep_Tool::Surface( F );
2781       }
2782     }
2783     else
2784     {
2785       F.Nullify(); surface.Nullify();
2786     }
2787     TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2788
2789     if ( data._edges[ iBeg ]->IsOnEdge() )
2790     { 
2791       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2792
2793       // try a simple solution on an analytic EDGE
2794       if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2795       {
2796         // smooth on EDGE's
2797         int step = 0;
2798         do {
2799           moved = false;
2800           for ( int i = iBeg; i < iEnd; ++i )
2801           {
2802             moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2803           }
2804           dumpCmd( SMESH_Comment("# end step ")<<step);
2805         }
2806         while ( moved && step++ < 5 );
2807       }
2808       dumpFunctionEnd();
2809     }
2810     else
2811     {
2812       // smooth on FACE's
2813       int step = 0, stepLimit = 5, badNb = 0; moved = true;
2814       while (( ++step <= stepLimit && moved ) || improved )
2815       {
2816         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2817                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2818         int oldBadNb = badNb;
2819         badNb = 0;
2820         moved = false;
2821         for ( int i = iBeg; i < iEnd; ++i )
2822           moved |= data._edges[i]->Smooth(badNb);
2823         improved = ( badNb < oldBadNb );
2824
2825         // issue 22576. no bad faces but still there are intersections to fix
2826         if ( improved && badNb == 0 )
2827           stepLimit = step + 3;
2828
2829         dumpFunctionEnd();
2830       }
2831       if ( badNb > 0 )
2832       {
2833 #ifdef __myDEBUG
2834         for ( int i = iBeg; i < iEnd; ++i )
2835         {
2836           _LayerEdge* edge = data._edges[i];
2837           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2838           for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2839             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2840             {
2841               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2842                    << " "<< edge->_simplices[j]._nPrev->GetID()
2843                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2844               return false;
2845             }
2846         }
2847 #endif
2848         return false;
2849       }
2850     }
2851   } // loop on shapes to smooth
2852
2853   // Check orientation of simplices of _ConvexFace::_simplexTestEdges
2854   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
2855   for ( ; id2face != data._convexFaces.end(); ++id2face )
2856   {
2857     _ConvexFace & convFace = (*id2face).second;
2858     if ( !convFace._simplexTestEdges.empty() &&
2859          convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
2860       continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
2861
2862     if ( !convFace.CheckPrisms() )
2863       return false;
2864   }
2865
2866   // Check if the last segments of _LayerEdge intersects 2D elements;
2867   // checked elements are either temporary faces or faces on surfaces w/o the layers
2868
2869   auto_ptr<SMESH_ElementSearcher> searcher
2870     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2871                                            data._proxyMesh->GetFaces( data._solid )) );
2872
2873   distToIntersection = Precision::Infinite();
2874   double dist;
2875   const SMDS_MeshElement* intFace = 0;
2876   const SMDS_MeshElement* closestFace = 0;
2877   int iLE = 0;
2878   for ( size_t i = 0; i < data._edges.size(); ++i )
2879   {
2880     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2881       return false;
2882     if ( distToIntersection > dist )
2883     {
2884       // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
2885       // lying on this _ConvexFace
2886       if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
2887         if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
2888           continue;
2889
2890       distToIntersection = dist;
2891       iLE = i;
2892       closestFace = intFace;
2893     }
2894   }
2895 #ifdef __myDEBUG
2896   if ( closestFace )
2897   {
2898     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2899     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2900          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2901          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2902          << ") distance = " << distToIntersection<< endl;
2903   }
2904 #endif
2905
2906   return true;
2907 }
2908
2909 //================================================================================
2910 /*!
2911  * \brief Return a curve of the EDGE to be used for smoothing and arrange
2912  *        _LayerEdge's to be in a consequent order
2913  */
2914 //================================================================================
2915
2916 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
2917                                                const int             iFrom,
2918                                                const int             iTo,
2919                                                Handle(Geom_Surface)& surface,
2920                                                const TopoDS_Face&    F,
2921                                                SMESH_MesherHelper&   helper)
2922 {
2923   TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2924
2925   map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2926
2927   if ( i2curve == _edge2curve.end() )
2928   {
2929     // sort _LayerEdge's by position on the EDGE
2930     SortOnEdge( E, iFrom, iTo, helper );
2931
2932     SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2933
2934     TopLoc_Location loc; double f,l;
2935
2936     Handle(Geom_Line)   line;
2937     Handle(Geom_Circle) circle;
2938     bool isLine, isCirc;
2939     if ( F.IsNull() ) // 3D case
2940     {
2941       // check if the EDGE is a line
2942       Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2943       if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2944         curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2945
2946       line   = Handle(Geom_Line)::DownCast( curve );
2947       circle = Handle(Geom_Circle)::DownCast( curve );
2948       isLine = (!line.IsNull());
2949       isCirc = (!circle.IsNull());
2950
2951       if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2952       {
2953         Bnd_B3d bndBox;
2954         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2955         while ( nIt->more() )
2956           bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2957         gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2958
2959         SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2960         SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2961         const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2962         for ( int i = 0; i < 3 && !isLine; ++i )
2963           isLine = ( size.Coord( i+1 ) <= lineTol );
2964       }
2965       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2966       {
2967         // TODO
2968       }
2969     }
2970     else // 2D case
2971     {
2972       // check if the EDGE is a line
2973       Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2974       if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2975         curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2976
2977       Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
2978       Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2979       isLine = (!line2d.IsNull());
2980       isCirc = (!circle2d.IsNull());
2981
2982       if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2983       {
2984         Bnd_B2d bndBox;
2985         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2986         while ( nIt->more() )
2987           bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2988         gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2989
2990         const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2991         for ( int i = 0; i < 2 && !isLine; ++i )
2992           isLine = ( size.Coord( i+1 ) <= lineTol );
2993       }
2994       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2995       {
2996         // TODO
2997       }
2998       if ( isLine )
2999       {
3000         line = new Geom_Line( gp::OX() ); // only type does matter
3001       }
3002       else if ( isCirc )
3003       {
3004         gp_Pnt2d p = circle2d->Location();
3005         gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
3006         circle = new Geom_Circle( ax, 1.); // only center position does matter
3007       }
3008     }
3009
3010     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
3011     if ( isLine )
3012       res = line;
3013     else if ( isCirc )
3014       res = circle;
3015
3016     return res;
3017   }
3018   return i2curve->second;
3019 }
3020
3021 //================================================================================
3022 /*!
3023  * \brief Sort _LayerEdge's by a parameter on a given EDGE
3024  */
3025 //================================================================================
3026
3027 void _SolidData::SortOnEdge( const TopoDS_Edge&  E,
3028                              const int           iFrom,
3029                              const int           iTo,
3030                              SMESH_MesherHelper& helper)
3031 {
3032   map< double, _LayerEdge* > u2edge;
3033   for ( int i = iFrom; i < iTo; ++i )
3034     u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
3035
3036   ASSERT( u2edge.size() == iTo - iFrom );
3037   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
3038   for ( int i = iFrom; i < iTo; ++i, ++u2e )
3039     _edges[i] = u2e->second;
3040
3041   // set _2neibors according to the new order
3042   for ( int i = iFrom; i < iTo-1; ++i )
3043     if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
3044       _edges[i]->_2neibors->reverse();
3045   if ( u2edge.size() > 1 &&
3046        _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
3047     _edges[iTo-1]->_2neibors->reverse();
3048 }
3049
3050 //================================================================================
3051 /*!
3052  * \brief Return index corresponding to the shape in _endEdgeOnShape
3053  */
3054 //================================================================================
3055
3056 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
3057                                size_t &      edgesEnd,
3058                                int*          iBeg,
3059                                int*          iEnd ) const
3060 {
3061   int beg = 0, end = 0;
3062   for ( edgesEnd = 0; edgesEnd < _endEdgeOnShape.size(); ++edgesEnd )
3063   {
3064     end = _endEdgeOnShape[ edgesEnd ];
3065     TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
3066     if ( sID == shapeID )
3067     {
3068       if ( iBeg ) *iBeg = beg;
3069       if ( iEnd ) *iEnd = end;
3070       return true;
3071     }
3072     beg = end;
3073   }
3074   return false;
3075 }
3076
3077 //================================================================================
3078 /*!
3079  * \brief Add faces for smoothing
3080  */
3081 //================================================================================
3082
3083 void _SolidData::AddFacesToSmooth( const set< TGeomID >& faceIDs )
3084 {
3085   // convert faceIDs to indices in _endEdgeOnShape
3086   set< size_t > iEnds;
3087   size_t end;
3088   set< TGeomID >::const_iterator fId = faceIDs.begin();
3089   for ( ; fId != faceIDs.end(); ++fId )
3090     if ( GetShapeEdges( *fId, end ) && end >= _nbShapesToSmooth )
3091       iEnds.insert( end );
3092
3093   set< size_t >::iterator endsIt = iEnds.begin();
3094
3095   // "add" by move of _nbShapesToSmooth
3096   int nbFacesToAdd = faceIDs.size();
3097   while ( endsIt != iEnds.end() && *endsIt == _nbShapesToSmooth )
3098   {
3099     ++endsIt;
3100     ++_nbShapesToSmooth;
3101     --nbFacesToAdd;
3102   }
3103   if ( endsIt == iEnds.end() )
3104     return;
3105
3106   // Move _LayerEdge's on FACEs just after _nbShapesToSmooth
3107
3108   vector< _LayerEdge* > nonSmoothLE, smoothLE;
3109   size_t lastSmooth = *iEnds.rbegin();
3110   int iBeg, iEnd;
3111   for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
3112   {
3113     vector< _LayerEdge* > & edgesVec = iEnds.count(i) ? smoothLE : nonSmoothLE;
3114     iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
3115     iEnd = _endEdgeOnShape[ i ];
3116     edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd ); 
3117   }
3118
3119   iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
3120   std::copy( smoothLE.begin(),    smoothLE.end(),    &_edges[ iBeg ] );
3121   std::copy( nonSmoothLE.begin(), nonSmoothLE.end(), &_edges[ iBeg + smoothLE.size()]);
3122
3123   // update _endEdgeOnShape
3124   for ( size_t i = _nbShapesToSmooth; i < _endEdgeOnShape.size(); ++i )
3125   {
3126     TGeomID curShape = _edges[ iBeg ]->_nodes[0]->getshapeId();
3127     while ( ++iBeg < _edges.size() &&
3128             curShape == _edges[ iBeg ]->_nodes[0]->getshapeId() );
3129
3130     _endEdgeOnShape[ i ] = iBeg;
3131   }
3132
3133   _nbShapesToSmooth += nbFacesToAdd;
3134 }
3135
3136 //================================================================================
3137 /*!
3138  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
3139  */
3140 //================================================================================
3141
3142 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
3143                                           const int             iFrom,
3144                                           const int             iTo,
3145                                           Handle(Geom_Surface)& surface,
3146                                           const TopoDS_Face&    F,
3147                                           SMESH_MesherHelper&   helper)
3148 {
3149   TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
3150                                              helper.GetMeshDS());
3151   TopoDS_Edge E = TopoDS::Edge( S );
3152
3153   Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
3154   if ( curve.IsNull() ) return false;
3155
3156   // compute a relative length of segments
3157   vector< double > len( iTo-iFrom+1 );
3158   {
3159     double curLen, prevLen = len[0] = 1.0;
3160     for ( int i = iFrom; i < iTo; ++i )
3161     {
3162       curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
3163       len[i-iFrom+1] = len[i-iFrom] + curLen;
3164       prevLen = curLen;
3165     }
3166   }
3167
3168   if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
3169   {
3170     if ( F.IsNull() ) // 3D
3171     {
3172       SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
3173       SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
3174       for ( int i = iFrom; i < iTo; ++i )
3175       {
3176         double r = len[i-iFrom] / len.back();
3177         gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
3178         data._edges[i]->_pos.back() = newPos;
3179         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3180         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3181         dumpMove( tgtNode );
3182       }
3183     }
3184     else
3185     {
3186       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
3187       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
3188       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
3189            data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
3190       {
3191         int iPeriodic = helper.GetPeriodicIndex();
3192         if ( iPeriodic == 1 || iPeriodic == 2 )
3193         {
3194           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
3195           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
3196             std::swap( uv0, uv1 );
3197         }
3198       }
3199       const gp_XY rangeUV = uv1 - uv0;
3200       for ( int i = iFrom; i < iTo; ++i )
3201       {
3202         double r = len[i-iFrom] / len.back();
3203         gp_XY newUV = uv0 + r * rangeUV;
3204         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
3205
3206         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
3207         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3208         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3209         dumpMove( tgtNode );
3210
3211         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3212         pos->SetUParameter( newUV.X() );
3213         pos->SetVParameter( newUV.Y() );
3214       }
3215     }
3216     return true;
3217   }
3218
3219   if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
3220   {
3221     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
3222     gp_Pnt center3D = circle->Location();
3223
3224     if ( F.IsNull() ) // 3D
3225     {
3226       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
3227            data._edges[iTo-1]->_2neibors->_nodes[1] )
3228         return true; // closed EDGE - nothing to do
3229
3230       return false; // TODO ???
3231     }
3232     else // 2D
3233     {
3234       const gp_XY center( center3D.X(), center3D.Y() );
3235
3236       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
3237       gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
3238       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
3239       gp_Vec2d vec0( center, uv0 );
3240       gp_Vec2d vecM( center, uvM );
3241       gp_Vec2d vec1( center, uv1 );
3242       double uLast = vec0.Angle( vec1 ); // -PI - +PI
3243       double uMidl = vec0.Angle( vecM );
3244       if ( uLast * uMidl <= 0. )
3245         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
3246       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
3247
3248       gp_Ax2d   axis( center, vec0 );
3249       gp_Circ2d circ( axis, radius );
3250       for ( int i = iFrom; i < iTo; ++i )
3251       {
3252         double    newU = uLast * len[i-iFrom] / len.back();
3253         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
3254         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
3255
3256         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
3257         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
3258         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3259         dumpMove( tgtNode );
3260
3261         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3262         pos->SetUParameter( newUV.X() );
3263         pos->SetVParameter( newUV.Y() );
3264       }
3265     }
3266     return true;
3267   }
3268
3269   return false;
3270 }
3271
3272 //================================================================================
3273 /*!
3274  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
3275  * _LayerEdge's on neighbor EDGE's
3276  */
3277 //================================================================================
3278
3279 bool _ViscousBuilder::updateNormals( _SolidData&         data,
3280                                      SMESH_MesherHelper& helper,
3281                                      int                 stepNb )
3282 {
3283   if ( stepNb > 0 )
3284     return updateNormalsOfConvexFaces( data, helper, stepNb );
3285
3286   // make temporary quadrangles got by extrusion of
3287   // mesh edges along _LayerEdge._normal's
3288
3289   vector< const SMDS_MeshElement* > tmpFaces;
3290   {
3291     set< SMESH_TLink > extrudedLinks; // contains target nodes
3292     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
3293
3294     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
3295     for ( size_t i = 0; i < data._edges.size(); ++i )
3296     {
3297       _LayerEdge* edge = data._edges[i];
3298       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3299       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
3300       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
3301       {
3302         const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
3303         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
3304           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
3305         if ( !link_isnew.second )
3306         {
3307           extrudedLinks.erase( link_isnew.first );
3308           continue; // already extruded and will no more encounter
3309         }
3310         // a _LayerEdge containg tgt2
3311         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3312
3313         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3314         tmpFaces.push_back( f );
3315
3316         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3317                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3318                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3319       }
3320     }
3321     dumpFunctionEnd();
3322   }
3323   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3324   // Perform two loops on _LayerEdge on EDGE's:
3325   // 1) to find and fix intersection
3326   // 2) to check that no new intersection appears as result of 1)
3327
3328   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3329                                                             tmpFaces.end()));
3330   auto_ptr<SMESH_ElementSearcher> searcher
3331     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3332
3333   // 1) Find intersections
3334   double dist;
3335   const SMDS_MeshElement* face;
3336   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3337   TLEdge2LEdgeSet edge2CloseEdge;
3338
3339   const double eps = data._epsilon * data._epsilon;
3340   for ( size_t i = 0; i < data._edges.size(); ++i )
3341   {
3342     _LayerEdge* edge = data._edges[i];
3343     if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3344     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3345     {
3346       const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
3347       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3348       ee.insert( f->_le1 );
3349       ee.insert( f->_le2 );
3350       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
3351         edge2CloseEdge[ f->_le1 ].insert( edge );
3352       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
3353         edge2CloseEdge[ f->_le2 ].insert( edge );
3354     }
3355   }
3356
3357   // Set _LayerEdge._normal
3358
3359   if ( !edge2CloseEdge.empty() )
3360   {
3361     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3362
3363     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3364     for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3365     {
3366       _LayerEdge* edge1       = e2ee->first;
3367       _LayerEdge* edge2       = 0;
3368       set< _LayerEdge*, _LayerEdgeCmp >& ee  = e2ee->second;
3369
3370       // find EDGEs the edges reside
3371       TopoDS_Edge E1, E2;
3372       TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3373       if ( S.ShapeType() != TopAbs_EDGE )
3374         continue; // TODO: find EDGE by VERTEX
3375       E1 = TopoDS::Edge( S );
3376       set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3377       while ( E2.IsNull() && eIt != ee.end())
3378       {
3379         _LayerEdge* e2 = *eIt++;
3380         TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3381         if ( S.ShapeType() == TopAbs_EDGE )
3382           E2 = TopoDS::Edge( S ), edge2 = e2;
3383       }
3384       if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3385
3386       // find 3 FACEs sharing 2 EDGEs
3387
3388       TopoDS_Face FF1[2], FF2[2];
3389       PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3390       while ( fIt->more() && FF1[1].IsNull())
3391       {
3392         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3393         if ( helper.IsSubShape( *F, data._solid))
3394           FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3395       }
3396       fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3397       while ( fIt->more() && FF2[1].IsNull())
3398       {
3399         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3400         if ( helper.IsSubShape( *F, data._solid))
3401           FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3402       }
3403       // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3404       if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3405         std::swap( FF1[0], FF1[1] );
3406       if ( FF2[0].IsSame( FF1[0]) )
3407         std::swap( FF2[0], FF2[1] );
3408       if ( FF1[0].IsNull() || FF2[0].IsNull() )
3409         continue;
3410
3411       // get a new normal for edge1
3412       bool ok;
3413       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3414       if ( edge1->_cosin < 0 )
3415         dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3416       if ( edge2->_cosin < 0 )
3417         dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3418       // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3419       // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3420       // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3421       // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3422       // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3423       // newNorm.Normalize();
3424
3425       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3426       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3427       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3428       newNorm.Normalize();
3429
3430       edge1->_normal = newNorm.XYZ();
3431
3432       // update data of edge1 depending on _normal
3433       const SMDS_MeshNode *n1, *n2;
3434       n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3435       n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3436       edge1->SetDataByNeighbors( n1, n2, helper );
3437       gp_Vec dirInFace;
3438       if ( edge1->_cosin < 0 )
3439         dirInFace = dir1;
3440       else
3441         dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3442       double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3443       edge1->SetCosin( cos( angle ));
3444
3445       // limit data._stepSize
3446       if ( edge1->_cosin > theMinSmoothCosin )
3447       {
3448         SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3449         while ( fIt->more() )
3450           limitStepSize( data, fIt->next(), edge1->_cosin );
3451       }
3452       // set new XYZ of target node
3453       edge1->InvalidateStep( 1 );
3454       edge1->_len = 0;
3455       edge1->SetNewLength( data._stepSize, helper );
3456     }
3457
3458     // Update normals and other dependent data of not intersecting _LayerEdge's
3459     // neighboring the intersecting ones
3460
3461     for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3462     {
3463       _LayerEdge* edge1 = e2ee->first;
3464       if ( !edge1->_2neibors )
3465         continue;
3466       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3467       {
3468         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3469         if ( edge2CloseEdge.count ( neighbor ))
3470           continue; // j-th neighbor is also intersected
3471         _LayerEdge* prevEdge = edge1;
3472         const int nbSteps = 6;
3473         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3474         {
3475           if ( !neighbor->_2neibors )
3476             break; // neighbor is on VERTEX
3477           int iNext = 0;
3478           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3479           if ( nextEdge == prevEdge )
3480             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3481           double r = double(step-1)/nbSteps;
3482           if ( !nextEdge->_2neibors )
3483             r = 0.5;
3484
3485           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3486           newNorm.Normalize();
3487
3488           neighbor->_normal = newNorm;
3489           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3490           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3491
3492           neighbor->InvalidateStep( 1 );
3493           neighbor->_len = 0;
3494           neighbor->SetNewLength( data._stepSize, helper );
3495
3496           // goto the next neighbor
3497           prevEdge = neighbor;
3498           neighbor = nextEdge;
3499         }
3500       }
3501     }
3502     dumpFunctionEnd();
3503   }
3504   // 2) Check absence of intersections
3505   // TODO?
3506
3507   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3508     delete tmpFaces[i];
3509
3510   return true;
3511 }
3512
3513 //================================================================================
3514 /*!
3515  * \brief Modify normals of _LayerEdge's on _ConvexFace's
3516  */
3517 //================================================================================
3518
3519 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
3520                                                   SMESH_MesherHelper& helper,
3521                                                   int                 stepNb )
3522 {
3523   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
3524   bool isOK;
3525
3526   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3527   for ( ; id2face != data._convexFaces.end(); ++id2face )
3528   {
3529     _ConvexFace & convFace = (*id2face).second;
3530     if ( convFace._normalsFixed )
3531       continue; // already fixed
3532     if ( convFace.CheckPrisms() )
3533       continue; // nothing to fix
3534
3535     convFace._normalsFixed = true;
3536
3537     BRepAdaptor_Surface surface ( convFace._face, false );
3538     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
3539
3540     // check if the convex FACE is of spherical shape
3541
3542     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
3543     Bnd_B3d nodesBox;
3544     gp_Pnt  center;
3545     int     iBeg, iEnd;
3546
3547     map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
3548     for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3549     {
3550       data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3551
3552       if ( meshDS->IndexToShape( id2end->first ).ShapeType() == TopAbs_VERTEX )
3553       {
3554         _LayerEdge* ledge = data._edges[ iBeg ];
3555         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
3556           centersBox.Add( center );
3557       }
3558       for ( ; iBeg < iEnd; ++iBeg )
3559         nodesBox.Add( SMESH_TNodeXYZ( data._edges[ iBeg ]->_nodes[0] ));
3560     }
3561     if ( centersBox.IsVoid() )
3562     {
3563       debugMsg( "Error: centersBox.IsVoid()" );
3564       return false;
3565     }
3566     const bool isSpherical =
3567       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
3568
3569     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
3570     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
3571
3572     if ( isSpherical )
3573     {
3574       // set _LayerEdge::_normal as average of all normals
3575
3576       // WARNING: different density of nodes on EDGEs is not taken into account that
3577       // can lead to an improper new normal
3578
3579       gp_XYZ avgNormal( 0,0,0 );
3580       nbEdges = 0;
3581       id2end = convFace._subIdToEdgeEnd.begin();
3582       for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3583       {
3584         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3585         // set data of _CentralCurveOnEdge
3586         const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
3587         if ( S.ShapeType() == TopAbs_EDGE )
3588         {
3589           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
3590           ceCurve.SetShapes( TopoDS::Edge(S), convFace, data, helper );
3591           if ( !data._edges[ iBeg ]->_sWOL.IsNull() )
3592             ceCurve._adjFace.Nullify();
3593           else
3594             ceCurve._ledges.insert( ceCurve._ledges.end(),
3595                                     &data._edges[ iBeg ], &data._edges[ iEnd ]);
3596         }
3597         // summarize normals
3598         for ( ; iBeg < iEnd; ++iBeg )
3599           avgNormal += data._edges[ iBeg ]->_normal;
3600       }
3601       avgNormal.Normalize();
3602
3603       // compute new _LayerEdge::_cosin on EDGEs
3604       double avgCosin = 0;
3605       int     nbCosin = 0;
3606       gp_Vec inFaceDir;
3607       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3608       {
3609         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
3610         if ( ceCurve._adjFace.IsNull() )
3611           continue;
3612         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
3613         {
3614           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
3615           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
3616           if ( isOK )
3617           {
3618             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
3619             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
3620             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
3621             nbCosin++;
3622           }
3623         }
3624       }
3625       if ( nbCosin > 0 )
3626         avgCosin /= nbCosin;
3627
3628       // set _LayerEdge::_normal = avgNormal
3629       id2end = convFace._subIdToEdgeEnd.begin();
3630       for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3631       {
3632         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3633         const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
3634         if ( S.ShapeType() != TopAbs_EDGE )
3635           for ( int i = iBeg; i < iEnd; ++i )
3636             data._edges[ i ]->_cosin = avgCosin;
3637
3638         for ( ; iBeg < iEnd; ++iBeg )
3639           data._edges[ iBeg ]->_normal = avgNormal;
3640       }
3641     }
3642     else // if ( isSpherical )
3643     {
3644       // We suppose that centers of curvature at all points of the FACE
3645       // lie on some curve, let's call it "central curve". For all _LayerEdge's
3646       // having a common center of curvature we define the same new normal
3647       // as a sum of normals of _LayerEdge's on EDGEs among them.
3648
3649       // get all centers of curvature for each EDGE
3650
3651       helper.SetSubShape( convFace._face );
3652       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
3653
3654       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
3655       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
3656       {
3657         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
3658
3659         // set adjacent FACE
3660         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
3661
3662         // get _LayerEdge's of the EDGE
3663         TGeomID edgeID = meshDS->ShapeToIndex( edge );
3664         id2end = convFace._subIdToEdgeEnd.find( edgeID );
3665         if ( id2end == convFace._subIdToEdgeEnd.end() )
3666         {
3667           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
3668           for ( int iV = 0; iV < 2; ++iV )
3669           {
3670             TopoDS_Vertex v = helper.IthVertex( iV, edge );
3671             TGeomID     vID = meshDS->ShapeToIndex( v );
3672             int  end = convFace._subIdToEdgeEnd[ vID ];
3673             int iBeg = end > 0 ? data._endEdgeOnShape[ end-1 ] : 0;
3674             vertexLEdges[ iV ] = data._edges[ iBeg ];
3675           }
3676           edgeLEdge    = &vertexLEdges[0];
3677           edgeLEdgeEnd = edgeLEdge + 2;
3678
3679           centerCurves[ iE ]._adjFace.Nullify();
3680         }
3681         else
3682         {
3683           data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3684           if ( id2end->second >= data._nbShapesToSmooth )
3685             data.SortOnEdge( edge, iBeg, iEnd, helper );
3686           edgeLEdge    = &data._edges[ iBeg ];
3687           edgeLEdgeEnd = edgeLEdge + iEnd - iBeg;
3688           vertexLEdges[0] = data._edges[ iBeg   ]->_2neibors->_edges[0];
3689           vertexLEdges[1] = data._edges[ iEnd-1 ]->_2neibors->_edges[1];
3690
3691           if ( ! data._edges[ iBeg ]->_sWOL.IsNull() )
3692             centerCurves[ iE ]._adjFace.Nullify();
3693         }
3694
3695         // Get curvature centers
3696
3697         centersBox.Clear();
3698
3699         if ( edgeLEdge[0]->IsOnEdge() &&
3700              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
3701         { // 1st VERTEX
3702           centerCurves[ iE ].Append( center, vertexLEdges[0] );
3703           centersBox.Add( center );
3704         }
3705         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
3706           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
3707           { // EDGE or VERTEXes
3708             centerCurves[ iE ].Append( center, *edgeLEdge );
3709             centersBox.Add( center );
3710           }
3711         if ( edgeLEdge[-1]->IsOnEdge() &&
3712              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
3713         { // 2nd VERTEX
3714           centerCurves[ iE ].Append( center, vertexLEdges[1] );
3715           centersBox.Add( center );
3716         }
3717         centerCurves[ iE ]._isDegenerated =
3718           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
3719
3720       } // loop on EDGES of convFace._face to set up data of centerCurves
3721
3722       // Compute new normals for _LayerEdge's on EDGEs
3723
3724       double avgCosin = 0;
3725       int     nbCosin = 0;
3726       gp_Vec inFaceDir;
3727       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
3728       {
3729         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
3730         if ( ceCurve._isDegenerated )
3731           continue;
3732         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
3733         vector< gp_XYZ > &   newNormals = ceCurve._normals;
3734         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
3735         {
3736           isOK = false;
3737           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
3738           {
3739             if ( iE1 != iE2 )
3740               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
3741           }
3742           if ( isOK && !ceCurve._adjFace.IsNull() )
3743           {
3744             // compute new _LayerEdge::_cosin
3745             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
3746             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
3747             if ( isOK )
3748             {
3749               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
3750               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
3751               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
3752               nbCosin++;
3753             }
3754           }
3755         }
3756       }
3757       // set new normals to _LayerEdge's of NOT degenerated central curves
3758       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3759       {
3760         if ( centerCurves[ iE ]._isDegenerated )
3761           continue;
3762         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
3763           centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
3764       }
3765       // set new normals to _LayerEdge's of     degenerated central curves
3766       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3767       {
3768         if ( !centerCurves[ iE ]._isDegenerated ||
3769              centerCurves[ iE ]._ledges.size() < 3 )
3770           continue;
3771         // new normal is an average of new normals at VERTEXes that
3772         // was computed on non-degenerated _CentralCurveOnEdge's
3773         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
3774                            centerCurves[ iE ]._ledges.back ()->_normal );
3775         double sz = newNorm.Modulus();
3776         if ( sz < 1e-200 )
3777           continue;
3778         newNorm /= sz;
3779         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
3780                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
3781         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
3782         {
3783           centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
3784           centerCurves[ iE ]._ledges[ iLE ]->_cosin  = newCosin;
3785         }
3786       }
3787
3788       // Find new normals for _LayerEdge's based on FACE
3789
3790       if ( nbCosin > 0 )
3791         avgCosin /= nbCosin;
3792       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
3793       map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
3794       if ( id2end != convFace._subIdToEdgeEnd.end() )
3795       {
3796         int iE = 0;
3797         gp_XYZ newNorm;
3798         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3799         for ( ; iBeg < iEnd; ++iBeg )
3800         {
3801           _LayerEdge* ledge = data._edges[ iBeg ];
3802           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
3803             continue;
3804           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
3805           {
3806             iE = iE % centerCurves.size();
3807             if ( centerCurves[ iE ]._isDegenerated )
3808               continue;
3809             newNorm.SetCoord( 0,0,0 );
3810             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
3811             {
3812               ledge->_normal = newNorm;
3813               ledge->_cosin  = avgCosin;
3814               break;
3815             }
3816           }
3817         }
3818       }
3819
3820     } // not a quasi-spherical FACE
3821
3822     // Update _LayerEdge's data according to a new normal
3823
3824     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
3825                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
3826
3827     id2end = convFace._subIdToEdgeEnd.begin();
3828     for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
3829     {
3830       data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
3831       for ( ; iBeg < iEnd; ++iBeg )
3832       {
3833         _LayerEdge* & ledge = data._edges[ iBeg ];
3834         double len = ledge->_len;
3835         ledge->InvalidateStep( stepNb + 1, /*restoreLength=*/true );
3836         ledge->SetCosin( ledge->_cosin );
3837         ledge->SetNewLength( len, helper );
3838       }
3839
3840     } // loop on sub-shapes of convFace._face
3841
3842     // Find FACEs adjacent to convFace._face that got necessity to smooth
3843     // as a result of normals modification
3844
3845     set< TGeomID > adjFacesToSmooth;
3846     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
3847     {
3848       if ( centerCurves[ iE ]._adjFace.IsNull() ||
3849            centerCurves[ iE ]._adjFaceToSmooth )
3850         continue;
3851       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
3852       {
3853         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
3854         {
3855           adjFacesToSmooth.insert( meshDS->ShapeToIndex( centerCurves[ iE ]._adjFace ));
3856           break;
3857         }
3858       }
3859     }
3860     data.AddFacesToSmooth( adjFacesToSmooth );
3861
3862     dumpFunctionEnd();
3863
3864
3865   } // loop on data._convexFaces
3866
3867   return true;
3868 }
3869
3870 //================================================================================
3871 /*!
3872  * \brief Finds a center of curvature of a surface at a _LayerEdge
3873  */
3874 //================================================================================
3875
3876 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
3877                                         BRepLProp_SLProps&  surfProp,
3878                                         SMESH_MesherHelper& helper,
3879                                         gp_Pnt &            center ) const
3880 {
3881   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
3882   surfProp.SetParameters( uv.X(), uv.Y() );
3883   if ( !surfProp.IsCurvatureDefined() )
3884     return false;
3885
3886   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
3887   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
3888   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
3889   if ( surfCurvatureMin > surfCurvatureMax )
3890     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
3891   else
3892     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
3893
3894   return true;
3895 }
3896
3897 //================================================================================
3898 /*!
3899  * \brief Check that prisms are not distorted
3900  */
3901 //================================================================================
3902
3903 bool _ConvexFace::CheckPrisms() const
3904 {
3905   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
3906   {
3907     const _LayerEdge* edge = _simplexTestEdges[i];
3908     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3909     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3910       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
3911       {
3912         debugMsg( "Bad simplex of _simplexTestEdges ("
3913                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3914                   << " "<< edge->_simplices[j]._nPrev->GetID()
3915                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
3916         return false;
3917       }
3918   }
3919   return true;
3920 }
3921
3922 //================================================================================
3923 /*!
3924  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
3925  *        stored in this _CentralCurveOnEdge.
3926  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
3927  *  \param [in,out] newNormal - current normal at this point, to be redefined
3928  *  \return bool - true if succeeded.
3929  */
3930 //================================================================================
3931
3932 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
3933 {
3934   if ( this->_isDegenerated )
3935     return false;
3936
3937   // find two centers the given one lies between
3938
3939   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
3940   {
3941     double sl2 = 1.001 * _segLength2[ i ];
3942
3943     double d1 = center.SquareDistance( _curvaCenters[ i ]);
3944     if ( d1 > sl2 )
3945       continue;
3946     
3947     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
3948     if ( d2 > sl2 || d2 + d1 < 1e-100 )
3949       continue;
3950
3951     d1 = Sqrt( d1 );
3952     d2 = Sqrt( d2 );
3953     double r = d1 / ( d1 + d2 );
3954     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
3955                    (      r ) * _ledges[ i+1 ]->_normal );
3956     norm.Normalize();
3957
3958     newNormal += norm;
3959     double sz = newNormal.Modulus();
3960     if ( Abs ( sz ) < 1e-200 )
3961       break;
3962     newNormal /= sz;
3963     return true;
3964   }
3965   return false;
3966 }
3967
3968 //================================================================================
3969 /*!
3970  * \brief Set shape members
3971  */
3972 //================================================================================
3973
3974 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
3975                                      const _ConvexFace&  convFace,
3976                                      const _SolidData&   data,
3977                                      SMESH_MesherHelper& helper)
3978 {
3979   _edge = edge;
3980
3981   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
3982   while ( const TopoDS_Shape* F = fIt->next())
3983     if ( !convFace._face.IsSame( *F ))
3984     {
3985       _adjFace = TopoDS::Face( *F );
3986       _adjFaceToSmooth = false;
3987       // _adjFace already in a smoothing queue ?
3988       size_t end;
3989       TGeomID adjFaceID = helper.GetMeshDS()->ShapeToIndex( *F );
3990       if ( data.GetShapeEdges( adjFaceID, end ))
3991         _adjFaceToSmooth = ( end < data._nbShapesToSmooth );
3992       break;
3993     }
3994 }
3995
3996 //================================================================================
3997 /*!
3998  * \brief Looks for intersection of it's last segment with faces
3999  *  \param distance - returns shortest distance from the last node to intersection
4000  */
4001 //================================================================================
4002
4003 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
4004                                    double &                 distance,
4005                                    const double&            epsilon,
4006                                    const SMDS_MeshElement** face)
4007 {
4008   vector< const SMDS_MeshElement* > suspectFaces;
4009   double segLen;
4010   gp_Ax1 lastSegment = LastSegment(segLen);
4011   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
4012
4013   bool segmentIntersected = false;
4014   distance = Precision::Infinite();
4015   int iFace = -1; // intersected face
4016   for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
4017   {
4018     const SMDS_MeshElement* face = suspectFaces[j];
4019     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
4020          face->GetNodeIndex( _nodes[0]     ) >= 0 )
4021       continue; // face sharing _LayerEdge node
4022     const int nbNodes = face->NbCornerNodes();
4023     bool intFound = false;
4024     double dist;
4025     SMDS_MeshElement::iterator nIt = face->begin_nodes();
4026     if ( nbNodes == 3 )
4027     {
4028       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
4029     }
4030     else
4031     {
4032       const SMDS_MeshNode* tria[3];
4033       tria[0] = *nIt++;
4034       tria[1] = *nIt++;;
4035       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
4036       {
4037         tria[2] = *nIt++;
4038         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
4039         tria[1] = tria[2];
4040       }
4041     }
4042     if ( intFound )
4043     {
4044       if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
4045         segmentIntersected = true;
4046       if ( distance > dist )
4047         distance = dist, iFace = j;
4048     }
4049   }
4050   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
4051
4052   if ( segmentIntersected )
4053   {
4054 #ifdef __myDEBUG
4055     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
4056     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
4057     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
4058          << ", intersection with face ("
4059          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4060          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
4061          << ") distance = " << distance - segLen<< endl;
4062 #endif
4063   }
4064
4065   distance -= segLen;
4066
4067   return segmentIntersected;
4068 }
4069
4070 //================================================================================
4071 /*!
4072  * \brief Returns size and direction of the last segment
4073  */
4074 //================================================================================
4075
4076 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
4077 {
4078   // find two non-coincident positions
4079   gp_XYZ orig = _pos.back();
4080   gp_XYZ dir;
4081   int iPrev = _pos.size() - 2;
4082   while ( iPrev >= 0 )
4083   {
4084     dir = orig - _pos[iPrev];
4085     if ( dir.SquareModulus() > 1e-100 )
4086       break;
4087     else
4088       iPrev--;
4089   }
4090
4091   // make gp_Ax1
4092   gp_Ax1 segDir;
4093   if ( iPrev < 0 )
4094   {
4095     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
4096     segDir.SetDirection( _normal );
4097     segLen = 0;
4098   }
4099   else
4100   {
4101     gp_Pnt pPrev = _pos[ iPrev ];
4102     if ( !_sWOL.IsNull() )
4103     {
4104       TopLoc_Location loc;
4105       if ( _sWOL.ShapeType() == TopAbs_EDGE )
4106       {
4107         double f,l;
4108         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
4109         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
4110       }
4111       else
4112       {
4113         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
4114         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
4115       }
4116       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
4117     }
4118     segDir.SetLocation( pPrev );
4119     segDir.SetDirection( dir );
4120     segLen = dir.Modulus();
4121   }
4122
4123   return segDir;
4124 }
4125
4126 //================================================================================
4127 /*!
4128  * \brief Test intersection of the last segment with a given triangle
4129  *   using Moller-Trumbore algorithm
4130  * Intersection is detected if distance to intersection is less than _LayerEdge._len
4131  */
4132 //================================================================================
4133
4134 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
4135                                const SMDS_MeshNode* n0,
4136                                const SMDS_MeshNode* n1,
4137                                const SMDS_MeshNode* n2,
4138                                double&              t,
4139                                const double&        EPSILON) const
4140 {
4141   //const double EPSILON = 1e-6;
4142
4143   gp_XYZ orig = lastSegment.Location().XYZ();
4144   gp_XYZ dir  = lastSegment.Direction().XYZ();
4145
4146   SMESH_TNodeXYZ vert0( n0 );
4147   SMESH_TNodeXYZ vert1( n1 );
4148   SMESH_TNodeXYZ vert2( n2 );
4149
4150   /* calculate distance from vert0 to ray origin */
4151   gp_XYZ tvec = orig - vert0;
4152
4153   if ( tvec * dir > EPSILON )
4154     // intersected face is at back side of the temporary face this _LayerEdge belongs to
4155     return false;
4156
4157   gp_XYZ edge1 = vert1 - vert0;
4158   gp_XYZ edge2 = vert2 - vert0;
4159
4160   /* begin calculating determinant - also used to calculate U parameter */
4161   gp_XYZ pvec = dir ^ edge2;
4162
4163   /* if determinant is near zero, ray lies in plane of triangle */
4164   double det = edge1 * pvec;
4165
4166   if (det > -EPSILON && det < EPSILON)
4167     return 0;
4168   double inv_det = 1.0 / det;
4169
4170   /* calculate U parameter and test bounds */
4171   double u = ( tvec * pvec ) * inv_det;
4172   if (u < 0.0 || u > 1.0)
4173     return 0;
4174
4175   /* prepare to test V parameter */
4176   gp_XYZ qvec = tvec ^ edge1;
4177
4178   /* calculate V parameter and test bounds */
4179   double v = (dir * qvec) * inv_det;
4180   if ( v < 0.0 || u + v > 1.0 )
4181     return 0;
4182
4183   /* calculate t, ray intersects triangle */
4184   t = (edge2 * qvec) * inv_det;
4185
4186   return true;
4187 }
4188
4189 //================================================================================
4190 /*!
4191  * \brief Perform smooth of _LayerEdge's based on EDGE's
4192  *  \retval bool - true if node has been moved
4193  */
4194 //================================================================================
4195
4196 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
4197                               const TopoDS_Face&    F,
4198                               SMESH_MesherHelper&   helper)
4199 {
4200   ASSERT( IsOnEdge() );
4201
4202   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
4203   SMESH_TNodeXYZ oldPos( tgtNode );
4204   double dist01, distNewOld;
4205   
4206   SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
4207   SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
4208   dist01 = p0.Distance( _2neibors->_nodes[1] );
4209
4210   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
4211   double lenDelta = 0;
4212   if ( _curvature )
4213   {
4214     //lenDelta = _curvature->lenDelta( _len );
4215     lenDelta = _curvature->lenDeltaByDist( dist01 );
4216     newPos.ChangeCoord() += _normal * lenDelta;
4217   }
4218
4219   distNewOld = newPos.Distance( oldPos );
4220
4221   if ( F.IsNull() )
4222   {
4223     if ( _2neibors->_plnNorm )
4224     {
4225       // put newPos on the plane defined by source node and _plnNorm
4226       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
4227       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
4228       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
4229     }
4230     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4231     _pos.back() = newPos.XYZ();
4232   }
4233   else
4234   {
4235     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4236     gp_XY uv( Precision::Infinite(), 0 );
4237     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
4238     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
4239
4240     newPos = surface->Value( uv.X(), uv.Y() );
4241     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4242   }
4243
4244   if ( _curvature && lenDelta < 0 )
4245   {
4246     gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
4247     _len -= prevPos.Distance( oldPos );
4248     _len += prevPos.Distance( newPos );
4249   }
4250   bool moved = distNewOld > dist01/50;
4251   //if ( moved )
4252   dumpMove( tgtNode ); // debug
4253
4254   return moved;
4255 }
4256
4257 //================================================================================
4258 /*!
4259  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
4260  *  \retval bool - true if _tgtNode has been moved
4261  */
4262 //================================================================================
4263
4264 bool _LayerEdge::Smooth(int& badNb)
4265 {
4266   if ( _simplices.size() < 2 )
4267     return false; // _LayerEdge inflated along EDGE or FACE
4268
4269   // compute new position for the last _pos
4270   gp_XYZ newPos (0,0,0);
4271   for ( size_t i = 0; i < _simplices.size(); ++i )
4272     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
4273   newPos /= _simplices.size();
4274
4275   if ( _curvature )
4276     newPos += _normal * _curvature->lenDelta( _len );
4277
4278   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
4279
4280   // count quality metrics (orientation) of tetras around _tgtNode
4281   int nbOkBefore = 0;
4282   SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
4283   for ( size_t i = 0; i < _simplices.size(); ++i )
4284     nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
4285
4286   int nbOkAfter = 0;
4287   for ( size_t i = 0; i < _simplices.size(); ++i )
4288     nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
4289
4290   if ( nbOkAfter < nbOkBefore )
4291     return false;
4292
4293   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
4294
4295   _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
4296   _len += prevPos.Distance(newPos);
4297
4298   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
4299   _pos.back() = newPos;
4300
4301   badNb += _simplices.size() - nbOkAfter;
4302
4303   dumpMove( n );
4304
4305   return true;
4306 }
4307
4308 //================================================================================
4309 /*!
4310  * \brief Add a new segment to _LayerEdge during inflation
4311  */
4312 //================================================================================
4313
4314 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
4315 {
4316   if ( _len - len > -1e-6 )
4317   {
4318     _pos.push_back( _pos.back() );
4319     return;
4320   }
4321
4322   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
4323   SMESH_TNodeXYZ oldXYZ( n );
4324   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
4325   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
4326
4327   _pos.push_back( nXYZ );
4328   _len = len;
4329   if ( !_sWOL.IsNull() )
4330   {
4331     double distXYZ[4];
4332     if ( _sWOL.ShapeType() == TopAbs_EDGE )
4333     {
4334       double u = Precision::Infinite(); // to force projection w/o distance check
4335       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
4336       _pos.back().SetCoord( u, 0, 0 );
4337       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
4338       pos->SetUParameter( u );
4339     }
4340     else //  TopAbs_FACE
4341     {
4342       gp_XY uv( Precision::Infinite(), 0 );
4343       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
4344       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
4345       SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
4346       pos->SetUParameter( uv.X() );
4347       pos->SetVParameter( uv.Y() );
4348     }
4349     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
4350   }
4351   dumpMove( n ); //debug
4352 }
4353
4354 //================================================================================
4355 /*!
4356  * \brief Remove last inflation step
4357  */
4358 //================================================================================
4359
4360 void _LayerEdge::InvalidateStep( int curStep, bool restoreLength )
4361 {
4362   if ( _pos.size() > curStep )
4363   {
4364     if ( restoreLength )
4365       _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
4366
4367     _pos.resize( curStep );
4368     gp_Pnt nXYZ = _pos.back();
4369     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
4370     if ( !_sWOL.IsNull() )
4371     {
4372       TopLoc_Location loc;
4373       if ( _sWOL.ShapeType() == TopAbs_EDGE )
4374       {
4375         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
4376         pos->SetUParameter( nXYZ.X() );
4377         double f,l;
4378         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
4379         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
4380       }
4381       else
4382       {
4383         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
4384         pos->SetUParameter( nXYZ.X() );
4385         pos->SetVParameter( nXYZ.Y() );
4386         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
4387         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
4388       }
4389     }
4390     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
4391     dumpMove( n );
4392   }
4393 }
4394
4395 //================================================================================
4396 /*!
4397  * \brief Create layers of prisms
4398  */
4399 //================================================================================
4400
4401 bool _ViscousBuilder::refine(_SolidData& data)
4402 {
4403   SMESH_MesherHelper helper( *_mesh );
4404   helper.SetSubShape( data._solid );
4405   helper.SetElementsOnShape(false);
4406
4407   Handle(Geom_Curve) curve;
4408   Handle(Geom_Surface) surface;
4409   TopoDS_Edge geomEdge;
4410   TopoDS_Face geomFace;
4411   TopoDS_Shape prevSWOL;
4412   TopLoc_Location loc;
4413   double f,l, u;
4414   gp_XY uv;
4415   bool isOnEdge;
4416   TGeomID prevBaseId = -1;
4417   TNode2Edge* n2eMap = 0;
4418   TNode2Edge::iterator n2e;
4419
4420   for ( size_t i = 0; i < data._edges.size(); ++i )
4421   {
4422     _LayerEdge& edge = *data._edges[i];
4423
4424     // get accumulated length of segments
4425     vector< double > segLen( edge._pos.size() );
4426     segLen[0] = 0.0;
4427     for ( size_t j = 1; j < edge._pos.size(); ++j )
4428       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
4429
4430     // allocate memory for new nodes if it is not yet refined
4431     const SMDS_MeshNode* tgtNode = edge._nodes.back();
4432     if ( edge._nodes.size() == 2 )
4433     {
4434       edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
4435       edge._nodes[1] = 0;
4436       edge._nodes.back() = tgtNode;
4437     }
4438     // get data of a shrink shape
4439     if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
4440     {
4441       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
4442       if ( isOnEdge )
4443       {
4444         geomEdge = TopoDS::Edge( edge._sWOL );
4445         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
4446       }
4447       else
4448       {
4449         geomFace = TopoDS::Face( edge._sWOL );
4450         surface  = BRep_Tool::Surface( geomFace, loc );
4451       }
4452       prevSWOL = edge._sWOL;
4453     }
4454     // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
4455     const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
4456     if ( baseShapeId != prevBaseId )
4457     {
4458       map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
4459       n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
4460       prevBaseId = baseShapeId;
4461     }
4462     if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
4463     {
4464       _LayerEdge*  foundEdge = n2e->second;
4465       const gp_XYZ& foundPos = foundEdge->_pos.back();
4466       SMDS_PositionPtr lastPos = tgtNode->GetPosition();
4467       if ( isOnEdge )
4468       {
4469         SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
4470         epos->SetUParameter( foundPos.X() );
4471       }
4472       else
4473       {
4474         SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
4475         fpos->SetUParameter( foundPos.X() );
4476         fpos->SetVParameter( foundPos.Y() );
4477       }
4478     }
4479     // calculate height of the first layer
4480     double h0;
4481     const double T = segLen.back(); //data._hyp.GetTotalThickness();
4482     const double f = data._hyp->GetStretchFactor();
4483     const int    N = data._hyp->GetNumberLayers();
4484     const double fPowN = pow( f, N );
4485     if ( fPowN - 1 <= numeric_limits<double>::min() )
4486       h0 = T / N;
4487     else
4488       h0 = T * ( f - 1 )/( fPowN - 1 );
4489
4490     const double zeroLen = std::numeric_limits<double>::min();
4491
4492     // create intermediate nodes
4493     double hSum = 0, hi = h0/f;
4494     size_t iSeg = 1;
4495     for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
4496     {
4497       // compute an intermediate position
4498       hi *= f;
4499       hSum += hi;
4500       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
4501         ++iSeg;
4502       int iPrevSeg = iSeg-1;
4503       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
4504         --iPrevSeg;
4505       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
4506       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
4507
4508       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
4509       if ( !edge._sWOL.IsNull() )
4510       {
4511         // compute XYZ by parameters <pos>
4512         if ( isOnEdge )
4513         {
4514           u = pos.X();
4515           if ( !node )
4516             pos = curve->Value( u ).Transformed(loc);
4517         }
4518         else
4519         {
4520           uv.SetCoord( pos.X(), pos.Y() );
4521           if ( !node )
4522             pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
4523         }
4524       }
4525       // create or update the node
4526       if ( !node )
4527       {
4528         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
4529         if ( !edge._sWOL.IsNull() )
4530         {
4531           if ( isOnEdge )
4532             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
4533           else
4534             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
4535         }
4536         else
4537         {
4538           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
4539         }
4540       }
4541       else
4542       {
4543         if ( !edge._sWOL.IsNull() )
4544         {
4545           // make average pos from new and current parameters
4546           if ( isOnEdge )
4547           {
4548             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
4549             pos = curve->Value( u ).Transformed(loc);
4550
4551             SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
4552             epos->SetUParameter( u );
4553           }
4554           else
4555           {
4556             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
4557             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
4558
4559             SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
4560             fpos->SetUParameter( uv.X() );
4561             fpos->SetVParameter( uv.Y() );
4562           }
4563         }
4564         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
4565       }
4566     }
4567   }
4568
4569   if ( !getMeshDS()->IsEmbeddedMode() )
4570     // Log node movement
4571     for ( size_t i = 0; i < data._edges.size(); ++i )
4572     {
4573       _LayerEdge& edge = *data._edges[i];
4574       SMESH_TNodeXYZ p ( edge._nodes.back() );
4575       getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
4576     }
4577
4578   // TODO: make quadratic prisms and polyhedrons(?)
4579
4580   helper.SetElementsOnShape(true);
4581
4582   TopExp_Explorer exp( data._solid, TopAbs_FACE );
4583   for ( ; exp.More(); exp.Next() )
4584   {
4585     if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
4586       continue;
4587     SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
4588     SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
4589     vector< vector<const SMDS_MeshNode*>* > nnVec;
4590     while ( fIt->more() )
4591     {
4592       const SMDS_MeshElement* face = fIt->next();
4593       int nbNodes = face->NbCornerNodes();
4594       nnVec.resize( nbNodes );
4595       SMDS_ElemIteratorPtr nIt = face->nodesIterator();
4596       for ( int iN = 0; iN < nbNodes; ++iN )
4597       {
4598         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4599         nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
4600       }
4601
4602       int nbZ = nnVec[0]->size();
4603       switch ( nbNodes )
4604       {
4605       case 3:
4606         for ( int iZ = 1; iZ < nbZ; ++iZ )
4607           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
4608                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
4609         break;
4610       case 4:
4611         for ( int iZ = 1; iZ < nbZ; ++iZ )
4612           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
4613                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
4614                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
4615                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
4616         break;
4617       default:
4618         return error("Not supported type of element", data._index);
4619       }
4620     }
4621   }
4622   return true;
4623 }
4624
4625 //================================================================================
4626 /*!
4627  * \brief Shrink 2D mesh on faces to let space for inflated layers
4628  */
4629 //================================================================================
4630
4631 bool _ViscousBuilder::shrink()
4632 {
4633   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
4634   // inflated along FACE or EDGE)
4635   map< TGeomID, _SolidData* > f2sdMap;
4636   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4637   {
4638     _SolidData& data = _sdVec[i];
4639     TopTools_MapOfShape FFMap;
4640     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
4641     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
4642       if ( s2s->second.ShapeType() == TopAbs_FACE )
4643       {
4644         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
4645
4646         if ( FFMap.Add( (*s2s).second ))
4647           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
4648           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
4649           // by StdMeshers_QuadToTriaAdaptor
4650           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
4651           {
4652             SMESH_ProxyMesh::SubMesh* proxySub =
4653               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
4654             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4655             while ( fIt->more() )
4656               proxySub->AddElement( fIt->next() );
4657             // as a result 3D algo will use elements from proxySub and not from smDS
4658           }
4659       }
4660   }
4661
4662   SMESH_MesherHelper helper( *_mesh );
4663   helper.ToFixNodeParameters( true );
4664
4665   // EDGE's to shrink
4666   map< TGeomID, _Shrinker1D > e2shrMap;
4667
4668   // loop on FACES to srink mesh on
4669   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
4670   for ( ; f2sd != f2sdMap.end(); ++f2sd )
4671   {
4672     _SolidData&     data = *f2sd->second;
4673     TNode2Edge&   n2eMap = data._n2eMap;
4674     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
4675
4676     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
4677
4678     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
4679     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
4680
4681     helper.SetSubShape(F);
4682
4683     // ===========================
4684     // Prepare data for shrinking
4685     // ===========================
4686
4687     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
4688     // and thus all nodes on a FACE connected to 2d elements are to be smoothed
4689     vector < const SMDS_MeshNode* > smoothNodes;
4690     {
4691       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
4692       while ( nIt->more() )
4693       {
4694         const SMDS_MeshNode* n = nIt->next();
4695         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
4696           smoothNodes.push_back( n );
4697       }
4698     }
4699     // Find out face orientation
4700     double refSign = 1;
4701     const set<TGeomID> ignoreShapes;
4702     bool isOkUV;
4703     if ( !smoothNodes.empty() )
4704     {
4705       vector<_Simplex> simplices;
4706       getSimplices( smoothNodes[0], simplices, ignoreShapes );
4707       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
4708       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
4709       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
4710       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
4711         refSign = -1;
4712     }
4713
4714     // Find _LayerEdge's inflated along F
4715     vector< _LayerEdge* > lEdges;
4716     {
4717       SMESH_subMeshIteratorPtr subIt =
4718         sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
4719       while ( subIt->more() )
4720       {
4721         SMESH_subMesh*     sub = subIt->next();
4722         SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
4723         if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
4724           continue;
4725         SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
4726         while ( nIt->more() )
4727         {
4728           _LayerEdge* edge = n2eMap[ nIt->next() ];
4729           lEdges.push_back( edge );
4730           prepareEdgeToShrink( *edge, F, helper, smDS );
4731         }
4732       }
4733     }
4734
4735     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
4736     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4737     while ( fIt->more() )
4738       if ( const SMDS_MeshElement* f = fIt->next() )
4739         dumpChangeNodes( f );
4740
4741     // Replace source nodes by target nodes in mesh faces to shrink
4742     const SMDS_MeshNode* nodes[20];
4743     for ( size_t i = 0; i < lEdges.size(); ++i )
4744     {
4745       _LayerEdge& edge = *lEdges[i];
4746       const SMDS_MeshNode* srcNode = edge._nodes[0];
4747       const SMDS_MeshNode* tgtNode = edge._nodes.back();
4748       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4749       while ( fIt->more() )
4750       {
4751         const SMDS_MeshElement* f = fIt->next();
4752         if ( !smDS->Contains( f ))
4753           continue;
4754         SMDS_NodeIteratorPtr nIt = f->nodeIterator();
4755         for ( int iN = 0; nIt->more(); ++iN )
4756         {
4757           const SMDS_MeshNode* n = nIt->next();
4758           nodes[iN] = ( n == srcNode ? tgtNode : n );
4759         }
4760         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
4761       }
4762     }
4763
4764     // find out if a FACE is concave
4765     const bool isConcaveFace = isConcave( F, helper );
4766
4767     // Create _SmoothNode's on face F
4768     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
4769     {
4770       const bool sortSimplices = isConcaveFace;
4771       for ( size_t i = 0; i < smoothNodes.size(); ++i )
4772       {
4773         const SMDS_MeshNode* n = smoothNodes[i];
4774         nodesToSmooth[ i ]._node = n;
4775         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
4776         getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
4777         // fix up incorrect uv of nodes on the FACE
4778         helper.GetNodeUV( F, n, 0, &isOkUV);
4779         dumpMove( n );
4780       }
4781     }
4782     //if ( nodesToSmooth.empty() ) continue;
4783
4784     // Find EDGE's to shrink and set simpices to LayerEdge's
4785     set< _Shrinker1D* > eShri1D;
4786     {
4787       for ( size_t i = 0; i < lEdges.size(); ++i )
4788       {
4789         _LayerEdge* edge = lEdges[i];
4790         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4791         {
4792           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4793           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4794           eShri1D.insert( & srinker );
4795           srinker.AddEdge( edge, helper );
4796           VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4797           // restore params of nodes on EGDE if the EDGE has been already
4798           // srinked while srinking another FACE
4799           srinker.RestoreParams();
4800         }
4801         getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4802       }
4803     }
4804
4805     bool toFixTria = false; // to improve quality of trias by diagonal swap
4806     if ( isConcaveFace )
4807     {
4808       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4809       if ( hasTria != hasQuad ) {
4810         toFixTria = hasTria;
4811       }
4812       else {
4813         set<int> nbNodesSet;
4814         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4815         while ( fIt->more() && nbNodesSet.size() < 2 )
4816           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4817         toFixTria = ( *nbNodesSet.begin() == 3 );
4818       }
4819     }
4820
4821     // ==================
4822     // Perform shrinking
4823     // ==================
4824
4825     bool shrinked = true;
4826     int badNb, shriStep=0, smooStep=0;
4827     _SmoothNode::SmoothType smoothType
4828       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4829     while ( shrinked )
4830     {
4831       shriStep++;
4832       // Move boundary nodes (actually just set new UV)
4833       // -----------------------------------------------
4834       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4835       shrinked = false;
4836       for ( size_t i = 0; i < lEdges.size(); ++i )
4837       {
4838         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4839       }
4840       dumpFunctionEnd();
4841
4842       // Move nodes on EDGE's
4843       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4844       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4845       for ( ; shr != eShri1D.end(); ++shr )
4846         (*shr)->Compute( /*set3D=*/false, helper );
4847
4848       // Smoothing in 2D
4849       // -----------------
4850       int nbNoImpSteps = 0;
4851       bool       moved = true;
4852       badNb = 1;
4853       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4854       {
4855         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4856
4857         int oldBadNb = badNb;
4858         badNb = 0;
4859         moved = false;
4860         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4861         {
4862           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4863                                             smoothType, /*set3D=*/isConcaveFace);
4864         }
4865         if ( badNb < oldBadNb )
4866           nbNoImpSteps = 0;
4867         else
4868           nbNoImpSteps++;
4869
4870         dumpFunctionEnd();
4871       }
4872       if ( badNb > 0 )
4873         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4874       if ( shriStep > 200 )
4875         return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4876
4877       // Fix narrow triangles by swapping diagonals
4878       // ---------------------------------------
4879       if ( toFixTria )
4880       {
4881         set<const SMDS_MeshNode*> usedNodes;
4882         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4883
4884         // update working data
4885         set<const SMDS_MeshNode*>::iterator n;
4886         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4887         {
4888           n = usedNodes.find( nodesToSmooth[ i ]._node );
4889           if ( n != usedNodes.end())
4890           {
4891             getSimplices( nodesToSmooth[ i ]._node,
4892                           nodesToSmooth[ i ]._simplices,
4893                           ignoreShapes, NULL,
4894                           /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4895             usedNodes.erase( n );
4896           }
4897         }
4898         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4899         {
4900           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4901           if ( n != usedNodes.end())
4902           {
4903             getSimplices( lEdges[i]->_nodes.back(),
4904                           lEdges[i]->_simplices,
4905                           ignoreShapes );
4906             usedNodes.erase( n );
4907           }
4908         }
4909       }
4910     } // while ( shrinked )
4911
4912     // No wrongly shaped faces remain; final smooth. Set node XYZ.
4913     bool isStructuredFixed = false;
4914     if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4915       isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4916     if ( !isStructuredFixed )
4917     {
4918       if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4919         fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4920
4921       for ( int st = 3; st; --st )
4922       {
4923         switch( st ) {
4924         case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4925         case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4926         case 3: smoothType = _SmoothNode::ANGULAR; break;
4927         }
4928         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4929         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4930         {
4931           nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4932                                    smoothType,/*set3D=*/st==1 );
4933         }
4934         dumpFunctionEnd();
4935       }
4936     }
4937     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4938     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4939
4940     if ( !getMeshDS()->IsEmbeddedMode() )
4941       // Log node movement
4942       for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4943       {
4944         SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4945         getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4946       }
4947
4948   } // loop on FACES to srink mesh on
4949
4950
4951   // Replace source nodes by target nodes in shrinked mesh edges
4952
4953   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4954   for ( ; e2shr != e2shrMap.end(); ++e2shr )
4955     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4956
4957   return true;
4958 }
4959
4960 //================================================================================
4961 /*!
4962  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4963  */
4964 //================================================================================
4965
4966 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
4967                                            const TopoDS_Face&     F,
4968                                            SMESH_MesherHelper&    helper,
4969                                            const SMESHDS_SubMesh* faceSubMesh)
4970 {
4971   const SMDS_MeshNode* srcNode = edge._nodes[0];
4972   const SMDS_MeshNode* tgtNode = edge._nodes.back();
4973
4974   edge._pos.clear();
4975
4976   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4977   {
4978     gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4979     gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4980     gp_Vec2d uvDir( srcUV, tgtUV );
4981     double uvLen = uvDir.Magnitude();
4982     uvDir /= uvLen;
4983     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4984     edge._len = uvLen;
4985
4986     edge._pos.resize(1);
4987     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4988
4989     // set UV of source node to target node
4990     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4991     pos->SetUParameter( srcUV.X() );
4992     pos->SetVParameter( srcUV.Y() );
4993   }
4994   else // _sWOL is TopAbs_EDGE
4995   {
4996     TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4997     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4998     if ( !edgeSM || edgeSM->NbElements() == 0 )
4999       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
5000
5001     const SMDS_MeshNode* n2 = 0;
5002     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5003     while ( eIt->more() && !n2 )
5004     {
5005       const SMDS_MeshElement* e = eIt->next();
5006       if ( !edgeSM->Contains(e)) continue;
5007       n2 = e->GetNode( 0 );
5008       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
5009     }
5010     if ( !n2 )
5011       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
5012
5013     double uSrc = helper.GetNodeU( E, srcNode, n2 );
5014     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
5015     double u2   = helper.GetNodeU( E, n2,      srcNode );
5016
5017     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
5018     {
5019       // tgtNode is located so that it does not make faces with wrong orientation
5020       return true;
5021     }
5022     edge._pos.resize(1);
5023     edge._pos[0].SetCoord( U_TGT, uTgt );
5024     edge._pos[0].SetCoord( U_SRC, uSrc );
5025     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
5026
5027     edge._simplices.resize( 1 );
5028     edge._simplices[0]._nPrev = n2;
5029
5030     // set UV of source node to target node
5031     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
5032     pos->SetUParameter( uSrc );
5033   }
5034   return true;
5035 }
5036
5037 //================================================================================
5038 /*!
5039  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
5040  */
5041 //================================================================================
5042
5043 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
5044                                   SMESH_MesherHelper&         helper,
5045                                   const bool                  is2D,
5046                                   const int                   step,
5047                                   set<const SMDS_MeshNode*> * involvedNodes)
5048 {
5049   SMESH::Controls::AspectRatio qualifier;
5050   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
5051   const double maxAspectRatio = is2D ? 4. : 2;
5052   _NodeCoordHelper xyz( F, helper, is2D );
5053
5054   // find bad triangles
5055
5056   vector< const SMDS_MeshElement* > badTrias;
5057   vector< double >                  badAspects;
5058   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
5059   SMDS_ElemIteratorPtr fIt = sm->GetElements();
5060   while ( fIt->more() )
5061   {
5062     const SMDS_MeshElement * f = fIt->next();
5063     if ( f->NbCornerNodes() != 3 ) continue;
5064     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
5065     double aspect = qualifier.GetValue( points );
5066     if ( aspect > maxAspectRatio )
5067     {
5068       badTrias.push_back( f );
5069       badAspects.push_back( aspect );
5070     }
5071   }
5072   if ( step == 1 )
5073   {
5074     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
5075     SMDS_ElemIteratorPtr fIt = sm->GetElements();
5076     while ( fIt->more() )
5077     {
5078       const SMDS_MeshElement * f = fIt->next();
5079       if ( f->NbCornerNodes() == 3 )
5080         dumpChangeNodes( f );
5081     }
5082     dumpFunctionEnd();
5083   }
5084   if ( badTrias.empty() )
5085     return;
5086
5087   // find couples of faces to swap diagonal
5088
5089   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
5090   vector< T2Trias > triaCouples; 
5091
5092   TIDSortedElemSet involvedFaces, emptySet;
5093   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
5094   {
5095     T2Trias trias    [3];
5096     double  aspRatio [3];
5097     int i1, i2, i3;
5098
5099     if ( !involvedFaces.insert( badTrias[iTia] ).second )
5100       continue;
5101     for ( int iP = 0; iP < 3; ++iP )
5102       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
5103
5104     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
5105     int bestCouple = -1;
5106     for ( int iSide = 0; iSide < 3; ++iSide )
5107     {
5108       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
5109       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
5110       trias [iSide].first  = badTrias[iTia];
5111       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
5112                                                              & i1, & i2 );
5113       if (( ! trias[iSide].second ) ||
5114           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
5115           ( ! sm->Contains( trias[iSide].second )))
5116         continue;
5117
5118       // aspect ratio of an adjacent tria
5119       for ( int iP = 0; iP < 3; ++iP )
5120         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
5121       double aspectInit = qualifier.GetValue( points2 );
5122
5123       // arrange nodes as after diag-swaping
5124       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
5125         i3 = helper.WrapIndex( i1-1, 3 );
5126       else
5127         i3 = helper.WrapIndex( i1+1, 3 );
5128       points1 = points;
5129       points1( 1+ iSide ) = points2( 1+ i3 );
5130       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
5131
5132       // aspect ratio after diag-swaping
5133       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
5134       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
5135         continue;
5136
5137       // prevent inversion of a triangle
5138       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
5139       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
5140       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
5141         continue;
5142
5143       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
5144         bestCouple = iSide;
5145     }
5146
5147     if ( bestCouple >= 0 )
5148     {
5149       triaCouples.push_back( trias[bestCouple] );
5150       involvedFaces.insert ( trias[bestCouple].second );
5151     }
5152     else
5153     {
5154       involvedFaces.erase( badTrias[iTia] );
5155     }
5156   }
5157   if ( triaCouples.empty() )
5158     return;
5159
5160   // swap diagonals
5161
5162   SMESH_MeshEditor editor( helper.GetMesh() );
5163   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
5164   for ( size_t i = 0; i < triaCouples.size(); ++i )
5165   {
5166     dumpChangeNodes( triaCouples[i].first );
5167     dumpChangeNodes( triaCouples[i].second );
5168     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
5169   }
5170
5171   if ( involvedNodes )
5172     for ( size_t i = 0; i < triaCouples.size(); ++i )
5173     {
5174       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
5175                              triaCouples[i].first->end_nodes() );
5176       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
5177                              triaCouples[i].second->end_nodes() );
5178     }
5179
5180   // just for debug dump resulting triangles
5181   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
5182   for ( size_t i = 0; i < triaCouples.size(); ++i )
5183   {
5184     dumpChangeNodes( triaCouples[i].first );
5185     dumpChangeNodes( triaCouples[i].second );
5186   }
5187 }
5188
5189 //================================================================================
5190 /*!
5191  * \brief Move target node to it's final position on the FACE during shrinking
5192  */
5193 //================================================================================
5194
5195 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
5196                                  const TopoDS_Face&    F,
5197                                  SMESH_MesherHelper&   helper )
5198 {
5199   if ( _pos.empty() )
5200     return false; // already at the target position
5201
5202   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
5203
5204   if ( _sWOL.ShapeType() == TopAbs_FACE )
5205   {
5206     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
5207     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
5208     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
5209     const double uvLen = tgtUV.Distance( curUV );
5210     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
5211
5212     // Select shrinking step such that not to make faces with wrong orientation.
5213     double stepSize = uvLen;
5214     for ( size_t i = 0; i < _simplices.size(); ++i )
5215     {
5216       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
5217       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
5218       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
5219       gp_XY dirN = uvN2 - uvN1;
5220       double det = uvDir.Crossed( dirN );
5221       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
5222       gp_XY dirN2Cur = curUV - uvN1;
5223       double step = dirN.Crossed( dirN2Cur ) / det;
5224       if ( step > 0 )
5225         stepSize = Min( step, stepSize );
5226     }
5227     gp_Pnt2d newUV;
5228     if ( uvLen - stepSize < _len / 200. )
5229     {
5230       newUV = tgtUV;
5231       _pos.clear();
5232     }
5233     else if ( stepSize > 0 )
5234     {
5235       newUV = curUV + uvDir.XY() * stepSize * kSafe;
5236     }
5237     else
5238     {
5239       return true;
5240     }
5241     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5242     pos->SetUParameter( newUV.X() );
5243     pos->SetVParameter( newUV.Y() );
5244
5245 #ifdef __myDEBUG
5246     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
5247     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5248     dumpMove( tgtNode );
5249 #endif
5250   }
5251   else // _sWOL is TopAbs_EDGE
5252   {
5253     TopoDS_Edge E = TopoDS::Edge( _sWOL );
5254     const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
5255     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
5256
5257     const double u2 = helper.GetNodeU( E, n2, tgtNode );
5258     const double uSrc   = _pos[0].Coord( U_SRC );
5259     const double lenTgt = _pos[0].Coord( LEN_TGT );
5260
5261     double newU = _pos[0].Coord( U_TGT );
5262     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
5263     {
5264       _pos.clear();
5265     }
5266     else
5267     {
5268       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
5269     }
5270     tgtPos->SetUParameter( newU );
5271 #ifdef __myDEBUG
5272     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
5273     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
5274     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5275     dumpMove( tgtNode );
5276 #endif
5277   }
5278   return true;
5279 }
5280
5281 //================================================================================
5282 /*!
5283  * \brief Perform smooth on the FACE
5284  *  \retval bool - true if the node has been moved
5285  */
5286 //================================================================================
5287
5288 bool _SmoothNode::Smooth(int&                  badNb,
5289                          Handle(Geom_Surface)& surface,
5290                          SMESH_MesherHelper&   helper,
5291                          const double          refSign,
5292                          SmoothType            how,
5293                          bool                  set3D)
5294 {
5295   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
5296
5297   // get uv of surrounding nodes
5298   vector<gp_XY> uv( _simplices.size() );
5299   for ( size_t i = 0; i < _simplices.size(); ++i )
5300     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
5301
5302   // compute new UV for the node
5303   gp_XY newPos (0,0);
5304   if ( how == TFI && _simplices.size() == 4 )
5305   {
5306     gp_XY corners[4];
5307     for ( size_t i = 0; i < _simplices.size(); ++i )
5308       if ( _simplices[i]._nOpp )
5309         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
5310       else
5311         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
5312
5313     newPos = helper.calcTFI ( 0.5, 0.5,
5314                               corners[0], corners[1], corners[2], corners[3],
5315                               uv[1], uv[2], uv[3], uv[0] );
5316   }
5317   else if ( how == ANGULAR )
5318   {
5319     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
5320   }
5321   else if ( how == CENTROIDAL && _simplices.size() > 3 )
5322   {
5323     // average centers of diagonals wieghted with their reciprocal lengths
5324     if ( _simplices.size() == 4 )
5325     {
5326       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
5327       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
5328       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
5329     }
5330     else
5331     {
5332       double sumWeight = 0;
5333       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
5334       for ( int i = 0; i < nb; ++i )
5335       {
5336         int iFrom = i + 2;
5337         int iTo   = i + _simplices.size() - 1;
5338         for ( int j = iFrom; j < iTo; ++j )
5339         {
5340           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
5341           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
5342           sumWeight += w;
5343           newPos += w * ( uv[i]+uv[i2] );
5344         }
5345       }
5346       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
5347     }
5348   }
5349   else
5350   {
5351     // Laplacian smooth
5352     for ( size_t i = 0; i < _simplices.size(); ++i )
5353       newPos += uv[i];
5354     newPos /= _simplices.size();
5355   }
5356
5357   // count quality metrics (orientation) of triangles around the node
5358   int nbOkBefore = 0;
5359   gp_XY tgtUV = helper.GetNodeUV( face, _node );
5360   for ( size_t i = 0; i < _simplices.size(); ++i )
5361     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
5362
5363   int nbOkAfter = 0;
5364   for ( size_t i = 0; i < _simplices.size(); ++i )
5365     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
5366
5367   if ( nbOkAfter < nbOkBefore )
5368   {
5369     badNb += _simplices.size() - nbOkBefore;
5370     return false;
5371   }
5372
5373   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
5374   pos->SetUParameter( newPos.X() );
5375   pos->SetVParameter( newPos.Y() );
5376
5377 #ifdef __myDEBUG
5378   set3D = true;
5379 #endif
5380   if ( set3D )
5381   {
5382     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
5383     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
5384     dumpMove( _node );
5385   }
5386
5387   badNb += _simplices.size() - nbOkAfter;
5388   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
5389 }
5390
5391 //================================================================================
5392 /*!
5393  * \brief Computes new UV using angle based smoothing technic
5394  */
5395 //================================================================================
5396
5397 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
5398                                      const gp_XY&   uvToFix,
5399                                      const double   refSign)
5400 {
5401   uv.push_back( uv.front() );
5402
5403   vector< gp_XY >  edgeDir ( uv.size() );
5404   vector< double > edgeSize( uv.size() );
5405   for ( size_t i = 1; i < edgeDir.size(); ++i )
5406   {
5407     edgeDir [i-1] = uv[i] - uv[i-1];
5408     edgeSize[i-1] = edgeDir[i-1].Modulus();
5409     if ( edgeSize[i-1] < numeric_limits<double>::min() )
5410       edgeDir[i-1].SetX( 100 );
5411     else
5412       edgeDir[i-1] /= edgeSize[i-1] * refSign;
5413   }
5414   edgeDir.back()  = edgeDir.front();
5415   edgeSize.back() = edgeSize.front();
5416
5417   gp_XY  newPos(0,0);
5418   int    nbEdges = 0;
5419   double sumSize = 0;
5420   for ( size_t i = 1; i < edgeDir.size(); ++i )
5421   {
5422     if ( edgeDir[i-1].X() > 1. ) continue;
5423     int i1 = i-1;
5424     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
5425     if ( i == edgeDir.size() ) break;
5426     gp_XY p = uv[i];
5427     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
5428     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
5429     gp_XY bisec = norm1 + norm2;
5430     double bisecSize = bisec.Modulus();
5431     if ( bisecSize < numeric_limits<double>::min() )
5432     {
5433       bisec = -edgeDir[i1] + edgeDir[i];
5434       bisecSize = bisec.Modulus();
5435     }
5436     bisec /= bisecSize;
5437
5438     gp_XY  dirToN  = uvToFix - p;
5439     double distToN = dirToN.Modulus();
5440     if ( bisec * dirToN < 0 )
5441       distToN = -distToN;
5442
5443     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
5444     ++nbEdges;
5445     sumSize += edgeSize[i1] + edgeSize[i];
5446   }
5447   newPos /= /*nbEdges * */sumSize;
5448   return newPos;
5449 }
5450
5451 //================================================================================
5452 /*!
5453  * \brief Delete _SolidData
5454  */
5455 //================================================================================
5456
5457 _SolidData::~_SolidData()
5458 {
5459   for ( size_t i = 0; i < _edges.size(); ++i )
5460   {
5461     if ( _edges[i] && _edges[i]->_2neibors )
5462       delete _edges[i]->_2neibors;
5463     delete _edges[i];
5464   }
5465   _edges.clear();
5466 }
5467 //================================================================================
5468 /*!
5469  * \brief Add a _LayerEdge inflated along the EDGE
5470  */
5471 //================================================================================
5472
5473 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
5474 {
5475   // init
5476   if ( _nodes.empty() )
5477   {
5478     _edges[0] = _edges[1] = 0;
5479     _done = false;
5480   }
5481   // check _LayerEdge
5482   if ( e == _edges[0] || e == _edges[1] )
5483     return;
5484   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
5485     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
5486   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
5487     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
5488
5489   // store _LayerEdge
5490   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
5491   double f,l;
5492   BRep_Tool::Range( E, f,l );
5493   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
5494   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
5495
5496   // Update _nodes
5497
5498   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
5499   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
5500
5501   if ( _nodes.empty() )
5502   {
5503     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
5504     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
5505       return;
5506     TopLoc_Location loc;
5507     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
5508     GeomAdaptor_Curve aCurve(C, f,l);
5509     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
5510
5511     int nbExpectNodes = eSubMesh->NbNodes();
5512     _initU  .reserve( nbExpectNodes );
5513     _normPar.reserve( nbExpectNodes );
5514     _nodes  .reserve( nbExpectNodes );
5515     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
5516     while ( nIt->more() )
5517     {
5518       const SMDS_MeshNode* node = nIt->next();
5519       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
5520            node == tgtNode0 || node == tgtNode1 )
5521         continue; // refinement nodes
5522       _nodes.push_back( node );
5523       _initU.push_back( helper.GetNodeU( E, node ));
5524       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
5525       _normPar.push_back(  len / totLen );
5526     }
5527   }
5528   else
5529   {
5530     // remove target node of the _LayerEdge from _nodes
5531     int nbFound = 0;
5532     for ( size_t i = 0; i < _nodes.size(); ++i )
5533       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
5534         _nodes[i] = 0, nbFound++;
5535     if ( nbFound == _nodes.size() )
5536       _nodes.clear();
5537   }
5538 }
5539
5540 //================================================================================
5541 /*!
5542  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
5543  */
5544 //================================================================================
5545
5546 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
5547 {
5548   if ( _done || _nodes.empty())
5549     return;
5550   const _LayerEdge* e = _edges[0];
5551   if ( !e ) e = _edges[1];
5552   if ( !e ) return;
5553
5554   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
5555             ( !_edges[1] || _edges[1]->_pos.empty() ));
5556
5557   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
5558   double f,l;
5559   if ( set3D || _done )
5560   {
5561     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
5562     GeomAdaptor_Curve aCurve(C, f,l);
5563
5564     if ( _edges[0] )
5565       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
5566     if ( _edges[1] )
5567       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
5568     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
5569
5570     for ( size_t i = 0; i < _nodes.size(); ++i )
5571     {
5572       if ( !_nodes[i] ) continue;
5573       double len = totLen * _normPar[i];
5574       GCPnts_AbscissaPoint discret( aCurve, len, f );
5575       if ( !discret.IsDone() )
5576         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
5577       double u = discret.Parameter();
5578       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
5579       pos->SetUParameter( u );
5580       gp_Pnt p = C->Value( u );
5581       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
5582     }
5583   }
5584   else
5585   {
5586     BRep_Tool::Range( E, f,l );
5587     if ( _edges[0] )
5588       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
5589     if ( _edges[1] )
5590       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
5591     
5592     for ( size_t i = 0; i < _nodes.size(); ++i )
5593     {
5594       if ( !_nodes[i] ) continue;
5595       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
5596       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
5597       pos->SetUParameter( u );
5598     }
5599   }
5600 }
5601
5602 //================================================================================
5603 /*!
5604  * \brief Restore initial parameters of nodes on EDGE
5605  */
5606 //================================================================================
5607
5608 void _Shrinker1D::RestoreParams()
5609 {
5610   if ( _done )
5611     for ( size_t i = 0; i < _nodes.size(); ++i )
5612     {
5613       if ( !_nodes[i] ) continue;
5614       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
5615       pos->SetUParameter( _initU[i] );
5616     }
5617   _done = false;
5618 }
5619
5620 //================================================================================
5621 /*!
5622  * \brief Replace source nodes by target nodes in shrinked mesh edges
5623  */
5624 //================================================================================
5625
5626 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
5627 {
5628   const SMDS_MeshNode* nodes[3];
5629   for ( int i = 0; i < 2; ++i )
5630   {
5631     if ( !_edges[i] ) continue;
5632
5633     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
5634     if ( !eSubMesh ) return;
5635     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
5636     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
5637     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
5638     while ( eIt->more() )
5639     {
5640       const SMDS_MeshElement* e = eIt->next();
5641       if ( !eSubMesh->Contains( e ))
5642           continue;
5643       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
5644       for ( int iN = 0; iN < e->NbNodes(); ++iN )
5645       {
5646         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
5647         nodes[iN] = ( n == srcNode ? tgtNode : n );
5648       }
5649       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
5650     }
5651   }
5652 }
5653
5654 //================================================================================
5655 /*!
5656  * \brief Creates 2D and 1D elements on boundaries of new prisms
5657  */
5658 //================================================================================
5659
5660 bool _ViscousBuilder::addBoundaryElements()
5661 {
5662   SMESH_MesherHelper helper( *_mesh );
5663
5664   for ( size_t i = 0; i < _sdVec.size(); ++i )
5665   {
5666     _SolidData& data = _sdVec[i];
5667     TopTools_IndexedMapOfShape geomEdges;
5668     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
5669     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
5670     {
5671       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
5672
5673       // Get _LayerEdge's based on E
5674
5675       map< double, const SMDS_MeshNode* > u2nodes;
5676       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
5677         continue;
5678
5679       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
5680       TNode2Edge & n2eMap = data._n2eMap;
5681       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5682       {
5683         //check if 2D elements are needed on E
5684         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5685         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5686         ledges.push_back( n2e->second );
5687         u2n++;
5688         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5689           continue; // no layers on E
5690         ledges.push_back( n2eMap[ u2n->second ]);
5691
5692         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5693         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5694         int nbSharedPyram = 0;
5695         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5696         while ( vIt->more() )
5697         {
5698           const SMDS_MeshElement* v = vIt->next();
5699           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5700         }
5701         if ( nbSharedPyram > 1 )
5702           continue; // not free border of the pyramid
5703
5704         if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5705                                     ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5706           continue; // faces already created
5707       }
5708       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5709         ledges.push_back( n2eMap[ u2n->second ]);
5710
5711       // Find out orientation and type of face to create
5712
5713       bool reverse = false, isOnFace;
5714       
5715       map< TGeomID, TopoDS_Shape >::iterator e2f =
5716         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5717       TopoDS_Shape F;
5718       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5719       {
5720         F = e2f->second.Oriented( TopAbs_FORWARD );
5721         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5722         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5723           reverse = !reverse, F.Reverse();
5724         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5725           reverse = !reverse;
5726       }
5727       else
5728       {
5729         // find FACE with layers sharing E
5730         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5731         while ( fIt->more() && F.IsNull() )
5732         {
5733           const TopoDS_Shape* pF = fIt->next();
5734           if ( helper.IsSubShape( *pF, data._solid) &&
5735                !data._ignoreFaceIds.count( e2f->first ))
5736             F = *pF;
5737         }
5738       }
5739       // Find the sub-mesh to add new faces
5740       SMESHDS_SubMesh* sm = 0;
5741       if ( isOnFace )
5742         sm = getMeshDS()->MeshElements( F );
5743       else
5744         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5745       if ( !sm )
5746         return error("error in addBoundaryElements()", data._index);
5747
5748       // Make faces
5749       const int dj1 = reverse ? 0 : 1;
5750       const int dj2 = reverse ? 1 : 0;
5751       for ( size_t j = 1; j < ledges.size(); ++j )
5752       {
5753         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
5754         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
5755         if ( isOnFace )
5756           for ( size_t z = 1; z < nn1.size(); ++z )
5757             sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5758         else
5759           for ( size_t z = 1; z < nn1.size(); ++z )
5760             sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5761       }
5762
5763       // Make edges
5764       for ( int isFirst = 0; isFirst < 2; ++isFirst )
5765       {
5766         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5767         if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5768         {
5769           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
5770           if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5771             continue;
5772           helper.SetSubShape( edge->_sWOL );
5773           helper.SetElementsOnShape( true );
5774           for ( size_t z = 1; z < nn.size(); ++z )
5775             helper.AddEdge( nn[z-1], nn[z] );
5776         }
5777       }
5778     }
5779   }
5780
5781   return true;
5782 }