Salome HOME
1ebf95af9e79c847b7f01659c13ad0e6ebd68cb6
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  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 "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
48
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
59 #include <ElCLib.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
85 #include <gp_Ax1.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
88 #include <gp_Vec.hxx>
89 #include <gp_XY.hxx>
90
91 #include <cmath>
92 #include <limits>
93 #include <list>
94 #include <queue>
95 #include <string>
96
97 #ifdef _DEBUG_
98 //#define __myDEBUG
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
101 #endif
102
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
106
107 using namespace std;
108
109 //================================================================================
110 namespace VISCOUS_3D
111 {
112   typedef int TGeomID;
113
114   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
115
116   const double theMinSmoothCosin = 0.1;
117   const double theSmoothThickToElemSizeRatio = 0.3;
118   const double theMinSmoothTriaAngle = 30;
119   const double theMinSmoothQuadAngle = 45;
120
121   // what part of thickness is allowed till intersection
122   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123   const double theThickToIntersection = 1.5;
124
125   bool needSmoothing( double cosin, double tgtThick, double elemSize )
126   {
127     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
128   }
129   double getSmoothingThickness( double cosin, double elemSize )
130   {
131     return theSmoothThickToElemSizeRatio * elemSize / cosin;
132   }
133
134   /*!
135    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
137    */
138   struct _MeshOfSolid : public SMESH_ProxyMesh,
139                         public SMESH_subMeshEventListenerData
140   {
141     bool                  _n2nMapComputed;
142     SMESH_ComputeErrorPtr _warning;
143
144     _MeshOfSolid( SMESH_Mesh* mesh)
145       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
146     {
147       SMESH_ProxyMesh::setMesh( *mesh );
148     }
149
150     // returns submesh for a geom face
151     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
152     {
153       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
155     }
156     void setNode2Node(const SMDS_MeshNode*                 srcNode,
157                       const SMDS_MeshNode*                 proxyNode,
158                       const SMESH_ProxyMesh::SubMesh* subMesh)
159     {
160       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
161     }
162   };
163   //--------------------------------------------------------------------------------
164   /*!
165    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166    * It is used to clear an inferior dim sub-meshes modified by viscous layers
167    */
168   class _ShrinkShapeListener : SMESH_subMeshEventListener
169   {
170     _ShrinkShapeListener()
171       : SMESH_subMeshEventListener(/*isDeletable=*/false,
172                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
173   public:
174     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175     virtual void ProcessEvent(const int                       event,
176                               const int                       eventType,
177                               SMESH_subMesh*                  solidSM,
178                               SMESH_subMeshEventListenerData* data,
179                               const SMESH_Hypothesis*         hyp)
180     {
181       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
182       {
183         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
184       }
185     }
186   };
187   //--------------------------------------------------------------------------------
188   /*!
189    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191    * delete the data as soon as it has been used
192    */
193   class _ViscousListener : SMESH_subMeshEventListener
194   {
195     _ViscousListener():
196       SMESH_subMeshEventListener(/*isDeletable=*/false,
197                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
198     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
199   public:
200     virtual void ProcessEvent(const int                       event,
201                               const int                       eventType,
202                               SMESH_subMesh*                  subMesh,
203                               SMESH_subMeshEventListenerData* data,
204                               const SMESH_Hypothesis*         hyp)
205     {
206       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
207           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
209       {
210         // delete SMESH_ProxyMesh containing temporary faces
211         subMesh->DeleteEventListener( this );
212       }
213     }
214     // Finds or creates proxy mesh of the solid
215     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
216                                       const TopoDS_Shape& solid,
217                                       bool                toCreate=false)
218     {
219       if ( !mesh ) return 0;
220       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222       if ( !data && toCreate )
223       {
224         data = new _MeshOfSolid(mesh);
225         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226         sm->SetEventListener( Get(), data, sm );
227       }
228       return data;
229     }
230     // Removes proxy mesh of the solid
231     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
232     {
233       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
234     }
235   };
236   
237   //================================================================================
238   /*!
239    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240    * the main shape when sub-mesh of the main shape is cleared,
241    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
242    * is cleared
243    */
244   //================================================================================
245
246   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
247   {
248     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249     SMESH_subMeshEventListenerData* data =
250       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
251     if ( data )
252     {
253       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254            data->mySubMeshes.end())
255         data->mySubMeshes.push_back( sub );
256     }
257     else
258     {
259       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
261     }
262   }
263   struct _SolidData;
264   //--------------------------------------------------------------------------------
265   /*!
266    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268    * The class is used to check validity of face or volumes around a smoothed node;
269    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
270    */
271   struct _Simplex
272   {
273     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275     _Simplex(const SMDS_MeshNode* nPrev=0,
276              const SMDS_MeshNode* nNext=0,
277              const SMDS_MeshNode* nOpp=0)
278       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
280     {
281       const double M[3][3] =
282         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285       vol = ( + M[0][0] * M[1][1] * M[2][2]
286               + M[0][1] * M[1][2] * M[2][0]
287               + M[0][2] * M[1][0] * M[2][1]
288               - M[0][0] * M[1][2] * M[2][1]
289               - M[0][1] * M[1][0] * M[2][2]
290               - M[0][2] * M[1][1] * M[2][0]);
291       return vol > 1e-100;
292     }
293     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
294     {
295       SMESH_TNodeXYZ pSrc( nSrc );
296       return IsForward( &pSrc, &pTgt, vol );
297     }
298     bool IsForward(const gp_XY&         tgtUV,
299                    const SMDS_MeshNode* smoothedNode,
300                    const TopoDS_Face&   face,
301                    SMESH_MesherHelper&  helper,
302                    const double         refSign) const
303     {
304       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
307       double d = v1 ^ v2;
308       return d*refSign > 1e-100;
309     }
310     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
311     {
312       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313       if ( !_nOpp ) // triangle
314       {
315         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316         double tp2 = tp.SquareMagnitude();
317         double pn2 = pn.SquareMagnitude();
318         double nt2 = nt.SquareMagnitude();
319
320         if ( tp2 < pn2 && tp2 < nt2 )
321           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322         else if ( pn2 < nt2 )
323           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
324         else
325           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
326
327         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329         return minAngle < theMaxCos2;
330       }
331       else // quadrangle
332       {
333         SMESH_TNodeXYZ pOpp( _nOpp );
334         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335         double tp2 = tp.SquareMagnitude();
336         double po2 = po.SquareMagnitude();
337         double on2 = on.SquareMagnitude();
338         double nt2 = nt.SquareMagnitude();
339         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
343
344         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346         return minAngle < theMaxCos2;
347       }
348     }
349     bool IsNeighbour(const _Simplex& other) const
350     {
351       return _nPrev == other._nNext || _nNext == other._nPrev;
352     }
353     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354     static void GetSimplices( const SMDS_MeshNode* node,
355                               vector<_Simplex>&   simplices,
356                               const set<TGeomID>& ingnoreShapes,
357                               const _SolidData*   dataToCheckOri = 0,
358                               const bool          toSort = false);
359     static void SortSimplices(vector<_Simplex>& simplices);
360   };
361   //--------------------------------------------------------------------------------
362   /*!
363    * Structure used to take into account surface curvature while smoothing
364    */
365   struct _Curvature
366   {
367     double   _r; // radius
368     double   _k; // factor to correct node smoothed position
369     double   _h2lenRatio; // avgNormProj / (2*avgDist)
370     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
371   public:
372     static _Curvature* New( double avgNormProj, double avgDist )
373     {
374       _Curvature* c = 0;
375       if ( fabs( avgNormProj / avgDist ) > 1./200 )
376       {
377         c = new _Curvature;
378         c->_r = avgDist * avgDist / avgNormProj;
379         c->_k = avgDist * avgDist / c->_r / c->_r;
380         //c->_k = avgNormProj / c->_r;
381         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
383
384         c->_uv.SetCoord( 0., 0. );
385       }
386       return c;
387     }
388     double lenDelta(double len) const { return _k * ( _r + len ); }
389     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
390   };
391   //--------------------------------------------------------------------------------
392
393   struct _2NearEdges;
394   struct _LayerEdge;
395   struct _EdgesOnShape;
396   struct _Smoother1D;
397   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
398
399   //--------------------------------------------------------------------------------
400   /*!
401    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402    * and a node of the most internal layer (_nodes.back())
403    */
404   struct _LayerEdge
405   {
406     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
407
408     vector< const SMDS_MeshNode*> _nodes;
409
410     gp_XYZ              _normal;    // to boundary of solid
411     vector<gp_XYZ>      _pos;       // points computed during inflation
412     double              _len;       // length achived with the last inflation step
413     double              _maxLen;    // maximal possible length
414     double              _cosin;     // of angle (_normal ^ surface)
415     double              _minAngle;  // of _simplices
416     double              _lenFactor; // to compute _len taking _cosin into account
417     int                 _flags;
418
419     // simplices connected to the source node (_nodes[0]);
420     // used for smoothing and quality check of _LayerEdge's based on the FACE
421     vector<_Simplex>    _simplices;
422     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423     PSmooFun            _smooFunction; // smoothing function
424     _Curvature*         _curvature;
425     // data for smoothing of _LayerEdge's based on the EDGE
426     _2NearEdges*        _2neibors;
427
428     enum EFlags { TO_SMOOTH       = 0x0000001,
429                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
430                   SMOOTHED        = 0x0000004, // set by this->Smooth()
431                   DIFFICULT       = 0x0000008, // near concave VERTEX
432                   ON_CONCAVE_FACE = 0x0000010,
433                   BLOCKED         = 0x0000020, // not to inflate any more
434                   INTERSECTED     = 0x0000040, // close intersection with a face found
435                   NORMAL_UPDATED  = 0x0000080,
436                   MARKED          = 0x0000100, // local usage
437                   MULTI_NORMAL    = 0x0000200, // a normal is invisible by some of surrounding faces
438                   NEAR_BOUNDARY   = 0x0000400, // is near FACE boundary forcing smooth
439                   SMOOTHED_C1     = 0x0000800, // is on _eosC1
440                   DISTORTED       = 0x0001000, // was bad before smoothing
441                   RISKY_SWOL      = 0x0002000, // SWOL is parallel to a source FACE
442                   UNUSED_FLAG     = 0x0100000
443     };
444     bool Is   ( int flag ) const { return _flags & flag; }
445     void Set  ( int flag ) { _flags |= flag; }
446     void Unset( int flag ) { _flags &= ~flag; }
447
448     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
449     bool SetNewLength2d( Handle(Geom_Surface)& surface,
450                          const TopoDS_Face&    F,
451                          _EdgesOnShape&        eos,
452                          SMESH_MesherHelper&   helper );
453     void SetDataByNeighbors( const SMDS_MeshNode* n1,
454                              const SMDS_MeshNode* n2,
455                              const _EdgesOnShape& eos,
456                              SMESH_MesherHelper&  helper);
457     void Block( _SolidData& data );
458     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
459     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
460                             const TNode2Edge&     n2eMap);
461     void SmoothPos( const vector< double >& segLen, const double tol );
462     int  GetSmoothedPos( const double tol );
463     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
464     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
465     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
466     void SmoothWoCheck();
467     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
468                       const TopoDS_Face&             F,
469                       SMESH_MesherHelper&            helper);
470     void MoveNearConcaVer( const _EdgesOnShape*    eov,
471                            const _EdgesOnShape*    eos,
472                            const int               step,
473                            vector< _LayerEdge* > & badSmooEdges);
474     bool FindIntersection( SMESH_ElementSearcher&   searcher,
475                            double &                 distance,
476                            const double&            epsilon,
477                            _EdgesOnShape&           eos,
478                            const SMDS_MeshElement** face = 0);
479     bool SegTriaInter( const gp_Ax1&        lastSegment,
480                        const gp_XYZ&        p0,
481                        const gp_XYZ&        p1,
482                        const gp_XYZ&        p2,
483                        double&              dist,
484                        const double&        epsilon) const;
485     bool SegTriaInter( const gp_Ax1&        lastSegment,
486                        const SMDS_MeshNode* n0,
487                        const SMDS_MeshNode* n1,
488                        const SMDS_MeshNode* n2,
489                        double&              dist,
490                        const double&        epsilon) const
491     { return SegTriaInter( lastSegment,
492                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
493                            dist, epsilon );
494     }
495     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
496     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
497     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
498     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
499     bool   IsOnEdge() const { return _2neibors; }
500     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
501     void   SetCosin( double cosin );
502     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
503     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
504     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
505     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
506       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
507     }
508     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
509
510     gp_XYZ smoothLaplacian();
511     gp_XYZ smoothAngular();
512     gp_XYZ smoothLengthWeighted();
513     gp_XYZ smoothCentroidal();
514     gp_XYZ smoothNefPolygon();
515
516     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
517     static const int theNbSmooFuns = FUN_NB;
518     static PSmooFun _funs[theNbSmooFuns];
519     static const char* _funNames[theNbSmooFuns+1];
520     int smooFunID( PSmooFun fun=0) const;
521   };
522   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
523                                                             &_LayerEdge::smoothLengthWeighted,
524                                                             &_LayerEdge::smoothCentroidal,
525                                                             &_LayerEdge::smoothNefPolygon,
526                                                             &_LayerEdge::smoothAngular };
527   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
528                                                          "LengthWeighted",
529                                                          "Centroidal",
530                                                          "NefPolygon",
531                                                          "Angular",
532                                                          "None"};
533   struct _LayerEdgeCmp
534   {
535     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
536     {
537       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
538       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
539     }
540   };
541   //--------------------------------------------------------------------------------
542   /*!
543    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
544    */
545   struct _halfPlane
546   {
547     gp_XY _pos, _dir, _inNorm;
548     bool IsOut( const gp_XY p, const double tol ) const
549     {
550       return _inNorm * ( p - _pos ) < -tol;
551     }
552     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
553     {
554       //const double eps = 1e-10;
555       double D = _dir.Crossed( hp._dir );
556       if ( fabs(D) < std::numeric_limits<double>::min())
557         return false;
558       gp_XY vec21 = _pos - hp._pos; 
559       double u = hp._dir.Crossed( vec21 ) / D; 
560       intPnt = _pos + _dir * u;
561       return true;
562     }
563   };
564   //--------------------------------------------------------------------------------
565   /*!
566    * Structure used to smooth a _LayerEdge based on an EDGE.
567    */
568   struct _2NearEdges
569   {
570     double               _wgt  [2]; // weights of _nodes
571     _LayerEdge*          _edges[2];
572
573      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
574     gp_XYZ*              _plnNorm;
575
576     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
577     const SMDS_MeshNode* tgtNode(bool is2nd) {
578       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
579     }
580     const SMDS_MeshNode* srcNode(bool is2nd) {
581       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
582     }
583     void reverse() {
584       std::swap( _wgt  [0], _wgt  [1] );
585       std::swap( _edges[0], _edges[1] );
586     }
587     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
588       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
589     }
590     bool include( const _LayerEdge* e ) {
591       return ( _edges[0] == e || _edges[1] == e );
592     }
593   };
594
595
596   //--------------------------------------------------------------------------------
597   /*!
598    * \brief Layers parameters got by averaging several hypotheses
599    */
600   struct AverageHyp
601   {
602     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
603       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
604     {
605       Add( hyp );
606     }
607     void Add( const StdMeshers_ViscousLayers* hyp )
608     {
609       if ( hyp )
610       {
611         _nbHyps++;
612         _nbLayers       = hyp->GetNumberLayers();
613         //_thickness     += hyp->GetTotalThickness();
614         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
615         _stretchFactor += hyp->GetStretchFactor();
616         _method         = hyp->GetMethod();
617       }
618     }
619     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621     int    GetNumberLayers()   const { return _nbLayers; }
622     int    GetMethod()         const { return _method; }
623
624     bool   UseSurfaceNormal()  const
625     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
626     bool   ToSmooth()          const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   IsOffsetMethod()    const
629     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
630
631   private:
632     int     _nbLayers, _nbHyps, _method;
633     double  _thickness, _stretchFactor;
634   };
635
636   //--------------------------------------------------------------------------------
637   /*!
638    * \brief _LayerEdge's on a shape and other shape data
639    */
640   struct _EdgesOnShape
641   {
642     vector< _LayerEdge* > _edges;
643
644     TopoDS_Shape          _shape;
645     TGeomID               _shapeID;
646     SMESH_subMesh *       _subMesh;
647     // face or edge w/o layer along or near which _edges are inflated
648     TopoDS_Shape          _sWOL;
649     bool                  _isRegularSWOL; // w/o singularities
650     // averaged StdMeshers_ViscousLayers parameters
651     AverageHyp            _hyp;
652     bool                  _toSmooth;
653     _Smoother1D*          _edgeSmoother;
654     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
655     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
656
657     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
658     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
659
660     Handle(ShapeAnalysis_Surface) _offsetSurf;
661     _LayerEdge*                   _edgeForOffset;
662
663     _SolidData*            _data; // parent SOLID
664
665     TopAbs_ShapeEnum ShapeType() const
666     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
667     TopAbs_ShapeEnum SWOLType() const
668     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
669     bool             HasC1( const _EdgesOnShape* other ) const
670     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
671     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
672     _SolidData&      GetData() const { return *_data; }
673
674     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
675   };
676
677   //--------------------------------------------------------------------------------
678   /*!
679    * \brief Convex FACE whose radius of curvature is less than the thickness of 
680    *        layers. It is used to detect distortion of prisms based on a convex
681    *        FACE and to update normals to enable further increasing the thickness
682    */
683   struct _ConvexFace
684   {
685     TopoDS_Face                     _face;
686
687     // edges whose _simplices are used to detect prism distortion
688     vector< _LayerEdge* >           _simplexTestEdges;
689
690     // map a sub-shape to _SolidData::_edgesOnShape
691     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
692
693     bool                            _normalsFixed;
694
695     bool GetCenterOfCurvature( _LayerEdge*         ledge,
696                                BRepLProp_SLProps&  surfProp,
697                                SMESH_MesherHelper& helper,
698                                gp_Pnt &            center ) const;
699     bool CheckPrisms() const;
700   };
701
702   //--------------------------------------------------------------------------------
703   /*!
704    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
705    *        at inflation up to the full thickness. A detected collision
706    *        is fixed in updateNormals()
707    */
708   struct _CollisionEdges
709   {
710     _LayerEdge*           _edge;
711     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
712     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
713     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
714   };
715
716   //--------------------------------------------------------------------------------
717   /*!
718    * \brief Data of a SOLID
719    */
720   struct _SolidData
721   {
722     typedef const StdMeshers_ViscousLayers* THyp;
723     TopoDS_Shape                    _solid;
724     TGeomID                         _index; // SOLID id
725     _MeshOfSolid*                   _proxyMesh;
726     list< THyp >                    _hyps;
727     list< TopoDS_Shape >            _hypShapes;
728     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
729     set< TGeomID >                  _reversedFaceIds;
730     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
731
732     double                          _stepSize, _stepSizeCoeff, _geomSize;
733     const SMDS_MeshNode*            _stepSizeNodes[2];
734
735     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
736
737     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
738     map< TGeomID, TNode2Edge* >     _s2neMap;
739     // _LayerEdge's with underlying shapes
740     vector< _EdgesOnShape >         _edgesOnShape;
741
742     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
743     //        layers and a FACE w/o layers
744     // value: the shape (FACE or EDGE) to shrink mesh on.
745     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
746     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
747
748     // Convex FACEs whose radius of curvature is less than the thickness of layers
749     map< TGeomID, _ConvexFace >      _convexFaces;
750
751     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
752     // the adjacent SOLID
753     set< TGeomID >                   _noShrinkShapes;
754
755     int                              _nbShapesToSmooth;
756
757     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
758
759     vector< _CollisionEdges >        _collisionEdges;
760     set< TGeomID >                   _concaveFaces;
761
762     double                           _maxThickness; // of all _hyps
763     double                           _minThickness; // of all _hyps
764
765     double                           _epsilon; // precision for SegTriaInter()
766
767     SMESH_MesherHelper*              _helper;
768
769     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
770                _MeshOfSolid*       m=0)
771       :_solid(s), _proxyMesh(m), _helper(0) {}
772     ~_SolidData();
773
774     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
775     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
776
777     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
778       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
779       return id2face == _convexFaces.end() ? 0 : & id2face->second;
780     }
781     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
782     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
783     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
784     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
785
786     SMESH_MesherHelper& GetHelper() const { return *_helper; }
787
788     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
789       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
790         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
791           _edgesOnShape[i]._edges[j]->Unset( flag );
792     }
793     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
794                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
795
796     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
797   };
798   //--------------------------------------------------------------------------------
799   /*!
800    * \brief Offset plane used in getNormalByOffset()
801    */
802   struct _OffsetPlane
803   {
804     gp_Pln _plane;
805     int    _faceIndex;
806     int    _faceIndexNext[2];
807     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
808     bool   _isLineOK[2];
809     _OffsetPlane() {
810       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
811     }
812     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
813                                     const TopoDS_Edge&   E,
814                                     const TopoDS_Vertex& V );
815     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
816     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
817   };
818   //--------------------------------------------------------------------------------
819   /*!
820    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
821    */
822   struct _CentralCurveOnEdge
823   {
824     bool                  _isDegenerated;
825     vector< gp_Pnt >      _curvaCenters;
826     vector< _LayerEdge* > _ledges;
827     vector< gp_XYZ >      _normals; // new normal for each of _ledges
828     vector< double >      _segLength2;
829
830     TopoDS_Edge           _edge;
831     TopoDS_Face           _adjFace;
832     bool                  _adjFaceToSmooth;
833
834     void Append( const gp_Pnt& center, _LayerEdge* ledge )
835     {
836       if ( _curvaCenters.size() > 0 )
837         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
838       _curvaCenters.push_back( center );
839       _ledges.push_back( ledge );
840       _normals.push_back( ledge->_normal );
841     }
842     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
843     void SetShapes( const TopoDS_Edge&  edge,
844                     const _ConvexFace&  convFace,
845                     _SolidData&         data,
846                     SMESH_MesherHelper& helper);
847   };
848   //--------------------------------------------------------------------------------
849   /*!
850    * \brief Data of node on a shrinked FACE
851    */
852   struct _SmoothNode
853   {
854     const SMDS_MeshNode*         _node;
855     vector<_Simplex>             _simplices; // for quality check
856
857     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
858
859     bool Smooth(int&                  badNb,
860                 Handle(Geom_Surface)& surface,
861                 SMESH_MesherHelper&   helper,
862                 const double          refSign,
863                 SmoothType            how,
864                 bool                  set3D);
865
866     gp_XY computeAngularPos(vector<gp_XY>& uv,
867                             const gp_XY&   uvToFix,
868                             const double   refSign );
869   };
870   //--------------------------------------------------------------------------------
871   /*!
872    * \brief Builder of viscous layers
873    */
874   class _ViscousBuilder
875   {
876   public:
877     _ViscousBuilder();
878     // does it's job
879     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
880                                   const TopoDS_Shape& shape);
881     // check validity of hypotheses
882     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
883                                            const TopoDS_Shape& shape );
884
885     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
886     void RestoreListeners();
887
888     // computes SMESH_ProxyMesh::SubMesh::_n2n;
889     bool MakeN2NMap( _MeshOfSolid* pm );
890
891   private:
892
893     bool findSolidsWithLayers();
894     bool findFacesWithLayers(const bool onlyWith=false);
895     void getIgnoreFaces(const TopoDS_Shape&             solid,
896                         const StdMeshers_ViscousLayers* hyp,
897                         const TopoDS_Shape&             hypShape,
898                         set<TGeomID>&                   ignoreFaces);
899     bool makeLayer(_SolidData& data);
900     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
901     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
902                       SMESH_MesherHelper& helper, _SolidData& data);
903     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
904                          const TopoDS_Face&   face,
905                          SMESH_MesherHelper&  helper,
906                          bool&                isOK,
907                          bool                 shiftInside=false);
908     bool getFaceNormalAtSingularity(const gp_XY&        uv,
909                                     const TopoDS_Face&  face,
910                                     SMESH_MesherHelper& helper,
911                                     gp_Dir&             normal );
912     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
913     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
914                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
915                               int                              nbFaces,
916                               bool                             lastNoOffset = false);
917     bool findNeiborsOnEdge(const _LayerEdge*     edge,
918                            const SMDS_MeshNode*& n1,
919                            const SMDS_MeshNode*& n2,
920                            _EdgesOnShape&        eos,
921                            _SolidData&           data);
922     void findSimplexTestEdges( _SolidData&                    data,
923                                vector< vector<_LayerEdge*> >& edgesByGeom);
924     void computeGeomSize( _SolidData& data );
925     bool findShapesToSmooth( _SolidData& data);
926     void limitStepSizeByCurvature( _SolidData&  data );
927     void limitStepSize( _SolidData&             data,
928                         const SMDS_MeshElement* face,
929                         const _LayerEdge*       maxCosinEdge );
930     void limitStepSize( _SolidData& data, const double minSize);
931     bool inflate(_SolidData& data);
932     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
933     int  invalidateBadSmooth( _SolidData&               data,
934                               SMESH_MesherHelper&       helper,
935                               vector< _LayerEdge* >&    badSmooEdges,
936                               vector< _EdgesOnShape* >& eosC1,
937                               const int                 infStep );
938     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
939     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
940                              vector< _EdgesOnShape* >& eosC1,
941                              int smooStep=0, bool moveAll=false );
942     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
943     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
944     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
945                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
946                                  SMESH_MesherHelper& helper );
947     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
948     bool updateNormalsOfConvexFaces( _SolidData&         data,
949                                      SMESH_MesherHelper& helper,
950                                      int                 stepNb );
951     void updateNormalsOfC1Vertices( _SolidData& data );
952     bool updateNormalsOfSmoothed( _SolidData&         data,
953                                   SMESH_MesherHelper& helper,
954                                   const int           nbSteps,
955                                   const double        stepSize );
956     bool isNewNormalOk( _SolidData&   data,
957                         _LayerEdge&   edge,
958                         const gp_XYZ& newNormal);
959     bool refine(_SolidData& data);
960     bool shrink();
961     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
962                               SMESH_MesherHelper& helper,
963                               const SMESHDS_SubMesh* faceSubMesh );
964     void restoreNoShrink( _LayerEdge& edge ) const;
965     void fixBadFaces(const TopoDS_Face&          F,
966                      SMESH_MesherHelper&         helper,
967                      const bool                  is2D,
968                      const int                   step,
969                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
970     bool addBoundaryElements();
971
972     bool error( const string& text, int solidID=-1 );
973     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
974
975     // debug
976     void makeGroupOfLE();
977
978     SMESH_Mesh*           _mesh;
979     SMESH_ComputeErrorPtr _error;
980
981     vector< _SolidData >  _sdVec;
982     int                   _tmpFaceID;
983   };
984   //--------------------------------------------------------------------------------
985   /*!
986    * \brief Shrinker of nodes on the EDGE
987    */
988   class _Shrinker1D
989   {
990     TopoDS_Edge                   _geomEdge;
991     vector<double>                _initU;
992     vector<double>                _normPar;
993     vector<const SMDS_MeshNode*>  _nodes;
994     const _LayerEdge*             _edges[2];
995     bool                          _done;
996   public:
997     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
998     void Compute(bool set3D, SMESH_MesherHelper& helper);
999     void RestoreParams();
1000     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1001     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1002     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1003     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1004     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1005     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1006   };
1007   //--------------------------------------------------------------------------------
1008   /*!
1009    * \brief Smoother of _LayerEdge's on EDGE.
1010    */
1011   struct _Smoother1D
1012   {
1013     struct OffPnt // point of the offsetted EDGE
1014     {
1015       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1016       double      _len;    // length reached at previous inflation step
1017       double      _param;  // on EDGE
1018       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1019       gp_XYZ      _edgeDir;// EDGE tangent at _param
1020       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1021     };
1022     vector< OffPnt >   _offPoints;
1023     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1024     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1025     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1026     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1027     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1028     _EdgesOnShape&     _eos;
1029     double             _curveLen; // length of the EDGE
1030
1031     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1032                                               _EdgesOnShape&      eos,
1033                                               SMESH_MesherHelper& helper);
1034
1035     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1036                  _EdgesOnShape&     eos )
1037       : _anaCurve( curveForSmooth ), _eos( eos )
1038     {
1039     }
1040     bool Perform(_SolidData&                    data,
1041                  Handle(ShapeAnalysis_Surface)& surface,
1042                  const TopoDS_Face&             F,
1043                  SMESH_MesherHelper&            helper )
1044     {
1045       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1046         prepare( data );
1047
1048       if ( isAnalytic() )
1049         return smoothAnalyticEdge( data, surface, F, helper );
1050       else
1051         return smoothComplexEdge ( data, surface, F, helper );
1052     }
1053     void prepare(_SolidData& data );
1054
1055     bool smoothAnalyticEdge( _SolidData&                    data,
1056                              Handle(ShapeAnalysis_Surface)& surface,
1057                              const TopoDS_Face&             F,
1058                              SMESH_MesherHelper&            helper);
1059
1060     bool smoothComplexEdge( _SolidData&                    data,
1061                             Handle(ShapeAnalysis_Surface)& surface,
1062                             const TopoDS_Face&             F,
1063                             SMESH_MesherHelper&            helper);
1064
1065     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1066                             const gp_XYZ&  edgeDir);
1067
1068     _LayerEdge* getLEdgeOnV( bool is2nd )
1069     {
1070       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1071     }
1072     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1073   };
1074   //--------------------------------------------------------------------------------
1075   /*!
1076    * \brief Class of temporary mesh face.
1077    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1078    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1079    */
1080   struct _TmpMeshFace : public SMDS_MeshElement
1081   {
1082     vector<const SMDS_MeshNode* > _nn;
1083     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1084                   int id, int faceID=-1, int idInFace=-1):
1085       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1086     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1087     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1088     virtual vtkIdType GetVtkType() const                      { return -1; }
1089     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1090     virtual SMDSAbs_GeometryType GetGeomType() const
1091     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1092     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1093     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1094   };
1095   //--------------------------------------------------------------------------------
1096   /*!
1097    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1098    */
1099   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1100   {
1101     _LayerEdge *_le1, *_le2;
1102     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1103       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1104     {
1105       _nn[0]=_le1->_nodes[0];
1106       _nn[1]=_le1->_nodes.back();
1107       _nn[2]=_le2->_nodes.back();
1108       _nn[3]=_le2->_nodes[0];
1109     }
1110     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1111     {
1112       SMESH_TNodeXYZ p0s( _nn[0] );
1113       SMESH_TNodeXYZ p0t( _nn[1] );
1114       SMESH_TNodeXYZ p1t( _nn[2] );
1115       SMESH_TNodeXYZ p1s( _nn[3] );
1116       gp_XYZ  v0 = p0t - p0s;
1117       gp_XYZ  v1 = p1t - p1s;
1118       gp_XYZ v01 = p1s - p0s;
1119       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1120       gp_XYZ   d = v01 ^ n;
1121       d.Normalize();
1122       return d;
1123     }
1124     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1125     {
1126       _nn[0]=le1->_nodes[0];
1127       _nn[1]=le1->_nodes.back();
1128       _nn[2]=le2->_nodes.back();
1129       _nn[3]=le2->_nodes[0];
1130       return GetDir();
1131     }
1132   };
1133   //--------------------------------------------------------------------------------
1134   /*!
1135    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1136    * \warning Location of a surface is ignored
1137    */
1138   struct _NodeCoordHelper
1139   {
1140     SMESH_MesherHelper&        _helper;
1141     const TopoDS_Face&         _face;
1142     Handle(Geom_Surface)       _surface;
1143     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1144
1145     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1146       : _helper( helper ), _face( F )
1147     {
1148       if ( is2D )
1149       {
1150         TopLoc_Location loc;
1151         _surface = BRep_Tool::Surface( _face, loc );
1152       }
1153       if ( _surface.IsNull() )
1154         _fun = & _NodeCoordHelper::direct;
1155       else
1156         _fun = & _NodeCoordHelper::byUV;
1157     }
1158     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1159
1160   private:
1161     gp_XYZ direct(const SMDS_MeshNode* n) const
1162     {
1163       return SMESH_TNodeXYZ( n );
1164     }
1165     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1166     {
1167       gp_XY uv = _helper.GetNodeUV( _face, n );
1168       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1169     }
1170   };
1171
1172   //================================================================================
1173   /*!
1174    * \brief Check angle between vectors 
1175    */
1176   //================================================================================
1177
1178   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1179   {
1180     double dot = v1 * v2; // cos * |v1| * |v2|
1181     double l1  = v1.SquareMagnitude();
1182     double l2  = v2.SquareMagnitude();
1183     return (( dot * cos >= 0 ) && 
1184             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1185   }
1186
1187 } // namespace VISCOUS_3D
1188
1189
1190
1191 //================================================================================
1192 // StdMeshers_ViscousLayers hypothesis
1193 //
1194 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1195   :SMESH_Hypothesis(hypId, studyId, gen),
1196    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1197    _method( SURF_OFFSET_SMOOTH )
1198 {
1199   _name = StdMeshers_ViscousLayers::GetHypType();
1200   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1201 } // --------------------------------------------------------------------------------
1202 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1203 {
1204   if ( faceIds != _shapeIds )
1205     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1206   if ( _isToIgnoreShapes != toIgnore )
1207     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1210 {
1211   if ( thickness != _thickness )
1212     _thickness = thickness, NotifySubMeshesHypothesisModification();
1213 } // --------------------------------------------------------------------------------
1214 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1215 {
1216   if ( _nbLayers != nb )
1217     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1218 } // --------------------------------------------------------------------------------
1219 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1220 {
1221   if ( _stretchFactor != factor )
1222     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1223 } // --------------------------------------------------------------------------------
1224 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1225 {
1226   if ( _method != method )
1227     _method = method, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 SMESH_ProxyMesh::Ptr
1230 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1231                                   const TopoDS_Shape& theShape,
1232                                   const bool          toMakeN2NMap) const
1233 {
1234   using namespace VISCOUS_3D;
1235   _ViscousBuilder bulder;
1236   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1237   if ( err && !err->IsOK() )
1238     return SMESH_ProxyMesh::Ptr();
1239
1240   vector<SMESH_ProxyMesh::Ptr> components;
1241   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1242   for ( ; exp.More(); exp.Next() )
1243   {
1244     if ( _MeshOfSolid* pm =
1245          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1246     {
1247       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1248         if ( !bulder.MakeN2NMap( pm ))
1249           return SMESH_ProxyMesh::Ptr();
1250       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1251       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1252
1253       if ( pm->_warning && !pm->_warning->IsOK() )
1254       {
1255         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1256         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1257         if ( !smError || smError->IsOK() )
1258           smError = pm->_warning;
1259       }
1260     }
1261     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1262   }
1263   switch ( components.size() )
1264   {
1265   case 0: break;
1266
1267   case 1: return components[0];
1268
1269   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1270   }
1271   return SMESH_ProxyMesh::Ptr();
1272 } // --------------------------------------------------------------------------------
1273 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1274 {
1275   save << " " << _nbLayers
1276        << " " << _thickness
1277        << " " << _stretchFactor
1278        << " " << _shapeIds.size();
1279   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1280     save << " " << _shapeIds[i];
1281   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1282   save << " " << _method;
1283   return save;
1284 } // --------------------------------------------------------------------------------
1285 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1286 {
1287   int nbFaces, faceID, shapeToTreat, method;
1288   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1289   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1290     _shapeIds.push_back( faceID );
1291   if ( load >> shapeToTreat ) {
1292     _isToIgnoreShapes = !shapeToTreat;
1293     if ( load >> method )
1294       _method = (ExtrusionMethod) method;
1295   }
1296   else {
1297     _isToIgnoreShapes = true; // old behavior
1298   }
1299   return load;
1300 } // --------------------------------------------------------------------------------
1301 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1302                                                    const TopoDS_Shape& theShape)
1303 {
1304   // TODO
1305   return false;
1306 } // --------------------------------------------------------------------------------
1307 SMESH_ComputeErrorPtr
1308 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1309                                           const TopoDS_Shape&                  theShape,
1310                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1311 {
1312   VISCOUS_3D::_ViscousBuilder bulder;
1313   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1314   if ( err && !err->IsOK() )
1315     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1316   else
1317     theStatus = SMESH_Hypothesis::HYP_OK;
1318
1319   return err;
1320 }
1321 // --------------------------------------------------------------------------------
1322 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1323 {
1324   bool isIn =
1325     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1326   return IsToIgnoreShapes() ? !isIn : isIn;
1327 }
1328 // END StdMeshers_ViscousLayers hypothesis
1329 //================================================================================
1330
1331 namespace VISCOUS_3D
1332 {
1333   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1334   {
1335     gp_Vec dir;
1336     double f,l;
1337     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1338     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1339     gp_Pnt p = BRep_Tool::Pnt( fromV );
1340     double distF = p.SquareDistance( c->Value( f ));
1341     double distL = p.SquareDistance( c->Value( l ));
1342     c->D1(( distF < distL ? f : l), p, dir );
1343     if ( distL < distF ) dir.Reverse();
1344     return dir.XYZ();
1345   }
1346   //--------------------------------------------------------------------------------
1347   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1348                      SMESH_MesherHelper& helper)
1349   {
1350     gp_Vec dir;
1351     double f,l; gp_Pnt p;
1352     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1353     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1354     double u = helper.GetNodeU( E, atNode );
1355     c->D1( u, p, dir );
1356     return dir.XYZ();
1357   }
1358   //--------------------------------------------------------------------------------
1359   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1360                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1361                      double* cosin=0);
1362   //--------------------------------------------------------------------------------
1363   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1364                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1365   {
1366     double f,l;
1367     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1368     if ( c.IsNull() )
1369     {
1370       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1371       return getFaceDir( F, v, node, helper, ok );
1372     }
1373     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1374     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1375     gp_Pnt p; gp_Vec du, dv, norm;
1376     surface->D1( uv.X(),uv.Y(), p, du,dv );
1377     norm = du ^ dv;
1378
1379     double u = helper.GetNodeU( fromE, node, 0, &ok );
1380     c->D1( u, p, du );
1381     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1382     if ( o == TopAbs_REVERSED )
1383       du.Reverse();
1384
1385     gp_Vec dir = norm ^ du;
1386
1387     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1388          helper.IsClosedEdge( fromE ))
1389     {
1390       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1391       else                        c->D1( f, p, dv );
1392       if ( o == TopAbs_REVERSED )
1393         dv.Reverse();
1394       gp_Vec dir2 = norm ^ dv;
1395       dir = dir.Normalized() + dir2.Normalized();
1396     }
1397     return dir.XYZ();
1398   }
1399   //--------------------------------------------------------------------------------
1400   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1401                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1402                      bool& ok, double* cosin)
1403   {
1404     TopoDS_Face faceFrw = F;
1405     faceFrw.Orientation( TopAbs_FORWARD );
1406     //double f,l; TopLoc_Location loc;
1407     TopoDS_Edge edges[2]; // sharing a vertex
1408     size_t nbEdges = 0;
1409     {
1410       TopoDS_Vertex VV[2];
1411       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1412       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1413       {
1414         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1415         if ( SMESH_Algo::isDegenerated( e )) continue;
1416         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1417         if ( VV[1].IsSame( fromV )) {
1418           nbEdges += edges[ 0 ].IsNull();
1419           edges[ 0 ] = e;
1420         }
1421         else if ( VV[0].IsSame( fromV )) {
1422           nbEdges += edges[ 1 ].IsNull();
1423           edges[ 1 ] = e;
1424         }
1425       }
1426     }
1427     gp_XYZ dir(0,0,0), edgeDir[2];
1428     if ( nbEdges == 2 )
1429     {
1430       // get dirs of edges going fromV
1431       ok = true;
1432       for ( size_t i = 0; i < nbEdges && ok; ++i )
1433       {
1434         edgeDir[i] = getEdgeDir( edges[i], fromV );
1435         double size2 = edgeDir[i].SquareModulus();
1436         if (( ok = size2 > numeric_limits<double>::min() ))
1437           edgeDir[i] /= sqrt( size2 );
1438       }
1439       if ( !ok ) return dir;
1440
1441       // get angle between the 2 edges
1442       gp_Vec faceNormal;
1443       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1444       if ( Abs( angle ) < 5 * M_PI/180 )
1445       {
1446         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1447       }
1448       else
1449       {
1450         dir = edgeDir[0] + edgeDir[1];
1451         if ( angle < 0 )
1452           dir.Reverse();
1453       }
1454       if ( cosin ) {
1455         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1456         *cosin = Cos( angle );
1457       }
1458     }
1459     else if ( nbEdges == 1 )
1460     {
1461       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1462       if ( cosin ) *cosin = 1.;
1463     }
1464     else
1465     {
1466       ok = false;
1467     }
1468
1469     return dir;
1470   }
1471
1472   //================================================================================
1473   /*!
1474    * \brief Finds concave VERTEXes of a FACE
1475    */
1476   //================================================================================
1477
1478   bool getConcaveVertices( const TopoDS_Face&  F,
1479                            SMESH_MesherHelper& helper,
1480                            set< TGeomID >*     vertices = 0)
1481   {
1482     // check angles at VERTEXes
1483     TError error;
1484     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1485     for ( size_t iW = 0; iW < wires.size(); ++iW )
1486     {
1487       const int nbEdges = wires[iW]->NbEdges();
1488       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1489         continue;
1490       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1491       {
1492         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1493         int iE2 = ( iE1 + 1 ) % nbEdges;
1494         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1495           iE2 = ( iE2 + 1 ) % nbEdges;
1496         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1497         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1498                                         wires[iW]->Edge( iE2 ), F, V );
1499         if ( angle < -5. * M_PI / 180. )
1500         {
1501           if ( !vertices )
1502             return true;
1503           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1504         }
1505       }
1506     }
1507     return vertices ? !vertices->empty() : false;
1508   }
1509
1510   //================================================================================
1511   /*!
1512    * \brief Returns true if a FACE is bound by a concave EDGE
1513    */
1514   //================================================================================
1515
1516   bool isConcave( const TopoDS_Face&  F,
1517                   SMESH_MesherHelper& helper,
1518                   set< TGeomID >*     vertices = 0 )
1519   {
1520     bool isConcv = false;
1521     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1522     //   return true;
1523     gp_Vec2d drv1, drv2;
1524     gp_Pnt2d p;
1525     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1526     for ( ; eExp.More(); eExp.Next() )
1527     {
1528       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1529       if ( SMESH_Algo::isDegenerated( E )) continue;
1530       // check if 2D curve is concave
1531       BRepAdaptor_Curve2d curve( E, F );
1532       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1533       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1534       curve.Intervals( intervals, GeomAbs_C2 );
1535       bool isConvex = true;
1536       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1537       {
1538         double u1 = intervals( i );
1539         double u2 = intervals( i+1 );
1540         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1541         double cross = drv1 ^ drv2;
1542         if ( E.Orientation() == TopAbs_REVERSED )
1543           cross = -cross;
1544         isConvex = ( cross > -1e-9 ); // 0.1 );
1545       }
1546       if ( !isConvex )
1547       {
1548         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1549         isConcv = true;
1550         if ( vertices )
1551           break;
1552         else
1553           return true;
1554       }
1555     }
1556
1557     // check angles at VERTEXes
1558     if ( getConcaveVertices( F, helper, vertices ))
1559       isConcv = true;
1560
1561     return isConcv;
1562   }
1563
1564   //================================================================================
1565   /*!
1566    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1567    *  \param [in] face - the mesh face to treat
1568    *  \param [in] nodeOnEdge - a node on the EDGE
1569    *  \param [out] faceSize - the computed distance
1570    *  \return bool - true if faceSize computed
1571    */
1572   //================================================================================
1573
1574   bool getDistFromEdge( const SMDS_MeshElement* face,
1575                         const SMDS_MeshNode*    nodeOnEdge,
1576                         double &                faceSize )
1577   {
1578     faceSize = Precision::Infinite();
1579     bool done = false;
1580
1581     int nbN  = face->NbCornerNodes();
1582     int iOnE = face->GetNodeIndex( nodeOnEdge );
1583     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1584                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1585     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1586                                       face->GetNode( iNext[1] ) };
1587     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1588     double segLen = -1.;
1589     // look for two neighbor not in-FACE nodes of face
1590     for ( int i = 0; i < 2; ++i )
1591     {
1592       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1593            nNext[i]->GetID() < nodeOnEdge->GetID() )
1594       {
1595         // look for an in-FACE node
1596         for ( int iN = 0; iN < nbN; ++iN )
1597         {
1598           if ( iN == iOnE || iN == iNext[i] )
1599             continue;
1600           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1601           gp_XYZ v = pInFace - segEnd;
1602           if ( segLen < 0 )
1603           {
1604             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1605             segLen = segVec.Modulus();
1606           }
1607           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1608           faceSize = Min( faceSize, distToSeg );
1609           done = true;
1610         }
1611         segLen = -1;
1612       }
1613     }
1614     return done;
1615   }
1616   //================================================================================
1617   /*!
1618    * \brief Return direction of axis or revolution of a surface
1619    */
1620   //================================================================================
1621
1622   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1623                           gp_Dir &                 axis )
1624   {
1625     switch ( surface.GetType() ) {
1626     case GeomAbs_Cone:
1627     {
1628       gp_Cone cone = surface.Cone();
1629       axis = cone.Axis().Direction();
1630       break;
1631     }
1632     case GeomAbs_Sphere:
1633     {
1634       gp_Sphere sphere = surface.Sphere();
1635       axis = sphere.Position().Direction();
1636       break;
1637     }
1638     case GeomAbs_SurfaceOfRevolution:
1639     {
1640       axis = surface.AxeOfRevolution().Direction();
1641       break;
1642     }
1643     //case GeomAbs_SurfaceOfExtrusion:
1644     case GeomAbs_OffsetSurface:
1645     {
1646       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1647       return getRovolutionAxis( base->Surface(), axis );
1648     }
1649     default: return false;
1650     }
1651     return true;
1652   }
1653
1654   //--------------------------------------------------------------------------------
1655   // DEBUG. Dump intermediate node positions into a python script
1656   // HOWTO use: run python commands written in a console to see
1657   //  construction steps of viscous layers
1658 #ifdef __myDEBUG
1659   ofstream* py;
1660   int       theNbPyFunc;
1661   struct PyDump {
1662     PyDump(SMESH_Mesh& m) {
1663       int tag = 3 + m.GetId();
1664       const char* fname = "/tmp/viscous.py";
1665       cout << "execfile('"<<fname<<"')"<<endl;
1666       py = new ofstream(fname);
1667       *py << "import SMESH" << endl
1668           << "from salome.smesh import smeshBuilder" << endl
1669           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1670           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1671           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1672       theNbPyFunc = 0;
1673     }
1674     void Finish() {
1675       if (py) {
1676         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1677           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1678         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1679           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1680       }
1681       delete py; py=0;
1682     }
1683     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1684   };
1685 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1686 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1687 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1688 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1689   void _dumpFunction(const string& fun, int ln)
1690   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1691   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1692   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1693                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1694   void _dumpCmd(const string& txt, int ln)
1695   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1696   void dumpFunctionEnd()
1697   { if (py) *py<< "  return"<< endl; }
1698   void dumpChangeNodes( const SMDS_MeshElement* f )
1699   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1700       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1701       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1702 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1703
1704 #else
1705
1706   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1707 #define dumpFunction(f) f
1708 #define dumpMove(n)
1709 #define dumpMoveComm(n,txt)
1710 #define dumpCmd(txt)
1711 #define dumpFunctionEnd()
1712 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1713 #define debugMsg( txt ) {}
1714
1715 #endif
1716 }
1717
1718 using namespace VISCOUS_3D;
1719
1720 //================================================================================
1721 /*!
1722  * \brief Constructor of _ViscousBuilder
1723  */
1724 //================================================================================
1725
1726 _ViscousBuilder::_ViscousBuilder()
1727 {
1728   _error = SMESH_ComputeError::New(COMPERR_OK);
1729   _tmpFaceID = 0;
1730 }
1731
1732 //================================================================================
1733 /*!
1734  * \brief Stores error description and returns false
1735  */
1736 //================================================================================
1737
1738 bool _ViscousBuilder::error(const string& text, int solidId )
1739 {
1740   const string prefix = string("Viscous layers builder: ");
1741   _error->myName    = COMPERR_ALGO_FAILED;
1742   _error->myComment = prefix + text;
1743   if ( _mesh )
1744   {
1745     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1746     if ( !sm && !_sdVec.empty() )
1747       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1748     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1749     {
1750       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1751       if ( smError && smError->myAlgo )
1752         _error->myAlgo = smError->myAlgo;
1753       smError = _error;
1754       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1755     }
1756     // set KO to all solids
1757     for ( size_t i = 0; i < _sdVec.size(); ++i )
1758     {
1759       if ( _sdVec[i]._index == solidId )
1760         continue;
1761       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1762       if ( !sm->IsEmpty() )
1763         continue;
1764       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1765       if ( !smError || smError->IsOK() )
1766       {
1767         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1768         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1769       }
1770     }
1771   }
1772   makeGroupOfLE(); // debug
1773
1774   return false;
1775 }
1776
1777 //================================================================================
1778 /*!
1779  * \brief At study restoration, restore event listeners used to clear an inferior
1780  *  dim sub-mesh modified by viscous layers
1781  */
1782 //================================================================================
1783
1784 void _ViscousBuilder::RestoreListeners()
1785 {
1786   // TODO
1787 }
1788
1789 //================================================================================
1790 /*!
1791  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1792  */
1793 //================================================================================
1794
1795 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1796 {
1797   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1798   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1799   for ( ; fExp.More(); fExp.Next() )
1800   {
1801     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1802     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1803
1804     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1805       continue;
1806     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1807       continue;
1808
1809     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1810       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1811
1812     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1813     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1814     while( prxIt->more() )
1815     {
1816       const SMDS_MeshElement* fSrc = srcIt->next();
1817       const SMDS_MeshElement* fPrx = prxIt->next();
1818       if ( fSrc->NbNodes() != fPrx->NbNodes())
1819         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1820       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1821         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1822     }
1823   }
1824   pm->_n2nMapComputed = true;
1825   return true;
1826 }
1827
1828 //================================================================================
1829 /*!
1830  * \brief Does its job
1831  */
1832 //================================================================================
1833
1834 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1835                                                const TopoDS_Shape& theShape)
1836 {
1837   // TODO: set priority of solids during Gen::Compute()
1838
1839   _mesh = & theMesh;
1840
1841   // check if proxy mesh already computed
1842   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1843   if ( !exp.More() )
1844     return error("No SOLID's in theShape"), _error;
1845
1846   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1847     return SMESH_ComputeErrorPtr(); // everything already computed
1848
1849   PyDump debugDump( theMesh );
1850
1851   // TODO: ignore already computed SOLIDs 
1852   if ( !findSolidsWithLayers())
1853     return _error;
1854
1855   if ( !findFacesWithLayers() )
1856     return _error;
1857
1858   for ( size_t i = 0; i < _sdVec.size(); ++i )
1859   {
1860     if ( ! makeLayer(_sdVec[i]) )
1861       return _error;
1862
1863     if ( _sdVec[i]._n2eMap.size() == 0 )
1864       continue;
1865     
1866     if ( ! inflate(_sdVec[i]) )
1867       return _error;
1868
1869     if ( ! refine(_sdVec[i]) )
1870       return _error;
1871   }
1872   if ( !shrink() )
1873     return _error;
1874
1875   addBoundaryElements();
1876
1877   makeGroupOfLE(); // debug
1878   debugDump.Finish();
1879
1880   return _error;
1881 }
1882
1883 //================================================================================
1884 /*!
1885  * \brief Check validity of hypotheses
1886  */
1887 //================================================================================
1888
1889 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1890                                                         const TopoDS_Shape& shape )
1891 {
1892   _mesh = & mesh;
1893
1894   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1895     return SMESH_ComputeErrorPtr(); // everything already computed
1896
1897
1898   findSolidsWithLayers();
1899   bool ok = findFacesWithLayers( true );
1900
1901   // remove _MeshOfSolid's of _SolidData's
1902   for ( size_t i = 0; i < _sdVec.size(); ++i )
1903     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1904
1905   if ( !ok )
1906     return _error;
1907
1908   return SMESH_ComputeErrorPtr();
1909 }
1910
1911 //================================================================================
1912 /*!
1913  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1914  */
1915 //================================================================================
1916
1917 bool _ViscousBuilder::findSolidsWithLayers()
1918 {
1919   // get all solids
1920   TopTools_IndexedMapOfShape allSolids;
1921   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1922   _sdVec.reserve( allSolids.Extent());
1923
1924   SMESH_Gen* gen = _mesh->GetGen();
1925   SMESH_HypoFilter filter;
1926   for ( int i = 1; i <= allSolids.Extent(); ++i )
1927   {
1928     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1929     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1930     if ( !algo ) continue;
1931     // TODO: check if algo is hidden
1932     const list <const SMESHDS_Hypothesis *> & allHyps =
1933       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1934     _SolidData* soData = 0;
1935     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1936     const StdMeshers_ViscousLayers* viscHyp = 0;
1937     for ( ; hyp != allHyps.end(); ++hyp )
1938       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1939       {
1940         TopoDS_Shape hypShape;
1941         filter.Init( filter.Is( viscHyp ));
1942         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1943
1944         if ( !soData )
1945         {
1946           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1947                                                                     allSolids(i),
1948                                                                     /*toCreate=*/true);
1949           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1950           soData = & _sdVec.back();
1951           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1952           soData->_helper = new SMESH_MesherHelper( *_mesh );
1953           soData->_helper->SetSubShape( allSolids(i) );
1954         }
1955         soData->_hyps.push_back( viscHyp );
1956         soData->_hypShapes.push_back( hypShape );
1957       }
1958   }
1959   if ( _sdVec.empty() )
1960     return error
1961       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1962
1963   return true;
1964 }
1965
1966 //================================================================================
1967 /*!
1968  * \brief 
1969  */
1970 //================================================================================
1971
1972 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1973 {
1974   SMESH_MesherHelper helper( *_mesh );
1975   TopExp_Explorer exp;
1976   TopTools_IndexedMapOfShape solids;
1977
1978   // collect all faces-to-ignore defined by hyp
1979   for ( size_t i = 0; i < _sdVec.size(); ++i )
1980   {
1981     solids.Add( _sdVec[i]._solid );
1982
1983     // get faces-to-ignore defined by each hyp
1984     typedef const StdMeshers_ViscousLayers* THyp;
1985     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1986     list< TFacesOfHyp > ignoreFacesOfHyps;
1987     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1988     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1989     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1990     {
1991       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1992       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1993     }
1994
1995     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1996     const int nbHyps = _sdVec[i]._hyps.size();
1997     if ( nbHyps > 1 )
1998     {
1999       // check if two hypotheses define different parameters for the same FACE
2000       list< TFacesOfHyp >::iterator igFacesOfHyp;
2001       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2002       {
2003         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2004         THyp hyp = 0;
2005         igFacesOfHyp = ignoreFacesOfHyps.begin();
2006         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2007           if ( ! igFacesOfHyp->first.count( faceID ))
2008           {
2009             if ( hyp )
2010               return error(SMESH_Comment("Several hypotheses define "
2011                                          "Viscous Layers on the face #") << faceID );
2012             hyp = igFacesOfHyp->second;
2013           }
2014         if ( hyp )
2015           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2016         else
2017           _sdVec[i]._ignoreFaceIds.insert( faceID );
2018       }
2019
2020       // check if two hypotheses define different number of viscous layers for
2021       // adjacent faces of a solid
2022       set< int > nbLayersSet;
2023       igFacesOfHyp = ignoreFacesOfHyps.begin();
2024       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2025       {
2026         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2027       }
2028       if ( nbLayersSet.size() > 1 )
2029       {
2030         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2031         {
2032           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2033           THyp hyp1 = 0, hyp2 = 0;
2034           while( const TopoDS_Shape* face = fIt->next() )
2035           {
2036             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2037             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2038             if ( f2h != _sdVec[i]._face2hyp.end() )
2039             {
2040               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2041             }
2042           }
2043           if ( hyp1 && hyp2 &&
2044                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2045           {
2046             return error("Two hypotheses define different number of "
2047                          "viscous layers on adjacent faces");
2048           }
2049         }
2050       }
2051     } // if ( nbHyps > 1 )
2052     else
2053     {
2054       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2055     }
2056   } // loop on _sdVec
2057
2058   if ( onlyWith ) // is called to check hypotheses compatibility only
2059     return true;
2060
2061   // fill _SolidData::_reversedFaceIds
2062   for ( size_t i = 0; i < _sdVec.size(); ++i )
2063   {
2064     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2065     for ( ; exp.More(); exp.Next() )
2066     {
2067       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2068       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2069       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2070           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2071           helper.IsReversedSubMesh( face ))
2072       {
2073         _sdVec[i]._reversedFaceIds.insert( faceID );
2074       }
2075     }
2076   }
2077
2078   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2079   TopTools_IndexedMapOfShape shapes;
2080   for ( size_t i = 0; i < _sdVec.size(); ++i )
2081   {
2082     shapes.Clear();
2083     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2084     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2085     {
2086       const TopoDS_Shape& edge = shapes(iE);
2087       // find 2 faces sharing an edge
2088       TopoDS_Shape FF[2];
2089       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2090       while ( fIt->more())
2091       {
2092         const TopoDS_Shape* f = fIt->next();
2093         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2094           FF[ int( !FF[0].IsNull()) ] = *f;
2095       }
2096       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2097       // check presence of layers on them
2098       int ignore[2];
2099       for ( int j = 0; j < 2; ++j )
2100         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2101       if ( ignore[0] == ignore[1] )
2102         continue; // nothing interesting
2103       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2104       // check presence of layers on fWOL within an adjacent SOLID
2105       bool collision = false;
2106       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2107       while ( const TopoDS_Shape* solid = sIt->next() )
2108         if ( !solid->IsSame( _sdVec[i]._solid ))
2109         {
2110           int iSolid = solids.FindIndex( *solid );
2111           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2112           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2113           {
2114             //_sdVec[i]._noShrinkShapes.insert( iFace );
2115             //fWOL.Nullify();
2116             collision = true;
2117           }
2118         }
2119       // add edge to maps
2120       if ( !fWOL.IsNull())
2121       {
2122         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2123         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2124         if ( collision )
2125         {
2126           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2127           // on the edge but shrink won't be performed
2128           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2129         }
2130       }
2131     }
2132   }
2133   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2134   // the algo of the SOLID sharing the FACE does not support it
2135   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2136   for ( size_t i = 0; i < _sdVec.size(); ++i )
2137   {
2138     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2139     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2140     {
2141       const TopoDS_Shape& fWOL = e2f->second;
2142       const TGeomID     edgeID = e2f->first;
2143       bool notShrinkFace = false;
2144       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2145       while ( soIt->more() )
2146       {
2147         const TopoDS_Shape* solid = soIt->next();
2148         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2149         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2150         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2151         notShrinkFace = true;
2152         size_t iSolid = 0;
2153         for ( ; iSolid < _sdVec.size(); ++iSolid )
2154         {
2155           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2156             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2157               notShrinkFace = false;
2158             break;
2159           }
2160         }
2161         if ( notShrinkFace )
2162         {
2163           _sdVec[i]._noShrinkShapes.insert( edgeID );
2164
2165           // add VERTEXes of the edge in _noShrinkShapes
2166           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2167           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2168             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2169
2170           // check if there is a collision with to-shrink-from EDGEs in iSolid
2171           if ( iSolid == _sdVec.size() )
2172             continue; // no VL in the solid
2173           shapes.Clear();
2174           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2175           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2176           {
2177             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2178             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2179             if ( eID == edgeID ||
2180                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2181                  _sdVec[i]._noShrinkShapes.count( eID ))
2182               continue;
2183             for ( int is1st = 0; is1st < 2; ++is1st )
2184             {
2185               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2186               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2187               {
2188                 // _sdVec[i]._noShrinkShapes.insert( eID );
2189                 // V = helper.IthVertex( !is1st, E );
2190                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2191                 //iE = 0; // re-start the loop on EDGEs of fWOL
2192                 return error("No way to make a conformal mesh with "
2193                              "the given set of faces with layers", _sdVec[i]._index);
2194               }
2195             }
2196           }
2197         }
2198
2199       } // while ( soIt->more() )
2200     } // loop on _sdVec[i]._shrinkShape2Shape
2201   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2202
2203   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2204
2205   for ( size_t i = 0; i < _sdVec.size(); ++i )
2206   {
2207     shapes.Clear();
2208     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2209     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2210     {
2211       const TopoDS_Shape& vertex = shapes(iV);
2212       // find faces WOL sharing the vertex
2213       vector< TopoDS_Shape > facesWOL;
2214       size_t totalNbFaces = 0;
2215       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2216       while ( fIt->more())
2217       {
2218         const TopoDS_Shape* f = fIt->next();
2219         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2220         {
2221           totalNbFaces++;
2222           const int fID = getMeshDS()->ShapeToIndex( *f );
2223           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2224                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2225             facesWOL.push_back( *f );
2226         }
2227       }
2228       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2229         continue; // no layers at this vertex or no WOL
2230       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2231       switch ( facesWOL.size() )
2232       {
2233       case 1:
2234       {
2235         helper.SetSubShape( facesWOL[0] );
2236         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2237         {
2238           TopoDS_Shape seamEdge;
2239           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2240           while ( eIt->more() && seamEdge.IsNull() )
2241           {
2242             const TopoDS_Shape* e = eIt->next();
2243             if ( helper.IsRealSeam( *e ) )
2244               seamEdge = *e;
2245           }
2246           if ( !seamEdge.IsNull() )
2247           {
2248             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2249             break;
2250           }
2251         }
2252         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2253         break;
2254       }
2255       case 2:
2256       {
2257         // find an edge shared by 2 faces
2258         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2259         while ( eIt->more())
2260         {
2261           const TopoDS_Shape* e = eIt->next();
2262           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2263                helper.IsSubShape( *e, facesWOL[1]))
2264           {
2265             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2266           }
2267         }
2268         break;
2269       }
2270       default:
2271         return error("Not yet supported case", _sdVec[i]._index);
2272       }
2273     }
2274   }
2275
2276   // add FACEs of other SOLIDs to _ignoreFaceIds
2277   for ( size_t i = 0; i < _sdVec.size(); ++i )
2278   {
2279     shapes.Clear();
2280     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2281
2282     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2283     {
2284       if ( !shapes.Contains( exp.Current() ))
2285         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2286     }
2287   }
2288
2289   return true;
2290 }
2291
2292 //================================================================================
2293 /*!
2294  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2295  */
2296 //================================================================================
2297
2298 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2299                                      const StdMeshers_ViscousLayers* hyp,
2300                                      const TopoDS_Shape&             hypShape,
2301                                      set<TGeomID>&                   ignoreFaceIds)
2302 {
2303   TopExp_Explorer exp;
2304
2305   vector<TGeomID> ids = hyp->GetBndShapes();
2306   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2307   {
2308     for ( size_t ii = 0; ii < ids.size(); ++ii )
2309     {
2310       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2311       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2312         ignoreFaceIds.insert( ids[ii] );
2313     }
2314   }
2315   else // FACEs with layers are given
2316   {
2317     exp.Init( solid, TopAbs_FACE );
2318     for ( ; exp.More(); exp.Next() )
2319     {
2320       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2321       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2322         ignoreFaceIds.insert( faceInd );
2323     }
2324   }
2325
2326   // ignore internal FACEs if inlets and outlets are specified
2327   if ( hyp->IsToIgnoreShapes() )
2328   {
2329     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2330     TopExp::MapShapesAndAncestors( hypShape,
2331                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2332
2333     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2334     {
2335       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2336       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2337         continue;
2338
2339       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2340       if ( nbSolids > 1 )
2341         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2342     }
2343   }
2344 }
2345
2346 //================================================================================
2347 /*!
2348  * \brief Create the inner surface of the viscous layer and prepare data for infation
2349  */
2350 //================================================================================
2351
2352 bool _ViscousBuilder::makeLayer(_SolidData& data)
2353 {
2354   // get all sub-shapes to make layers on
2355   set<TGeomID> subIds, faceIds;
2356   subIds = data._noShrinkShapes;
2357   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2358   for ( ; exp.More(); exp.Next() )
2359   {
2360     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2361     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2362       faceIds.insert( fSubM->GetId() );
2363   }
2364
2365   // make a map to find new nodes on sub-shapes shared with other SOLID
2366   map< TGeomID, TNode2Edge* >::iterator s2ne;
2367   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2368   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2369   {
2370     TGeomID shapeInd = s2s->first;
2371     for ( size_t i = 0; i < _sdVec.size(); ++i )
2372     {
2373       if ( _sdVec[i]._index == data._index ) continue;
2374       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2375       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2376            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2377       {
2378         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2379         break;
2380       }
2381     }
2382   }
2383
2384   // Create temporary faces and _LayerEdge's
2385
2386   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2387
2388   data._stepSize = Precision::Infinite();
2389   data._stepSizeNodes[0] = 0;
2390
2391   SMESH_MesherHelper helper( *_mesh );
2392   helper.SetSubShape( data._solid );
2393   helper.SetElementsOnShape( true );
2394
2395   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2396   TNode2Edge::iterator n2e2;
2397
2398   // collect _LayerEdge's of shapes they are based on
2399   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2400   const int nbShapes = getMeshDS()->MaxShapeIndex();
2401   edgesByGeom.resize( nbShapes+1 );
2402
2403   // set data of _EdgesOnShape's
2404   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2405   {
2406     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2407     while ( smIt->more() )
2408     {
2409       sm = smIt->next();
2410       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2411            !faceIds.count( sm->GetId() ))
2412         continue;
2413       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2414     }
2415   }
2416   // make _LayerEdge's
2417   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2418   {
2419     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2420     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2421     SMESH_ProxyMesh::SubMesh* proxySub =
2422       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2423
2424     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2425     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2426
2427     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2428     while ( eIt->more() )
2429     {
2430       const SMDS_MeshElement* face = eIt->next();
2431       double          faceMaxCosin = -1;
2432       _LayerEdge*     maxCosinEdge = 0;
2433       int             nbDegenNodes = 0;
2434
2435       newNodes.resize( face->NbCornerNodes() );
2436       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2437       {
2438         const SMDS_MeshNode* n = face->GetNode( i );
2439         const int      shapeID = n->getshapeId();
2440         const bool onDegenShap = helper.IsDegenShape( shapeID );
2441         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2442         if ( onDegenShap )
2443         {
2444           if ( onDegenEdge )
2445           {
2446             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2447             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2448             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2449             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2450               n = vN;
2451               nbDegenNodes++;
2452             }
2453           }
2454           else
2455           {
2456             nbDegenNodes++;
2457           }
2458         }
2459         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2460         if ( !(*n2e).second )
2461         {
2462           // add a _LayerEdge
2463           _LayerEdge* edge = new _LayerEdge();
2464           edge->_nodes.push_back( n );
2465           n2e->second = edge;
2466           edgesByGeom[ shapeID ]._edges.push_back( edge );
2467           const bool noShrink = data._noShrinkShapes.count( shapeID );
2468
2469           SMESH_TNodeXYZ xyz( n );
2470
2471           // set edge data or find already refined _LayerEdge and get data from it
2472           if (( !noShrink                                                     ) &&
2473               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2474               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2475               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2476           {
2477             _LayerEdge* foundEdge = (*n2e2).second;
2478             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2479             foundEdge->_pos.push_back( lastPos );
2480             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2481             const_cast< SMDS_MeshNode* >
2482               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2483           }
2484           else
2485           {
2486             if ( !noShrink )
2487             {
2488               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2489             }
2490             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2491               return false;
2492
2493             if ( edge->_nodes.size() < 2 )
2494               edge->Block( data );
2495               //data._noShrinkShapes.insert( shapeID );
2496           }
2497           dumpMove(edge->_nodes.back());
2498
2499           if ( edge->_cosin > faceMaxCosin )
2500           {
2501             faceMaxCosin = edge->_cosin;
2502             maxCosinEdge = edge;
2503           }
2504         }
2505         newNodes[ i ] = n2e->second->_nodes.back();
2506
2507         if ( onDegenEdge )
2508           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2509       }
2510       if ( newNodes.size() - nbDegenNodes < 2 )
2511         continue;
2512
2513       // create a temporary face
2514       const SMDS_MeshElement* newFace =
2515         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2516       proxySub->AddElement( newFace );
2517
2518       // compute inflation step size by min size of element on a convex surface
2519       if ( faceMaxCosin > theMinSmoothCosin )
2520         limitStepSize( data, face, maxCosinEdge );
2521
2522     } // loop on 2D elements on a FACE
2523   } // loop on FACEs of a SOLID to create _LayerEdge's
2524
2525
2526   // Set _LayerEdge::_neibors
2527   TNode2Edge::iterator n2e;
2528   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2529   {
2530     _EdgesOnShape& eos = data._edgesOnShape[iS];
2531     for ( size_t i = 0; i < eos._edges.size(); ++i )
2532     {
2533       _LayerEdge* edge = eos._edges[i];
2534       TIDSortedNodeSet nearNodes;
2535       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2536       while ( fIt->more() )
2537       {
2538         const SMDS_MeshElement* f = fIt->next();
2539         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2540           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2541       }
2542       nearNodes.erase( edge->_nodes[0] );
2543       edge->_neibors.reserve( nearNodes.size() );
2544       TIDSortedNodeSet::iterator node = nearNodes.begin();
2545       for ( ; node != nearNodes.end(); ++node )
2546         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2547           edge->_neibors.push_back( n2e->second );
2548     }
2549   }
2550
2551   data._epsilon = 1e-7;
2552   if ( data._stepSize < 1. )
2553     data._epsilon *= data._stepSize;
2554
2555   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2556     return false;
2557
2558   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2559   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2560
2561   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2562   const SMDS_MeshNode* nn[2];
2563   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2564   {
2565     _EdgesOnShape& eos = data._edgesOnShape[iS];
2566     for ( size_t i = 0; i < eos._edges.size(); ++i )
2567     {
2568       _LayerEdge* edge = eos._edges[i];
2569       if ( edge->IsOnEdge() )
2570       {
2571         // get neighbor nodes
2572         bool hasData = ( edge->_2neibors->_edges[0] );
2573         if ( hasData ) // _LayerEdge is a copy of another one
2574         {
2575           nn[0] = edge->_2neibors->srcNode(0);
2576           nn[1] = edge->_2neibors->srcNode(1);
2577         }
2578         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2579         {
2580           return false;
2581         }
2582         // set neighbor _LayerEdge's
2583         for ( int j = 0; j < 2; ++j )
2584         {
2585           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2586             return error("_LayerEdge not found by src node", data._index);
2587           edge->_2neibors->_edges[j] = n2e->second;
2588         }
2589         if ( !hasData )
2590           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2591       }
2592
2593       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2594       {
2595         _Simplex& s = edge->_simplices[j];
2596         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2597         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2598       }
2599
2600       // For an _LayerEdge on a degenerated EDGE, copy some data from
2601       // a corresponding _LayerEdge on a VERTEX
2602       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2603       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2604       {
2605         // Generally we should not get here
2606         if ( eos.ShapeType() != TopAbs_EDGE )
2607           continue;
2608         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2609         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2610         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2611           continue;
2612         const _LayerEdge* vEdge = n2e->second;
2613         edge->_normal    = vEdge->_normal;
2614         edge->_lenFactor = vEdge->_lenFactor;
2615         edge->_cosin     = vEdge->_cosin;
2616       }
2617
2618     } // loop on data._edgesOnShape._edges
2619   } // loop on data._edgesOnShape
2620
2621   // fix _LayerEdge::_2neibors on EDGEs to smooth
2622   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2623   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2624   //   if ( !e2c->second.IsNull() )
2625   //   {
2626   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2627   //       data.Sort2NeiborsOnEdge( eos->_edges );
2628   //   }
2629
2630   dumpFunctionEnd();
2631   return true;
2632 }
2633
2634 //================================================================================
2635 /*!
2636  * \brief Compute inflation step size by min size of element on a convex surface
2637  */
2638 //================================================================================
2639
2640 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2641                                      const SMDS_MeshElement* face,
2642                                      const _LayerEdge*       maxCosinEdge )
2643 {
2644   int iN = 0;
2645   double minSize = 10 * data._stepSize;
2646   const int nbNodes = face->NbCornerNodes();
2647   for ( int i = 0; i < nbNodes; ++i )
2648   {
2649     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2650     const SMDS_MeshNode*  curN = face->GetNode( i );
2651     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2652          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2653     {
2654       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2655       if ( dist < minSize )
2656         minSize = dist, iN = i;
2657     }
2658   }
2659   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2660   if ( newStep < data._stepSize )
2661   {
2662     data._stepSize = newStep;
2663     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2664     data._stepSizeNodes[0] = face->GetNode( iN );
2665     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2666   }
2667 }
2668
2669 //================================================================================
2670 /*!
2671  * \brief Compute inflation step size by min size of element on a convex surface
2672  */
2673 //================================================================================
2674
2675 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2676 {
2677   if ( minSize < data._stepSize )
2678   {
2679     data._stepSize = minSize;
2680     if ( data._stepSizeNodes[0] )
2681     {
2682       double dist =
2683         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2684       data._stepSizeCoeff = data._stepSize / dist;
2685     }
2686   }
2687 }
2688
2689 //================================================================================
2690 /*!
2691  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2692  */
2693 //================================================================================
2694
2695 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2696 {
2697   SMESH_MesherHelper helper( *_mesh );
2698
2699   const int nbTestPnt = 5; // on a FACE sub-shape
2700
2701   BRepLProp_SLProps surfProp( 2, 1e-6 );
2702   data._convexFaces.clear();
2703
2704   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2705   {
2706     _EdgesOnShape& eof = data._edgesOnShape[iS];
2707     if ( eof.ShapeType() != TopAbs_FACE ||
2708          data._ignoreFaceIds.count( eof._shapeID ))
2709       continue;
2710
2711     TopoDS_Face        F = TopoDS::Face( eof._shape );
2712     SMESH_subMesh *   sm = eof._subMesh;
2713     const TGeomID faceID = eof._shapeID;
2714
2715     BRepAdaptor_Surface surface( F, false );
2716     surfProp.SetSurface( surface );
2717
2718     bool isTooCurved = false;
2719
2720     _ConvexFace cnvFace;
2721     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2722     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2723     while ( smIt->more() )
2724     {
2725       sm = smIt->next();
2726       const TGeomID subID = sm->GetId();
2727       // find _LayerEdge's of a sub-shape
2728       _EdgesOnShape* eos;
2729       if (( eos = data.GetShapeEdges( subID )))
2730         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2731       else
2732         continue;
2733       // check concavity and curvature and limit data._stepSize
2734       const double minCurvature =
2735         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2736       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2737       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2738       {
2739         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2740         surfProp.SetParameters( uv.X(), uv.Y() );
2741         if ( !surfProp.IsCurvatureDefined() )
2742           continue;
2743         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2744         {
2745           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2746           isTooCurved = true;
2747         }
2748         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2749         {
2750           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2751           isTooCurved = true;
2752         }
2753       }
2754     } // loop on sub-shapes of the FACE
2755
2756     if ( !isTooCurved ) continue;
2757
2758     _ConvexFace & convFace =
2759       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2760
2761     convFace._face = F;
2762     convFace._normalsFixed = false;
2763
2764     // skip a closed surface (data._convexFaces is useful anyway)
2765     bool isClosedF = false;
2766     helper.SetSubShape( F );
2767     if ( helper.HasRealSeam() )
2768     {
2769       // in the closed surface there must be a closed EDGE
2770       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2771         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2772     }
2773     if ( isClosedF )
2774     {
2775       // limit _LayerEdge::_maxLen on the FACE
2776       const double minCurvature =
2777         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2778       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2779       if ( id2eos != cnvFace._subIdToEOS.end() )
2780       {
2781         _EdgesOnShape& eos = * id2eos->second;
2782         for ( size_t i = 0; i < eos._edges.size(); ++i )
2783         {
2784           _LayerEdge* ledge = eos._edges[ i ];
2785           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2786           surfProp.SetParameters( uv.X(), uv.Y() );
2787           if ( !surfProp.IsCurvatureDefined() )
2788             continue;
2789
2790           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2791             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2792
2793           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2794             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2795         }
2796       }
2797       continue;
2798     }
2799
2800     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2801     // prism distortion.
2802     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2803     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2804     {
2805       // there are _LayerEdge's on the FACE it-self;
2806       // select _LayerEdge's near EDGEs
2807       _EdgesOnShape& eos = * id2eos->second;
2808       for ( size_t i = 0; i < eos._edges.size(); ++i )
2809       {
2810         _LayerEdge* ledge = eos._edges[ i ];
2811         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2812           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2813           {
2814             convFace._simplexTestEdges.push_back( ledge );
2815             break;
2816           }
2817       }
2818     }
2819     else
2820     {
2821       // where there are no _LayerEdge's on a _ConvexFace,
2822       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2823       // so that collision of viscous internal faces is not detected by check of
2824       // intersection of _LayerEdge's with the viscous internal faces.
2825
2826       set< const SMDS_MeshNode* > usedNodes;
2827
2828       // look for _LayerEdge's with null _sWOL
2829       id2eos = convFace._subIdToEOS.begin();
2830       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2831       {
2832         _EdgesOnShape& eos = * id2eos->second;
2833         if ( !eos._sWOL.IsNull() )
2834           continue;
2835         for ( size_t i = 0; i < eos._edges.size(); ++i )
2836         {
2837           _LayerEdge* ledge = eos._edges[ i ];
2838           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2839           if ( !usedNodes.insert( srcNode ).second ) continue;
2840
2841           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2842           {
2843             usedNodes.insert( ledge->_simplices[i]._nPrev );
2844             usedNodes.insert( ledge->_simplices[i]._nNext );
2845           }
2846           convFace._simplexTestEdges.push_back( ledge );
2847         }
2848       }
2849     }
2850   } // loop on FACEs of data._solid
2851 }
2852
2853 //================================================================================
2854 /*!
2855  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2856  */
2857 //================================================================================
2858
2859 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2860 {
2861   // define allowed thickness
2862   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2863
2864   data._maxThickness = 0;
2865   data._minThickness = 1e100;
2866   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2867   for ( ; hyp != data._hyps.end(); ++hyp )
2868   {
2869     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2870     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2871   }
2872   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2873
2874   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2875   // boundry inclined to the shape at a sharp angle
2876
2877   //list< TGeomID > shapesToSmooth;
2878   TopTools_MapOfShape edgesOfSmooFaces;
2879
2880   SMESH_MesherHelper helper( *_mesh );
2881   bool ok = true;
2882
2883   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2884   data._nbShapesToSmooth = 0;
2885
2886   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2887   {
2888     _EdgesOnShape& eos = edgesByGeom[iS];
2889     eos._toSmooth = false;
2890     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2891       continue;
2892
2893     double tgtThick = eos._hyp.GetTotalThickness();
2894     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2895     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2896     {
2897       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2898       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2899       if ( eE.empty() ) continue;
2900
2901       double faceSize;
2902       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2903         if ( eE[i]->_cosin > theMinSmoothCosin )
2904         {
2905           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2906           while ( fIt->more() && !eos._toSmooth )
2907           {
2908             const SMDS_MeshElement* face = fIt->next();
2909             if ( face->getshapeId() == eos._shapeID &&
2910                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2911             {
2912               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2913             }
2914           }
2915         }
2916     }
2917     if ( eos._toSmooth )
2918     {
2919       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2920         edgesOfSmooFaces.Add( eExp.Current() );
2921
2922       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2923     }
2924     data._nbShapesToSmooth += eos._toSmooth;
2925
2926   }  // check FACEs
2927
2928   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2929   {
2930     _EdgesOnShape& eos = edgesByGeom[iS];
2931     eos._edgeSmoother = NULL;
2932     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2933     if ( !eos._hyp.ToSmooth() ) continue;
2934
2935     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2936     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2937       continue;
2938
2939     double tgtThick = eos._hyp.GetTotalThickness();
2940     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2941     {
2942       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2943       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2944       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2945       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2946       double angle    = eDir.Angle( eV[0]->_normal );
2947       double cosin    = Cos( angle );
2948       double cosinAbs = Abs( cosin );
2949       if ( cosinAbs > theMinSmoothCosin )
2950       {
2951         // always smooth analytic EDGEs
2952         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2953         eos._toSmooth = ! curve.IsNull();
2954
2955         // compare tgtThick with the length of an end segment
2956         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2957         while ( eIt->more() && !eos._toSmooth )
2958         {
2959           const SMDS_MeshElement* endSeg = eIt->next();
2960           if ( endSeg->getshapeId() == (int) iS )
2961           {
2962             double segLen =
2963               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2964             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2965           }
2966         }
2967         if ( eos._toSmooth )
2968         {
2969           eos._edgeSmoother = new _Smoother1D( curve, eos );
2970
2971           for ( size_t i = 0; i < eos._edges.size(); ++i )
2972             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2973         }
2974       }
2975     }
2976     data._nbShapesToSmooth += eos._toSmooth;
2977
2978   } // check EDGEs
2979
2980   // Reset _cosin if no smooth is allowed by the user
2981   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2982   {
2983     _EdgesOnShape& eos = edgesByGeom[iS];
2984     if ( eos._edges.empty() ) continue;
2985
2986     if ( !eos._hyp.ToSmooth() )
2987       for ( size_t i = 0; i < eos._edges.size(); ++i )
2988         eos._edges[i]->SetCosin( 0 );
2989   }
2990
2991
2992   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2993
2994   TopTools_MapOfShape c1VV;
2995
2996   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2997   {
2998     _EdgesOnShape& eos = edgesByGeom[iS];
2999     if ( eos._edges.empty() ||
3000          eos.ShapeType() != TopAbs_FACE ||
3001          !eos._toSmooth )
3002       continue;
3003
3004     // check EDGEs of a FACE
3005     TopTools_MapOfShape checkedEE, allVV;
3006     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3007     while ( !smQueue.empty() )
3008     {
3009       SMESH_subMesh* sm = smQueue.front();
3010       smQueue.pop_front();
3011       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3012       while ( smIt->more() )
3013       {
3014         sm = smIt->next();
3015         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3016           allVV.Add( sm->GetSubShape() );
3017         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3018              !checkedEE.Add( sm->GetSubShape() ))
3019           continue;
3020
3021         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3022         vector<_LayerEdge*>& eE = eoe->_edges;
3023         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3024           continue;
3025
3026         bool isC1 = true; // check continuity along an EDGE
3027         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3028           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3029         if ( !isC1 )
3030           continue;
3031
3032         // check that mesh faces are C1 as well
3033         {
3034           gp_XYZ norm1, norm2;
3035           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3036           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3037           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3038             continue;
3039           while ( fIt->more() && isC1 )
3040             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3041                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3042           if ( !isC1 )
3043             continue;
3044         }
3045
3046         // add the EDGE and an adjacent FACE to _eosC1
3047         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3048         while ( const TopoDS_Shape* face = fIt->next() )
3049         {
3050           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3051           if ( !eof ) continue; // other solid
3052           if ( !eos.HasC1( eoe ))
3053           {
3054             eos._eosC1.push_back( eoe );
3055             eoe->_toSmooth = false;
3056             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3057           }
3058           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3059           {
3060             eos._eosC1.push_back( eof );
3061             eof->_toSmooth = false;
3062             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3063             smQueue.push_back( eof->_subMesh );
3064           }
3065         }
3066       }
3067     }
3068     if ( eos._eosC1.empty() )
3069       continue;
3070
3071     // check VERTEXes of C1 FACEs
3072     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3073     for ( ; vIt.More(); vIt.Next() )
3074     {
3075       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3076       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3077         continue;
3078
3079       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3080       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3081       while ( const TopoDS_Shape* face = fIt->next() )
3082       {
3083         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3084         if ( !eof ) continue; // other solid
3085         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3086         if ( !isC1 )
3087           break;
3088       }
3089       if ( isC1 )
3090       {
3091         eos._eosC1.push_back( eov );
3092         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3093         c1VV.Add( eov->_shape );
3094       }
3095     }
3096
3097   } // fill _eosC1 of FACEs
3098
3099
3100   // Find C1 EDGEs
3101
3102   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3103
3104   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3105   {
3106     _EdgesOnShape& eov = edgesByGeom[iS];
3107     if ( eov._edges.empty() ||
3108          eov.ShapeType() != TopAbs_VERTEX ||
3109          c1VV.Contains( eov._shape ))
3110       continue;
3111     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3112
3113     // get directions of surrounding EDGEs
3114     dirOfEdges.clear();
3115     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3116     while ( const TopoDS_Shape* e = fIt->next() )
3117     {
3118       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3119       if ( !eoe ) continue; // other solid
3120       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3121       if ( !Precision::IsInfinite( eDir.X() ))
3122         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3123     }
3124
3125     // find EDGEs with C1 directions
3126     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3127       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3128         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3129         {
3130           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3131           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3132           if ( isC1 )
3133           {
3134             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3135             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3136             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3137             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3138             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3139             dirOfEdges[i].first = 0;
3140             dirOfEdges[j].first = 0;
3141           }
3142         }
3143   } // fill _eosC1 of VERTEXes
3144
3145
3146
3147   return ok;
3148 }
3149
3150 //================================================================================
3151 /*!
3152  * \brief initialize data of _EdgesOnShape
3153  */
3154 //================================================================================
3155
3156 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3157                                     SMESH_subMesh* sm,
3158                                     _SolidData&    data )
3159 {
3160   if ( !eos._shape.IsNull() ||
3161        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3162     return;
3163
3164   SMESH_MesherHelper helper( *_mesh );
3165
3166   eos._subMesh = sm;
3167   eos._shapeID = sm->GetId();
3168   eos._shape   = sm->GetSubShape();
3169   if ( eos.ShapeType() == TopAbs_FACE )
3170     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3171   eos._toSmooth = false;
3172   eos._data = &data;
3173
3174   // set _SWOL
3175   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3176     data._shrinkShape2Shape.find( eos._shapeID );
3177   if ( s2s != data._shrinkShape2Shape.end() )
3178     eos._sWOL = s2s->second;
3179
3180   eos._isRegularSWOL = true;
3181   if ( eos.SWOLType() == TopAbs_FACE )
3182   {
3183     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3184     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3185     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3186   }
3187
3188   // set _hyp
3189   if ( data._hyps.size() == 1 )
3190   {
3191     eos._hyp = data._hyps.back();
3192   }
3193   else
3194   {
3195     // compute average StdMeshers_ViscousLayers parameters
3196     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3197     if ( eos.ShapeType() == TopAbs_FACE )
3198     {
3199       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3200         eos._hyp = f2hyp->second;
3201     }
3202     else
3203     {
3204       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3205       while ( const TopoDS_Shape* face = fIt->next() )
3206       {
3207         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3208         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3209           eos._hyp.Add( f2hyp->second );
3210       }
3211     }
3212   }
3213
3214   // set _faceNormals
3215   if ( ! eos._hyp.UseSurfaceNormal() )
3216   {
3217     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3218     {
3219       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3220       eos._faceNormals.resize( smDS->NbElements() );
3221
3222       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3223       for ( int iF = 0; eIt->more(); ++iF )
3224       {
3225         const SMDS_MeshElement* face = eIt->next();
3226         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3227           eos._faceNormals[iF].SetCoord( 0,0,0 );
3228       }
3229
3230       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3231         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3232           eos._faceNormals[iF].Reverse();
3233     }
3234     else // find EOS of adjacent FACEs
3235     {
3236       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3237       while ( const TopoDS_Shape* face = fIt->next() )
3238       {
3239         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3240         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3241         if ( eos._faceEOS.back()->_shape.IsNull() )
3242           // avoid using uninitialised _shapeID in GetNormal()
3243           eos._faceEOS.back()->_shapeID = faceID;
3244       }
3245     }
3246   }
3247 }
3248
3249 //================================================================================
3250 /*!
3251  * \brief Returns normal of a face
3252  */
3253 //================================================================================
3254
3255 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3256 {
3257   bool ok = false;
3258   const _EdgesOnShape* eos = 0;
3259
3260   if ( face->getshapeId() == _shapeID )
3261   {
3262     eos = this;
3263   }
3264   else
3265   {
3266     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3267       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3268         eos = _faceEOS[ iF ];
3269   }
3270
3271   if (( eos ) &&
3272       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3273   {
3274     norm = eos->_faceNormals[ face->getIdInShape() ];
3275   }
3276   else if ( !eos )
3277   {
3278     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3279               << " on _shape #" << _shapeID );
3280   }
3281   return ok;
3282 }
3283
3284
3285 //================================================================================
3286 /*!
3287  * \brief Set data of _LayerEdge needed for smoothing
3288  */
3289 //================================================================================
3290
3291 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3292                                   _EdgesOnShape&      eos,
3293                                   SMESH_MesherHelper& helper,
3294                                   _SolidData&         data)
3295 {
3296   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3297
3298   edge._len       = 0;
3299   edge._maxLen    = Precision::Infinite();
3300   edge._minAngle  = 0;
3301   edge._2neibors  = 0;
3302   edge._curvature = 0;
3303   edge._flags     = 0;
3304
3305   // --------------------------
3306   // Compute _normal and _cosin
3307   // --------------------------
3308
3309   edge._cosin     = 0;
3310   edge._lenFactor = 1.;
3311   edge._normal.SetCoord(0,0,0);
3312   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3313
3314   int totalNbFaces = 0;
3315   TopoDS_Face F;
3316   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3317   gp_Vec geomNorm;
3318   bool normOK = true;
3319
3320   const bool onShrinkShape = !eos._sWOL.IsNull();
3321   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3322                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3323
3324   // get geom FACEs the node lies on
3325   //if ( useGeometry )
3326   {
3327     set<TGeomID> faceIds;
3328     if  ( eos.ShapeType() == TopAbs_FACE )
3329     {
3330       faceIds.insert( eos._shapeID );
3331     }
3332     else
3333     {
3334       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3335       while ( fIt->more() )
3336         faceIds.insert( fIt->next()->getshapeId() );
3337     }
3338     set<TGeomID>::iterator id = faceIds.begin();
3339     for ( ; id != faceIds.end(); ++id )
3340     {
3341       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3342       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3343         continue;
3344       F = TopoDS::Face( s );
3345       face2Norm[ totalNbFaces ].first = F;
3346       totalNbFaces++;
3347     }
3348   }
3349
3350   // find _normal
3351   if ( useGeometry )
3352   {
3353     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3354                       eos.SWOLType()  == TopAbs_FACE  &&
3355                       totalNbFaces > 1 );
3356
3357     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3358     {
3359       if ( eos.SWOLType() == TopAbs_EDGE )
3360       {
3361         // inflate from VERTEX along EDGE
3362         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3363       }
3364       else if ( eos.ShapeType() == TopAbs_VERTEX )
3365       {
3366         // inflate from VERTEX along FACE
3367         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3368                                    node, helper, normOK, &edge._cosin);
3369       }
3370       else
3371       {
3372         // inflate from EDGE along FACE
3373         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3374                                    node, helper, normOK);
3375       }
3376     }
3377     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3378     {
3379       if ( fromVonF )
3380         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3381
3382       int nbOkNorms = 0;
3383       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3384       {
3385         F = face2Norm[ iF ].first;
3386         geomNorm = getFaceNormal( node, F, helper, normOK );
3387         if ( !normOK ) continue;
3388         nbOkNorms++;
3389
3390         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3391           geomNorm.Reverse();
3392         face2Norm[ iF ].second = geomNorm.XYZ();
3393         edge._normal += geomNorm.XYZ();
3394       }
3395       if ( nbOkNorms == 0 )
3396         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3397
3398       if ( totalNbFaces >= 3 )
3399       {
3400         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3401       }
3402
3403       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3404       {
3405         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3406         edge._normal.SetCoord( 0,0,0 );
3407         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3408         {
3409           const TopoDS_Face& F = face2Norm[iF].first;
3410           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3411           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3412             geomNorm.Reverse();
3413           if ( normOK )
3414             face2Norm[ iF ].second = geomNorm.XYZ();
3415           edge._normal += face2Norm[ iF ].second;
3416         }
3417       }
3418     }
3419   }
3420   else // !useGeometry - get _normal using surrounding mesh faces
3421   {
3422     edge._normal = getWeigthedNormal( &edge );
3423
3424     // set<TGeomID> faceIds;
3425     //
3426     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3427     // while ( fIt->more() )
3428     // {
3429     //   const SMDS_MeshElement* face = fIt->next();
3430     //   if ( eos.GetNormal( face, geomNorm ))
3431     //   {
3432     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3433     //       continue; // use only one mesh face on FACE
3434     //     edge._normal += geomNorm.XYZ();
3435     //     totalNbFaces++;
3436     //   }
3437     // }
3438   }
3439
3440   // compute _cosin
3441   //if ( eos._hyp.UseSurfaceNormal() )
3442   {
3443     switch ( eos.ShapeType() )
3444     {
3445     case TopAbs_FACE: {
3446       edge._cosin = 0;
3447       break;
3448     }
3449     case TopAbs_EDGE: {
3450       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3451       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3452       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3453       edge._cosin      = Cos( angle );
3454       break;
3455     }
3456     case TopAbs_VERTEX: {
3457       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3458       {
3459         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3460         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3461         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3462         edge._cosin      = Cos( angle );
3463         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3464           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3465           {
3466             F = face2Norm[ iF ].first;
3467             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3468             if ( normOK ) {
3469               double angle = inFaceDir.Angle( edge._normal );
3470               double cosin = Cos( angle );
3471               if ( Abs( cosin ) > Abs( edge._cosin ))
3472                 edge._cosin = cosin;
3473             }
3474           }
3475       }
3476       break;
3477     }
3478     default:
3479       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3480     }
3481   }
3482
3483   double normSize = edge._normal.SquareModulus();
3484   if ( normSize < numeric_limits<double>::min() )
3485     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3486
3487   edge._normal /= sqrt( normSize );
3488
3489   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3490   {
3491     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3492     edge._nodes.resize( 1 );
3493     edge._normal.SetCoord( 0,0,0 );
3494     edge._maxLen = 0;
3495   }
3496
3497   // Set the rest data
3498   // --------------------
3499
3500   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3501
3502   if ( onShrinkShape )
3503   {
3504     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3505     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3506       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3507
3508     // set initial position which is parameters on _sWOL in this case
3509     if ( eos.SWOLType() == TopAbs_EDGE )
3510     {
3511       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3512       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3513       if ( edge._nodes.size() > 1 )
3514         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3515     }
3516     else // eos.SWOLType() == TopAbs_FACE
3517     {
3518       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3519       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3520       if ( edge._nodes.size() > 1 )
3521         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3522     }
3523
3524     if ( edge._nodes.size() > 1 )
3525     {
3526       // check if an angle between a FACE with layers and SWOL is sharp,
3527       // else the edge should not inflate
3528       F.Nullify();
3529       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3530         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3531           F = face2Norm[iF].first;
3532       if ( !F.IsNull())
3533       {
3534         geomNorm = getFaceNormal( node, F, helper, normOK );
3535         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3536           geomNorm.Reverse(); // inside the SOLID
3537         if ( geomNorm * edge._normal < -0.001 )
3538         {
3539           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3540           edge._nodes.resize( 1 );
3541         }
3542         else if ( edge._lenFactor > 3 )
3543         {
3544           edge._lenFactor = 2;
3545           edge.Set( _LayerEdge::RISKY_SWOL );
3546         }
3547       }
3548     }
3549   }
3550   else
3551   {
3552     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3553
3554     if ( eos.ShapeType() == TopAbs_FACE )
3555     {
3556       double angle;
3557       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3558       {
3559         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3560         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3561       }
3562     }
3563   }
3564
3565   // Set neighbor nodes for a _LayerEdge based on EDGE
3566
3567   if ( eos.ShapeType() == TopAbs_EDGE /*||
3568        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3569   {
3570     edge._2neibors = new _2NearEdges;
3571     // target nodes instead of source ones will be set later
3572   }
3573
3574   return true;
3575 }
3576
3577 //================================================================================
3578 /*!
3579  * \brief Return normal to a FACE at a node
3580  *  \param [in] n - node
3581  *  \param [in] face - FACE
3582  *  \param [in] helper - helper
3583  *  \param [out] isOK - true or false
3584  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3585  *  \return gp_XYZ - normal
3586  */
3587 //================================================================================
3588
3589 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3590                                       const TopoDS_Face&   face,
3591                                       SMESH_MesherHelper&  helper,
3592                                       bool&                isOK,
3593                                       bool                 shiftInside)
3594 {
3595   gp_XY uv;
3596   if ( shiftInside )
3597   {
3598     // get a shifted position
3599     gp_Pnt p = SMESH_TNodeXYZ( node );
3600     gp_XYZ shift( 0,0,0 );
3601     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3602     switch ( S.ShapeType() ) {
3603     case TopAbs_VERTEX:
3604     {
3605       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3606       break;
3607     }
3608     case TopAbs_EDGE:
3609     {
3610       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3611       break;
3612     }
3613     default:
3614       isOK = false;
3615     }
3616     if ( isOK )
3617       shift.Normalize();
3618     p.Translate( shift * 1e-5 );
3619
3620     TopLoc_Location loc;
3621     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3622
3623     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3624     
3625     projector.Perform( p );
3626     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3627     {
3628       isOK = false;
3629       return p.XYZ();
3630     }
3631     Quantity_Parameter U,V;
3632     projector.LowerDistanceParameters(U,V);
3633     uv.SetCoord( U,V );
3634   }
3635   else
3636   {
3637     uv = helper.GetNodeUV( face, node, 0, &isOK );
3638   }
3639
3640   gp_Dir normal;
3641   isOK = false;
3642
3643   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3644
3645   if ( !shiftInside &&
3646        helper.IsDegenShape( node->getshapeId() ) &&
3647        getFaceNormalAtSingularity( uv, face, helper, normal ))
3648   {
3649     isOK = true;
3650     return normal.XYZ();
3651   }
3652
3653   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3654   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3655
3656   if ( pointKind == IMPOSSIBLE &&
3657        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3658   {
3659     // probably NormEstim() failed due to a too high tolerance
3660     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3661     isOK = ( pointKind < IMPOSSIBLE );
3662   }
3663   if ( pointKind < IMPOSSIBLE )
3664   {
3665     if ( pointKind != REGULAR &&
3666          !shiftInside &&
3667          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3668     {
3669       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3670       if ( normShift * normal.XYZ() < 0. )
3671         normal = normShift;
3672     }
3673     isOK = true;
3674   }
3675
3676   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3677   {
3678     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3679
3680     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3681     while ( fIt->more() )
3682     {
3683       const SMDS_MeshElement* f = fIt->next();
3684       if ( f->getshapeId() == faceID )
3685       {
3686         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3687         if ( isOK )
3688         {
3689           TopoDS_Face ff = face;
3690           ff.Orientation( TopAbs_FORWARD );
3691           if ( helper.IsReversedSubMesh( ff ))
3692             normal.Reverse();
3693           break;
3694         }
3695       }
3696     }
3697   }
3698   return normal.XYZ();
3699 }
3700
3701 //================================================================================
3702 /*!
3703  * \brief Try to get normal at a singularity of a surface basing on it's nature
3704  */
3705 //================================================================================
3706
3707 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3708                                                   const TopoDS_Face&  face,
3709                                                   SMESH_MesherHelper& helper,
3710                                                   gp_Dir&             normal )
3711 {
3712   BRepAdaptor_Surface surface( face );
3713   gp_Dir axis;
3714   if ( !getRovolutionAxis( surface, axis ))
3715     return false;
3716
3717   double f,l, d, du, dv;
3718   f = surface.FirstUParameter();
3719   l = surface.LastUParameter();
3720   d = ( uv.X() - f ) / ( l - f );
3721   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3722   f = surface.FirstVParameter();
3723   l = surface.LastVParameter();
3724   d = ( uv.Y() - f ) / ( l - f );
3725   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3726
3727   gp_Dir refDir;
3728   gp_Pnt2d testUV = uv;
3729   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3730   double tol = 1e-5;
3731   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3732   for ( int iLoop = 0; true ; ++iLoop )
3733   {
3734     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3735     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3736       break;
3737     if ( iLoop > 20 )
3738       return false;
3739     tol /= 10.;
3740   }
3741
3742   if ( axis * refDir < 0. )
3743     axis.Reverse();
3744
3745   normal = axis;
3746
3747   return true;
3748 }
3749
3750 //================================================================================
3751 /*!
3752  * \brief Return a normal at a node weighted with angles taken by faces
3753  */
3754 //================================================================================
3755
3756 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3757 {
3758   const SMDS_MeshNode* n = edge->_nodes[0];
3759
3760   gp_XYZ resNorm(0,0,0);
3761   SMESH_TNodeXYZ p0( n ), pP, pN;
3762   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3763   {
3764     pP.Set( edge->_simplices[i]._nPrev );
3765     pN.Set( edge->_simplices[i]._nNext );
3766     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3767     double l0P = v0P.SquareMagnitude();
3768     double l0N = v0N.SquareMagnitude();
3769     double lPN = vPN.SquareMagnitude();
3770     if ( l0P < std::numeric_limits<double>::min() ||
3771          l0N < std::numeric_limits<double>::min() ||
3772          lPN < std::numeric_limits<double>::min() )
3773       continue;
3774     double lNorm = norm.SquareMagnitude();
3775     double  sin2 = lNorm / l0P / l0N;
3776     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3777
3778     double weight = sin2 * angle / lPN;
3779     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3780   }
3781
3782   return resNorm;
3783 }
3784
3785 //================================================================================
3786 /*!
3787  * \brief Return a normal at a node by getting a common point of offset planes
3788  *        defined by the FACE normals
3789  */
3790 //================================================================================
3791
3792 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3793                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3794                                            int                              nbFaces,
3795                                            bool                             lastNoOffset)
3796 {
3797   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3798
3799   gp_XYZ resNorm(0,0,0);
3800   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3801   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3802   {
3803     for ( int i = 0; i < nbFaces; ++i )
3804       resNorm += f2Normal[i].second;
3805     return resNorm;
3806   }
3807
3808   // prepare _OffsetPlane's
3809   vector< _OffsetPlane > pln( nbFaces );
3810   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3811   {
3812     pln[i]._faceIndex = i;
3813     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3814   }
3815   if ( lastNoOffset )
3816   {
3817     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3818     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3819   }
3820
3821   // intersect neighboring OffsetPlane's
3822   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3823   while ( const TopoDS_Shape* edge = edgeIt->next() )
3824   {
3825     int f1 = -1, f2 = -1;
3826     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3827       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3828         (( f1 < 0 ) ? f1 : f2 ) = i;
3829
3830     if ( f2 >= 0 )
3831       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3832   }
3833
3834   // get a common point
3835   gp_XYZ commonPnt( 0, 0, 0 );
3836   int nbPoints = 0;
3837   bool isPointFound;
3838   for ( int i = 0; i < nbFaces; ++i )
3839   {
3840     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3841     nbPoints  += isPointFound;
3842   }
3843   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3844   if ( nbPoints == 0 )
3845     return wgtNorm;
3846
3847   commonPnt /= nbPoints;
3848   resNorm = commonPnt - p0;
3849   if ( lastNoOffset )
3850     return resNorm;
3851
3852   // choose the best among resNorm and wgtNorm
3853   resNorm.Normalize();
3854   wgtNorm.Normalize();
3855   double resMinDot = std::numeric_limits<double>::max();
3856   double wgtMinDot = std::numeric_limits<double>::max();
3857   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3858   {
3859     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3860     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3861   }
3862
3863   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3864   {
3865     edge->Set( _LayerEdge::MULTI_NORMAL );
3866   }
3867
3868   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3869 }
3870
3871 //================================================================================
3872 /*!
3873  * \brief Compute line of intersection of 2 planes
3874  */
3875 //================================================================================
3876
3877 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3878                                             const TopoDS_Edge&   E,
3879                                             const TopoDS_Vertex& V )
3880 {
3881   int iNext = bool( _faceIndexNext[0] >= 0 );
3882   _faceIndexNext[ iNext ] = pln._faceIndex;
3883
3884   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3885   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3886
3887   gp_XYZ lineDir = n1 ^ n2;
3888
3889   double x = Abs( lineDir.X() );
3890   double y = Abs( lineDir.Y() );
3891   double z = Abs( lineDir.Z() );
3892
3893   int cooMax; // max coordinate
3894   if (x > y) {
3895     if (x > z) cooMax = 1;
3896     else       cooMax = 3;
3897   }
3898   else {
3899     if (y > z) cooMax = 2;
3900     else       cooMax = 3;
3901   }
3902
3903   gp_Pnt linePos;
3904   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3905   {
3906     // parallel planes - intersection is an offset of the common EDGE
3907     gp_Pnt p = BRep_Tool::Pnt( V );
3908     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3909     lineDir  = getEdgeDir( E, V );
3910   }
3911   else
3912   {
3913     // the constants in the 2 plane equations
3914     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3915     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3916
3917     switch ( cooMax ) {
3918     case 1:
3919       linePos.SetX(  0 );
3920       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3921       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3922       break;
3923     case 2:
3924       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3925       linePos.SetY(  0 );
3926       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3927       break;
3928     case 3:
3929       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3930       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3931       linePos.SetZ(  0 );
3932     }
3933   }
3934   gp_Lin& line = _lines[ iNext ];
3935   line.SetDirection( lineDir );
3936   line.SetLocation ( linePos );
3937
3938   _isLineOK[ iNext ] = true;
3939
3940
3941   iNext = bool( pln._faceIndexNext[0] >= 0 );
3942   pln._lines        [ iNext ] = line;
3943   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3944   pln._isLineOK     [ iNext ] = true;
3945 }
3946
3947 //================================================================================
3948 /*!
3949  * \brief Computes intersection point of two _lines
3950  */
3951 //================================================================================
3952
3953 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
3954                                     const TopoDS_Vertex & V) const
3955 {
3956   gp_XYZ p( 0,0,0 );
3957   isFound = false;
3958
3959   if ( NbLines() == 2 )
3960   {
3961     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3962     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
3963     if ( Abs( dot01 ) > 0.05 )
3964     {
3965       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3966       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
3967       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3968       isFound = true;
3969     }
3970     else
3971     {
3972       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
3973       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
3974       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
3975       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
3976       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
3977       isFound = true;
3978     }
3979   }
3980
3981   return p;
3982 }
3983
3984 //================================================================================
3985 /*!
3986  * \brief Find 2 neigbor nodes of a node on EDGE
3987  */
3988 //================================================================================
3989
3990 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3991                                         const SMDS_MeshNode*& n1,
3992                                         const SMDS_MeshNode*& n2,
3993                                         _EdgesOnShape&        eos,
3994                                         _SolidData&           data)
3995 {
3996   const SMDS_MeshNode* node = edge->_nodes[0];
3997   const int        shapeInd = eos._shapeID;
3998   SMESHDS_SubMesh*   edgeSM = 0;
3999   if ( eos.ShapeType() == TopAbs_EDGE )
4000   {
4001     edgeSM = eos._subMesh->GetSubMeshDS();
4002     if ( !edgeSM || edgeSM->NbElements() == 0 )
4003       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4004   }
4005   int iN = 0;
4006   n2 = 0;
4007   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4008   while ( eIt->more() && !n2 )
4009   {
4010     const SMDS_MeshElement* e = eIt->next();
4011     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4012     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4013     if ( edgeSM )
4014     {
4015       if (!edgeSM->Contains(e)) continue;
4016     }
4017     else
4018     {
4019       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4020       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4021     }
4022     ( iN++ ? n2 : n1 ) = nNeibor;
4023   }
4024   if ( !n2 )
4025     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4026   return true;
4027 }
4028
4029 //================================================================================
4030 /*!
4031  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4032  */
4033 //================================================================================
4034
4035 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4036                                      const SMDS_MeshNode* n2,
4037                                      const _EdgesOnShape& eos,
4038                                      SMESH_MesherHelper&  helper)
4039 {
4040   if ( eos.ShapeType() != TopAbs_EDGE )
4041     return;
4042
4043   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4044   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4045   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4046
4047   // Set _curvature
4048
4049   double      sumLen = vec1.Modulus() + vec2.Modulus();
4050   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4051   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4052   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4053   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4054   if ( _curvature ) delete _curvature;
4055   _curvature = _Curvature::New( avgNormProj, avgLen );
4056   // if ( _curvature )
4057   //   debugMsg( _nodes[0]->GetID()
4058   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4059   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4060   //             << _curvature->lenDelta(0) );
4061
4062   // Set _plnNorm
4063
4064   if ( eos._sWOL.IsNull() )
4065   {
4066     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4067     // if ( SMESH_Algo::isDegenerated( E ))
4068     //   return;
4069     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4070     gp_XYZ plnNorm = dirE ^ _normal;
4071     double proj0   = plnNorm * vec1;
4072     double proj1   = plnNorm * vec2;
4073     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4074     {
4075       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4076       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4077     }
4078   }
4079 }
4080
4081 //================================================================================
4082 /*!
4083  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4084  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4085  */
4086 //================================================================================
4087
4088 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4089                          _EdgesOnShape&      eos,
4090                          SMESH_MesherHelper& helper )
4091 {
4092   _nodes     = other._nodes;
4093   _normal    = other._normal;
4094   _len       = 0;
4095   _lenFactor = other._lenFactor;
4096   _cosin     = other._cosin;
4097   _2neibors  = other._2neibors;
4098   _curvature = 0; std::swap( _curvature, other._curvature );
4099   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4100
4101   gp_XYZ lastPos( 0,0,0 );
4102   if ( eos.SWOLType() == TopAbs_EDGE )
4103   {
4104     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4105     _pos.push_back( gp_XYZ( u, 0, 0));
4106
4107     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4108     lastPos.SetX( u );
4109   }
4110   else // TopAbs_FACE
4111   {
4112     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4113     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4114
4115     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4116     lastPos.SetX( uv.X() );
4117     lastPos.SetY( uv.Y() );
4118   }
4119   return lastPos;
4120 }
4121
4122 //================================================================================
4123 /*!
4124  * \brief Set _cosin and _lenFactor
4125  */
4126 //================================================================================
4127
4128 void _LayerEdge::SetCosin( double cosin )
4129 {
4130   _cosin = cosin;
4131   cosin = Abs( _cosin );
4132   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4133   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4134 }
4135
4136 //================================================================================
4137 /*!
4138  * \brief Check if another _LayerEdge is a neighbor on EDGE
4139  */
4140 //================================================================================
4141
4142 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4143 {
4144   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4145           ( edge->_2neibors && edge->_2neibors->include( this )));
4146 }
4147
4148 //================================================================================
4149 /*!
4150  * \brief Fills a vector<_Simplex > 
4151  */
4152 //================================================================================
4153
4154 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4155                              vector<_Simplex>&    simplices,
4156                              const set<TGeomID>&  ingnoreShapes,
4157                              const _SolidData*    dataToCheckOri,
4158                              const bool           toSort)
4159 {
4160   simplices.clear();
4161   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4162   while ( fIt->more() )
4163   {
4164     const SMDS_MeshElement* f = fIt->next();
4165     const TGeomID    shapeInd = f->getshapeId();
4166     if ( ingnoreShapes.count( shapeInd )) continue;
4167     const int nbNodes = f->NbCornerNodes();
4168     const int  srcInd = f->GetNodeIndex( node );
4169     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4170     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4171     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4172     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4173       std::swap( nPrev, nNext );
4174     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4175   }
4176
4177   if ( toSort )
4178     SortSimplices( simplices );
4179 }
4180
4181 //================================================================================
4182 /*!
4183  * \brief Set neighbor simplices side by side
4184  */
4185 //================================================================================
4186
4187 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4188 {
4189   vector<_Simplex> sortedSimplices( simplices.size() );
4190   sortedSimplices[0] = simplices[0];
4191   size_t nbFound = 0;
4192   for ( size_t i = 1; i < simplices.size(); ++i )
4193   {
4194     for ( size_t j = 1; j < simplices.size(); ++j )
4195       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4196       {
4197         sortedSimplices[i] = simplices[j];
4198         nbFound++;
4199         break;
4200       }
4201   }
4202   if ( nbFound == simplices.size() - 1 )
4203     simplices.swap( sortedSimplices );
4204 }
4205
4206 //================================================================================
4207 /*!
4208  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4209  */
4210 //================================================================================
4211
4212 void _ViscousBuilder::makeGroupOfLE()
4213 {
4214 #ifdef _DEBUG_
4215   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4216   {
4217     if ( _sdVec[i]._n2eMap.empty() ) continue;
4218
4219     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4220     TNode2Edge::iterator n2e;
4221     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4222     {
4223       _LayerEdge* le = n2e->second;
4224       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4225       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4226       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4227       if ( le ) {
4228         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4229                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4230       }
4231     }
4232     dumpFunctionEnd();
4233
4234     dumpFunction( SMESH_Comment("makeNormals") << i );
4235     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4236     {
4237       _LayerEdge* edge = n2e->second;
4238       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4239       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4240       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4241               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4242     }
4243     dumpFunctionEnd();
4244
4245     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4246     dumpCmd( "faceId1 = mesh.NbElements()" );
4247     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4248     for ( ; fExp.More(); fExp.Next() )
4249     {
4250       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4251       {
4252         if ( sm->NbElements() == 0 ) continue;
4253         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4254         while ( fIt->more())
4255         {
4256           const SMDS_MeshElement* e = fIt->next();
4257           SMESH_Comment cmd("mesh.AddFace([");
4258           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4259             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4260           dumpCmd( cmd );
4261         }
4262       }
4263     }
4264     dumpCmd( "faceId2 = mesh.NbElements()" );
4265     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4266              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4267              << "'%s-%s' % (faceId1+1, faceId2))");
4268     dumpFunctionEnd();
4269   }
4270 #endif
4271 }
4272
4273 //================================================================================
4274 /*!
4275  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4276  */
4277 //================================================================================
4278
4279 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4280 {
4281   data._geomSize = Precision::Infinite();
4282   double intersecDist;
4283   const SMDS_MeshElement* face;
4284   SMESH_MesherHelper helper( *_mesh );
4285
4286   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4287     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4288                                            data._proxyMesh->GetFaces( data._solid )));
4289
4290   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4291   {
4292     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4293     if ( eos._edges.empty() )
4294       continue;
4295     // get neighbor faces intersection with which should not be considered since
4296     // collisions are avoided by means of smoothing
4297     set< TGeomID > neighborFaces;
4298     if ( eos._hyp.ToSmooth() )
4299     {
4300       SMESH_subMeshIteratorPtr subIt =
4301         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4302       while ( subIt->more() )
4303       {
4304         SMESH_subMesh* sm = subIt->next();
4305         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4306         while ( const TopoDS_Shape* face = fIt->next() )
4307           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4308       }
4309     }
4310     // find intersections
4311     double thinkness = eos._hyp.GetTotalThickness();
4312     for ( size_t i = 0; i < eos._edges.size(); ++i )
4313     {
4314       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4315       eos._edges[i]->_maxLen = thinkness;
4316       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4317       if ( intersecDist > 0 && face )
4318       {
4319         data._geomSize = Min( data._geomSize, intersecDist );
4320         if ( !neighborFaces.count( face->getshapeId() ))
4321           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4322       }
4323     }
4324   }
4325 }
4326
4327 //================================================================================
4328 /*!
4329  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4330  */
4331 //================================================================================
4332
4333 bool _ViscousBuilder::inflate(_SolidData& data)
4334 {
4335   SMESH_MesherHelper helper( *_mesh );
4336
4337   // Limit inflation step size by geometry size found by itersecting
4338   // normals of _LayerEdge's with mesh faces
4339   if ( data._stepSize > 0.3 * data._geomSize )
4340     limitStepSize( data, 0.3 * data._geomSize );
4341
4342   const double tgtThick = data._maxThickness;
4343   if ( data._stepSize > data._minThickness )
4344     limitStepSize( data, data._minThickness );
4345
4346   if ( data._stepSize < 1. )
4347     data._epsilon = data._stepSize * 1e-7;
4348
4349   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4350
4351   findCollisionEdges( data, helper );
4352
4353   limitMaxLenByCurvature( data, helper );
4354
4355   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4356   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4357     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4358          data._edgesOnShape[i]._edges.size() > 0 &&
4359          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4360     {
4361       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4362       data._edgesOnShape[i]._edges[0]->Block( data );
4363     }
4364
4365   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4366
4367   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4368   int nbSteps = 0, nbRepeats = 0;
4369   while ( avgThick < 0.99 )
4370   {
4371     // new target length
4372     double prevThick = curThick;
4373     curThick += data._stepSize;
4374     if ( curThick > tgtThick )
4375     {
4376       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4377       nbRepeats++;
4378     }
4379
4380     double stepSize = curThick - prevThick;
4381     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4382
4383     // Elongate _LayerEdge's
4384     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4385     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4386     {
4387       _EdgesOnShape& eos = data._edgesOnShape[iS];
4388       if ( eos._edges.empty() ) continue;
4389
4390       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4391       for ( size_t i = 0; i < eos._edges.size(); ++i )
4392       {
4393         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4394       }
4395     }
4396     dumpFunctionEnd();
4397
4398     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4399       return false;
4400
4401     // Improve and check quality
4402     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4403     {
4404       if ( nbSteps > 0 )
4405       {
4406 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4407         debugMsg("NOT INVALIDATED STEP!");
4408         return error("Smoothing failed", data._index);
4409 #endif
4410         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4411         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4412         {
4413           _EdgesOnShape& eos = data._edgesOnShape[iS];
4414           for ( size_t i = 0; i < eos._edges.size(); ++i )
4415             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4416         }
4417         dumpFunctionEnd();
4418       }
4419       break; // no more inflating possible
4420     }
4421     nbSteps++;
4422
4423     // Evaluate achieved thickness
4424     avgThick = 0;
4425     int nbActiveEdges = 0;
4426     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4427     {
4428       _EdgesOnShape& eos = data._edgesOnShape[iS];
4429       if ( eos._edges.empty() ) continue;
4430
4431       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4432       for ( size_t i = 0; i < eos._edges.size(); ++i )
4433       {
4434         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4435         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4436       }
4437     }
4438     avgThick /= data._n2eMap.size();
4439     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4440
4441 #ifdef BLOCK_INFLATION
4442     if ( nbActiveEdges == 0 )
4443     {
4444       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4445       break;
4446     }
4447 #else
4448     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4449     {
4450       debugMsg( "-- Stop inflation since "
4451                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4452                 << tgtThick * avgThick << " ) * " << safeFactor );
4453       break;
4454     }
4455 #endif
4456     // new step size
4457     limitStepSize( data, 0.25 * distToIntersection );
4458     if ( data._stepSizeNodes[0] )
4459       data._stepSize = data._stepSizeCoeff *
4460         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4461
4462   } // while ( avgThick < 0.99 )
4463
4464   if ( nbSteps == 0 )
4465     return error("failed at the very first inflation step", data._index);
4466
4467   if ( avgThick < 0.99 )
4468   {
4469     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4470     {
4471       data._proxyMesh->_warning.reset
4472         ( new SMESH_ComputeError (COMPERR_WARNING,
4473                                   SMESH_Comment("Thickness ") << tgtThick <<
4474                                   " of viscous layers not reached,"
4475                                   " average reached thickness is " << avgThick*tgtThick));
4476     }
4477   }
4478
4479   // Restore position of src nodes moved by inflation on _noShrinkShapes
4480   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4481   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4482   {
4483     _EdgesOnShape& eos = data._edgesOnShape[iS];
4484     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4485       for ( size_t i = 0; i < eos._edges.size(); ++i )
4486       {
4487         restoreNoShrink( *eos._edges[ i ] );
4488       }
4489   }
4490   dumpFunctionEnd();
4491
4492   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4493 }
4494
4495 //================================================================================
4496 /*!
4497  * \brief Improve quality of layer inner surface and check intersection
4498  */
4499 //================================================================================
4500
4501 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4502                                      const int   infStep,
4503                                      double &    distToIntersection)
4504 {
4505   if ( data._nbShapesToSmooth == 0 )
4506     return true; // no shapes needing smoothing
4507
4508   bool moved, improved;
4509   double vol;
4510   vector< _LayerEdge* >    movedEdges, badEdges;
4511   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4512   vector< bool >           isConcaveFace;
4513
4514   SMESH_MesherHelper helper(*_mesh);
4515   Handle(ShapeAnalysis_Surface) surface;
4516   TopoDS_Face F;
4517
4518   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4519   {
4520     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4521
4522     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4523     {
4524       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4525       if ( !eos._toSmooth ||
4526            eos.ShapeType() != shapeType ||
4527            eos._edges.empty() )
4528         continue;
4529
4530       // already smoothed?
4531       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4532       // if ( !toSmooth ) continue;
4533
4534       if ( !eos._hyp.ToSmooth() )
4535       {
4536         // smooth disabled by the user; check validy only
4537         if ( !isFace ) continue;
4538         badEdges.clear();
4539         for ( size_t i = 0; i < eos._edges.size(); ++i )
4540         {
4541           _LayerEdge* edge = eos._edges[i];
4542           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4543             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4544             {
4545               // debugMsg( "-- Stop inflation. Bad simplex ("
4546               //           << " "<< edge->_nodes[0]->GetID()
4547               //           << " "<< edge->_nodes.back()->GetID()
4548               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4549               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4550               // return false;
4551               badEdges.push_back( edge );
4552             }
4553         }
4554         if ( !badEdges.empty() )
4555         {
4556           eosC1.resize(1);
4557           eosC1[0] = &eos;
4558           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4559           if ( nbBad > 0 )
4560             return false;
4561         }
4562         continue; // goto the next EDGE or FACE
4563       }
4564
4565       // prepare data
4566       if ( eos.SWOLType() == TopAbs_FACE )
4567       {
4568         if ( !F.IsSame( eos._sWOL )) {
4569           F = TopoDS::Face( eos._sWOL );
4570           helper.SetSubShape( F );
4571           surface = helper.GetSurface( F );
4572         }
4573       }
4574       else
4575       {
4576         F.Nullify(); surface.Nullify();
4577       }
4578       const TGeomID sInd = eos._shapeID;
4579
4580       // perform smoothing
4581
4582       if ( eos.ShapeType() == TopAbs_EDGE )
4583       {
4584         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4585
4586         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4587         {
4588           // smooth on EDGE's (normally we should not get here)
4589           int step = 0;
4590           do {
4591             moved = false;
4592             for ( size_t i = 0; i < eos._edges.size(); ++i )
4593             {
4594               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4595             }
4596             dumpCmd( SMESH_Comment("# end step ")<<step);
4597           }
4598           while ( moved && step++ < 5 );
4599         }
4600         dumpFunctionEnd();
4601       }
4602
4603       else // smooth on FACE
4604       {
4605         eosC1.clear();
4606         eosC1.push_back( & eos );
4607         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4608
4609         movedEdges.clear();
4610         isConcaveFace.resize( eosC1.size() );
4611         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4612         {
4613           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4614           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4615           for ( size_t i = 0; i < edges.size(); ++i )
4616             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4617                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4618               movedEdges.push_back( edges[i] );
4619
4620           makeOffsetSurface( *eosC1[ iEOS ], helper );
4621         }
4622
4623         int step = 0, stepLimit = 5, nbBad = 0;
4624         while (( ++step <= stepLimit ) || improved )
4625         {
4626           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4627                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4628           int oldBadNb = nbBad;
4629           badEdges.clear();
4630
4631 #ifdef INCREMENTAL_SMOOTH
4632           bool findBest = false; // ( step == stepLimit );
4633           for ( size_t i = 0; i < movedEdges.size(); ++i )
4634           {
4635             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4636             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4637               badEdges.push_back( movedEdges[i] );
4638           }
4639 #else
4640           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4641           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4642           {
4643             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4644             for ( size_t i = 0; i < edges.size(); ++i )
4645             {
4646               edges[i]->Unset( _LayerEdge::SMOOTHED );
4647               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4648                 badEdges.push_back( eos._edges[i] );
4649             }
4650           }
4651 #endif
4652           nbBad = badEdges.size();
4653
4654           if ( nbBad > 0 )
4655             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4656
4657           if ( !badEdges.empty() && step >= stepLimit / 2 )
4658           {
4659             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4660               stepLimit = 9;
4661
4662             // resolve hard smoothing situation around concave VERTEXes
4663             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4664             {
4665               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4666               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4667                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4668                                                          step, badEdges );
4669             }
4670             // look for the best smooth of _LayerEdge's neighboring badEdges
4671             nbBad = 0;
4672             for ( size_t i = 0; i < badEdges.size(); ++i )
4673             {
4674               _LayerEdge* ledge = badEdges[i];
4675               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4676               {
4677                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4678                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4679               }
4680               ledge->Unset( _LayerEdge::SMOOTHED );
4681               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4682             }
4683             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4684           }
4685
4686           if ( nbBad == oldBadNb  &&
4687                nbBad > 0 &&
4688                step < stepLimit ) // smooth w/o chech of validity
4689           {
4690             dumpFunctionEnd();
4691             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4692                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4693             for ( size_t i = 0; i < movedEdges.size(); ++i )
4694             {
4695               movedEdges[i]->SmoothWoCheck();
4696             }
4697             if ( stepLimit < 9 )
4698               stepLimit++;
4699           }
4700
4701           improved = ( nbBad < oldBadNb );
4702
4703           dumpFunctionEnd();
4704
4705           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4706             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4707             {
4708               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4709             }
4710
4711         } // smoothing steps
4712
4713         // project -- to prevent intersections or fix bad simplices
4714         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4715         {
4716           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4717             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4718         }
4719
4720         //if ( !badEdges.empty() )
4721         {
4722           badEdges.clear();
4723           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4724           {
4725             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4726             {
4727               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4728
4729               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4730               edge->CheckNeiborsOnBoundary( & badEdges );
4731               if (( nbBad > 0 ) ||
4732                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4733               {
4734                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4735                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4736                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4737                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4738                   {
4739                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4740                              << " "<< tgtXYZ._node->GetID()
4741                              << " "<< edge->_simplices[j]._nPrev->GetID()
4742                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4743                     badEdges.push_back( edge );
4744                     break;
4745                   }
4746               }
4747             }
4748           }
4749
4750           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4751           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4752
4753           if ( nbBad > 0 )
4754             return false;
4755         }
4756
4757       } // // smooth on FACE's
4758     } // loop on shapes
4759   } // smooth on [ EDGEs, FACEs ]
4760
4761   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4762   eosC1.resize(1);
4763   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4764   {
4765     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4766     if ( eos.ShapeType() == TopAbs_FACE ||
4767          eos._edges.empty() ||
4768          !eos._sWOL.IsNull() )
4769       continue;
4770
4771     badEdges.clear();
4772     for ( size_t i = 0; i < eos._edges.size(); ++i )
4773     {
4774       _LayerEdge*      edge = eos._edges[i];
4775       if ( edge->_nodes.size() < 2 ) continue;
4776       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4777       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4778       //const gp_XYZ& prevXYZ = edge->PrevPos();
4779       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4780         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4781         {
4782           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4783                    << " "<< tgtXYZ._node->GetID()
4784                    << " "<< edge->_simplices[j]._nPrev->GetID()
4785                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4786           badEdges.push_back( edge );
4787           break;
4788         }
4789     }
4790
4791     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4792     eosC1[0] = &eos;
4793     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4794     if ( nbBad > 0 )
4795       return false;
4796   }
4797
4798
4799   // Check if the last segments of _LayerEdge intersects 2D elements;
4800   // checked elements are either temporary faces or faces on surfaces w/o the layers
4801
4802   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4803     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4804                                            data._proxyMesh->GetFaces( data._solid )) );
4805
4806 #ifdef BLOCK_INFLATION
4807   const bool toBlockInfaltion = true;
4808 #else
4809   const bool toBlockInfaltion = false;
4810 #endif
4811   distToIntersection = Precision::Infinite();
4812   double dist;
4813   const SMDS_MeshElement* intFace = 0;
4814   const SMDS_MeshElement* closestFace = 0;
4815   _LayerEdge* le = 0;
4816   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4817   {
4818     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4819     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4820       continue;
4821     for ( size_t i = 0; i < eos._edges.size(); ++i )
4822     {
4823       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4824            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4825         continue;
4826       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4827       {
4828         return false;
4829         // commented due to "Illegal hash-positionPosition" error in NETGEN
4830         // on Debian60 on viscous_layers_01/B2 case
4831         // Collision; try to deflate _LayerEdge's causing it
4832         // badEdges.clear();
4833         // badEdges.push_back( eos._edges[i] );
4834         // eosC1[0] = & eos;
4835         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4836         // if ( nbBad > 0 )
4837         //   return false;
4838
4839         // badEdges.clear();
4840         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4841         // {
4842         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4843         //   {
4844         //     const SMDS_MeshElement* srcFace =
4845         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4846         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4847         //     while ( nIt->more() )
4848         //     {
4849         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4850         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4851         //       if ( n2e != data._n2eMap.end() )
4852         //         badEdges.push_back( n2e->second );
4853         //     }
4854         //     eosC1[0] = eof;
4855         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4856         //     if ( nbBad > 0 )
4857         //       return false;
4858         //   }
4859         // }
4860         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4861         //   return false;
4862         // else
4863         //   continue;
4864       }
4865       if ( !intFace )
4866       {
4867         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4868         debugMsg( msg );
4869         continue;
4870       }
4871
4872       const bool isShorterDist = ( distToIntersection > dist );
4873       if ( toBlockInfaltion || isShorterDist )
4874       {
4875         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4876         // lying on this _ConvexFace
4877         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4878           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4879             continue;
4880
4881         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4882         // ( avoid limiting the thickness on the case of issue 22576)
4883         if ( intFace->getshapeId() == eos._shapeID  )
4884           continue;
4885
4886         // ignore intersection with intFace of an adjacent FACE
4887         if ( dist > 0 )
4888         {
4889           bool toIgnore = false;
4890           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4891           {
4892             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4893             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4894             {
4895               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4896               for ( ; !toIgnore && edge.More(); edge.Next() )
4897                 // is adjacent - has a common EDGE
4898                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4899
4900               if ( toIgnore ) // check angle between normals
4901               {
4902                 gp_XYZ normal;
4903                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4904                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4905               }
4906             }
4907           }
4908           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4909           {
4910             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4911             {
4912               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4913               toIgnore = ( nInd >= 0 );
4914             }
4915           }
4916           if ( toIgnore )
4917             continue;
4918         }
4919
4920         // intersection not ignored
4921
4922         if ( toBlockInfaltion &&
4923              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4924         {
4925           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4926           eos._edges[i]->Block( data );                  // not to inflate
4927
4928           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4929           {
4930             // block _LayerEdge's, on top of which intFace is
4931             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4932             {
4933               const SMDS_MeshElement* srcFace =
4934                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4935               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4936               while ( nIt->more() )
4937               {
4938                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4939                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4940                 if ( n2e != data._n2eMap.end() )
4941                   n2e->second->Block( data );
4942               }
4943             }
4944           }
4945         }
4946
4947         if ( isShorterDist )
4948         {
4949           distToIntersection = dist;
4950           le = eos._edges[i];
4951           closestFace = intFace;
4952         }
4953
4954       } // if ( toBlockInfaltion || isShorterDist )
4955     } // loop on eos._edges
4956   } // loop on data._edgesOnShape
4957
4958   if ( closestFace && le )
4959   {
4960 #ifdef __myDEBUG
4961     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4962     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4963          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4964          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4965          << ") distance = " << distToIntersection<< endl;
4966 #endif
4967   }
4968
4969   return true;
4970 }
4971
4972 //================================================================================
4973 /*!
4974  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4975  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
4976  *  \return int - resulting nb of bad _LayerEdge's
4977  */
4978 //================================================================================
4979
4980 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
4981                                           SMESH_MesherHelper&       helper,
4982                                           vector< _LayerEdge* >&    badSmooEdges,
4983                                           vector< _EdgesOnShape* >& eosC1,
4984                                           const int                 infStep )
4985 {
4986   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4987
4988   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4989
4990   enum {
4991     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
4992     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
4993     ADDED         = _LayerEdge::UNUSED_FLAG * 4
4994   };
4995   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
4996
4997   double vol;
4998   bool haveInvalidated = true;
4999   while ( haveInvalidated )
5000   {
5001     haveInvalidated = false;
5002     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5003     {
5004       _LayerEdge*   edge = badSmooEdges[i];
5005       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5006       edge->Set( ADDED );
5007       bool invalidated = false;
5008       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5009       {
5010         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5011         edge->Block( data );
5012         edge->Set( INVALIDATED );
5013         edge->Unset( TO_INVALIDATE );
5014         invalidated = true;
5015         haveInvalidated = true;
5016       }
5017
5018       // look for _LayerEdge's of bad _simplices
5019       int nbBad = 0;
5020       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5021       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5022       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5023       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5024       {
5025         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5026             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5027           continue;
5028
5029         bool isBad = true;
5030         _LayerEdge* ee[2] = { 0,0 };
5031         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5032           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5033             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5034
5035         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5036         while ( maxNbSteps > edge->NbSteps() && isBad )
5037         {
5038           --maxNbSteps;
5039           for ( int iE = 0; iE < 2; ++iE )
5040           {
5041             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5042                  ee[ iE ]->NbSteps() > 1 )
5043             {
5044               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5045               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5046               ee[ iE ]->Block( data );
5047               ee[ iE ]->Set( INVALIDATED );
5048               haveInvalidated = true;
5049             }
5050           }
5051           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5052               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5053             isBad = false;
5054         }
5055         nbBad += isBad;
5056         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5057         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5058         ee[0]->Set( ADDED );
5059         ee[1]->Set( ADDED );
5060         if ( isBad )
5061         {
5062           ee[0]->Set( TO_INVALIDATE );
5063           ee[1]->Set( TO_INVALIDATE );
5064         }
5065       }
5066
5067       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5068       {
5069         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5070         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5071         edge->Block( data );
5072         edge->Set( INVALIDATED );
5073         edge->Unset( TO_INVALIDATE );
5074         haveInvalidated = true;
5075       }
5076     } // loop on badSmooEdges
5077   } // while ( haveInvalidated )
5078
5079   // re-smooth on analytical EDGEs
5080   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5081   {
5082     _LayerEdge* edge = badSmooEdges[i];
5083     if ( !edge->Is( INVALIDATED )) continue;
5084
5085     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5086     if ( eos->ShapeType() == TopAbs_VERTEX )
5087     {
5088       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5089       while ( const TopoDS_Shape* e = eIt->next() )
5090         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5091           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5092           {
5093             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5094             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5095             //   F       = TopoDS::Face( eoe->_sWOL );
5096             //   surface = helper.GetSurface( F );
5097             // }
5098             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5099             eoe->_edgeSmoother->_anaCurve.Nullify();
5100           }
5101     }
5102   }
5103
5104
5105   // check result of invalidation
5106
5107   int nbBad = 0;
5108   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5109   {
5110     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5111     {
5112       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5113       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5114       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5115       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5116       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5117         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5118         {
5119           ++nbBad;
5120           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5121                    << " "<< tgtXYZ._node->GetID()
5122                    << " "<< edge->_simplices[j]._nPrev->GetID()
5123                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5124         }
5125     }
5126   }
5127   dumpFunctionEnd();
5128
5129   return nbBad;
5130 }
5131
5132 //================================================================================
5133 /*!
5134  * \brief Create an offset surface
5135  */
5136 //================================================================================
5137
5138 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5139 {
5140   if ( eos._offsetSurf.IsNull() ||
5141        eos._edgeForOffset == 0 ||
5142        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5143     return;
5144
5145   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5146
5147   // find offset
5148   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5149   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5150   double offset = baseSurface->Gap();
5151
5152   eos._offsetSurf.Nullify();
5153
5154   try
5155   {
5156     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5157     if ( !offsetMaker.IsDone() ) return;
5158
5159     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5160     if ( !fExp.More() ) return;
5161
5162     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5163     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5164     if ( surf.IsNull() ) return;
5165
5166     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5167   }
5168   catch ( Standard_Failure )
5169   {
5170   }
5171 }
5172
5173 //================================================================================
5174 /*!
5175  * \brief Put nodes of a curved FACE to its offset surface
5176  */
5177 //================================================================================
5178
5179 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5180                                           int                       infStep,
5181                                           vector< _EdgesOnShape* >& eosC1,
5182                                           int                       smooStep,
5183                                           bool                      moveAll )
5184 {
5185   _EdgesOnShape * eof = & eos;
5186   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5187   {
5188     eof = 0;
5189     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5190     {
5191       if ( eosC1[i]->_offsetSurf.IsNull() ||
5192            eosC1[i]->ShapeType() != TopAbs_FACE ||
5193            eosC1[i]->_edgeForOffset == 0 ||
5194            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5195         continue;
5196       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5197         eof = eosC1[i];
5198     }
5199   }
5200   if ( !eof ||
5201        eof->_offsetSurf.IsNull() ||
5202        eof->ShapeType() != TopAbs_FACE ||
5203        eof->_edgeForOffset == 0 ||
5204        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5205     return;
5206
5207   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5208   for ( size_t i = 0; i < eos._edges.size(); ++i )
5209   {
5210     _LayerEdge* edge = eos._edges[i];
5211     edge->Unset( _LayerEdge::MARKED );
5212     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5213       continue;
5214     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5215         continue;
5216
5217     int nbBlockedAround = 0;
5218     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5219       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5220     if ( nbBlockedAround > 1 )
5221       continue;
5222
5223     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5224     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5225     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5226     edge->_curvature->_uv = uv;
5227     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5228
5229     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5230     gp_XYZ prevP = edge->PrevCheckPos();
5231     bool      ok = true;
5232     if ( !moveAll )
5233       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5234       {
5235         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5236       }
5237     if ( ok )
5238     {
5239       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5240       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5241       edge->_pos.back() = newP;
5242
5243       edge->Set( _LayerEdge::MARKED );
5244     }
5245   }
5246
5247 #ifdef _DEBUG_
5248   // dumpMove() for debug
5249   size_t i = 0;
5250   for ( ; i < eos._edges.size(); ++i )
5251     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5252       break;
5253   if ( i < eos._edges.size() )
5254   {
5255     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5256                  << "_InfStep" << infStep << "_" << smooStep );
5257     for ( ; i < eos._edges.size(); ++i )
5258     {
5259       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5260         dumpMove( eos._edges[i]->_nodes.back() );
5261     }
5262     dumpFunctionEnd();
5263   }
5264 #endif
5265 }
5266
5267 //================================================================================
5268 /*!
5269  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5270  *        _LayerEdge's to be in a consequent order
5271  */
5272 //================================================================================
5273
5274 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5275                                                 _EdgesOnShape&      eos,
5276                                                 SMESH_MesherHelper& helper)
5277 {
5278   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5279
5280   TopLoc_Location loc; double f,l;
5281
5282   Handle(Geom_Line)   line;
5283   Handle(Geom_Circle) circle;
5284   bool isLine, isCirc;
5285   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5286   {
5287     // check if the EDGE is a line
5288     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5289     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5290       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5291
5292     line   = Handle(Geom_Line)::DownCast( curve );
5293     circle = Handle(Geom_Circle)::DownCast( curve );
5294     isLine = (!line.IsNull());
5295     isCirc = (!circle.IsNull());
5296
5297     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5298     {
5299       isLine = SMESH_Algo::IsStraight( E );
5300
5301       if ( isLine )
5302         line = new Geom_Line( gp::OX() ); // only type does matter
5303     }
5304     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5305     {
5306       // TODO
5307     }
5308   }
5309   else //////////////////////////////////////////////////////////////////////// 2D case
5310   {
5311     if ( !eos._isRegularSWOL ) // 23190
5312       return NULL;
5313
5314     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5315
5316     // check if the EDGE is a line
5317     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5318     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5319       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5320
5321     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5322     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5323     isLine = (!line2d.IsNull());
5324     isCirc = (!circle2d.IsNull());
5325
5326     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5327     {
5328       Bnd_B2d bndBox;
5329       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5330       while ( nIt->more() )
5331         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5332       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5333
5334       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5335       for ( int i = 0; i < 2 && !isLine; ++i )
5336         isLine = ( size.Coord( i+1 ) <= lineTol );
5337     }
5338     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5339     {
5340       // TODO
5341     }
5342     if ( isLine )
5343     {
5344       line = new Geom_Line( gp::OX() ); // only type does matter
5345     }
5346     else if ( isCirc )
5347     {
5348       gp_Pnt2d p = circle2d->Location();
5349       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5350       circle = new Geom_Circle( ax, 1.); // only center position does matter
5351     }
5352   }
5353
5354   if ( isLine )
5355     return line;
5356   if ( isCirc )
5357     return circle;
5358
5359   return Handle(Geom_Curve)();
5360 }
5361
5362 //================================================================================
5363 /*!
5364  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5365  */
5366 //================================================================================
5367
5368 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5369                                       Handle(ShapeAnalysis_Surface)& surface,
5370                                       const TopoDS_Face&             F,
5371                                       SMESH_MesherHelper&            helper)
5372 {
5373   if ( !isAnalytic() ) return false;
5374
5375   const size_t iFrom = 0, iTo = _eos._edges.size();
5376
5377   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5378   {
5379     if ( F.IsNull() ) // 3D
5380     {
5381       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5382       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5383       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5384       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5385       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5386       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5387       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5388       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5389                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5390                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5391                          vLE1->Is( _LayerEdge::BLOCKED ));
5392       for ( size_t i = iFrom; i < iTo; ++i )
5393       {
5394         _LayerEdge*       edge = _eos._edges[i];
5395         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5396         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5397
5398         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5399         {
5400           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5401           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5402                             lineDir * ( curPos - pSrc0 ));
5403           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5404         }
5405         if ( edge->Is( _LayerEdge::BLOCKED ))
5406         {
5407           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5408           double curThick = pSrc.SquareDistance( tgtNode );
5409           double newThink = ( pSrc - newPos ).SquareModulus();
5410           if ( newThink > curThick )
5411             continue;
5412         }
5413         edge->_pos.back() = newPos;
5414         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5415         dumpMove( tgtNode );
5416       }
5417     }
5418     else // 2D
5419     {
5420       _LayerEdge* e0 = getLEdgeOnV( 0 );
5421       _LayerEdge* e1 = getLEdgeOnV( 1 );
5422       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5423       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5424       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5425       {
5426         int iPeriodic = helper.GetPeriodicIndex();
5427         if ( iPeriodic == 1 || iPeriodic == 2 )
5428         {
5429           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5430           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5431             std::swap( uv0, uv1 );
5432         }
5433       }
5434       const gp_XY rangeUV = uv1 - uv0;
5435       for ( size_t i = iFrom; i < iTo; ++i )
5436       {
5437         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5438         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5439         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5440
5441         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5442         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5443         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5444         dumpMove( tgtNode );
5445
5446         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5447         pos->SetUParameter( newUV.X() );
5448         pos->SetVParameter( newUV.Y() );
5449       }
5450     }
5451     return true;
5452   }
5453
5454   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5455   {
5456     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5457     gp_Pnt center3D = circle->Location();
5458
5459     if ( F.IsNull() ) // 3D
5460     {
5461       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5462         return true; // closed EDGE - nothing to do
5463
5464       // circle is a real curve of EDGE
5465       gp_Circ circ = circle->Circ();
5466
5467       // new center is shifted along its axis
5468       const gp_Dir& axis = circ.Axis().Direction();
5469       _LayerEdge*     e0 = getLEdgeOnV(0);
5470       _LayerEdge*     e1 = getLEdgeOnV(1);
5471       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5472       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5473       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5474       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5475       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5476
5477       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5478
5479       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5480       gp_Circ newCirc( newAxis, newRadius );
5481       gp_Vec  vecC1  ( newCenter, p1 );
5482
5483       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5484       if ( uLast < 0 )
5485         uLast += 2 * M_PI;
5486       
5487       for ( size_t i = iFrom; i < iTo; ++i )
5488       {
5489         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5490         double u = uLast * _leParams[i];
5491         gp_Pnt p = ElCLib::Value( u, newCirc );
5492         _eos._edges[i]->_pos.back() = p.XYZ();
5493
5494         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5495         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5496         dumpMove( tgtNode );
5497       }
5498       return true;
5499     }
5500     else // 2D
5501     {
5502       const gp_XY center( center3D.X(), center3D.Y() );
5503
5504       _LayerEdge* e0 = getLEdgeOnV(0);
5505       _LayerEdge* eM = _eos._edges[ 0 ];
5506       _LayerEdge* e1 = getLEdgeOnV(1);
5507       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5508       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5509       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5510       gp_Vec2d vec0( center, uv0 );
5511       gp_Vec2d vecM( center, uvM );
5512       gp_Vec2d vec1( center, uv1 );
5513       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5514       double uMidl = vec0.Angle( vecM );
5515       if ( uLast * uMidl <= 0. )
5516         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5517       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5518
5519       gp_Ax2d   axis( center, vec0 );
5520       gp_Circ2d circ( axis, radius );
5521       for ( size_t i = iFrom; i < iTo; ++i )
5522       {
5523         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5524         double    newU = uLast * _leParams[i];
5525         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5526         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5527
5528         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5529         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5530         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5531         dumpMove( tgtNode );
5532
5533         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5534         pos->SetUParameter( newUV.X() );
5535         pos->SetVParameter( newUV.Y() );
5536       }
5537     }
5538     return true;
5539   }
5540
5541   return false;
5542 }
5543
5544 //================================================================================
5545 /*!
5546  * \brief smooth _LayerEdge's on a an EDGE
5547  */
5548 //================================================================================
5549
5550 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5551                                      Handle(ShapeAnalysis_Surface)& surface,
5552                                      const TopoDS_Face&             F,
5553                                      SMESH_MesherHelper&            helper)
5554 {
5555   if ( _offPoints.empty() )
5556     return false;
5557
5558   // move _offPoints along normals of _LayerEdge's
5559
5560   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5561   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5562     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5563   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5564     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5565   _leOnV[0]._len = e[0]->_len;
5566   _leOnV[1]._len = e[1]->_len;
5567   for ( size_t i = 0; i < _offPoints.size(); i++ )
5568   {
5569     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5570     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5571     const double w0 = _offPoints[i]._2edges._wgt[0];
5572     const double w1 = _offPoints[i]._2edges._wgt[1];
5573     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5574     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5575     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5576     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5577          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5578       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5579
5580     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5581     _offPoints[i]._len  = avgLen;
5582   }
5583
5584   double fTol = 0;
5585   if ( !surface.IsNull() ) // project _offPoints to the FACE
5586   {
5587     fTol = 100 * BRep_Tool::Tolerance( F );
5588     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5589
5590     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5591     //if ( surface->Gap() < 0.5 * segLen )
5592       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5593
5594     for ( size_t i = 1; i < _offPoints.size(); ++i )
5595     {
5596       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5597       //if ( surface->Gap() < 0.5 * segLen )
5598         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5599     }
5600   }
5601
5602   // project tgt nodes of extreme _LayerEdge's to the offset segments
5603
5604   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5605   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5606
5607   gp_Pnt pExtreme[2], pProj[2];
5608   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5609   {
5610     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5611     int  i = _iSeg[ is2nd ];
5612     int di = is2nd ? -1 : +1;
5613     bool projected = false;
5614     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5615     int nbWorse = 0;
5616     do {
5617       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5618       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5619       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5620       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5621       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5622       if ( dist < distMin || projected )
5623       {
5624         _iSeg[ is2nd ] = i;
5625         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5626         distMin = dist;
5627       }
5628       else if ( dist > distPrev )
5629       {
5630         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5631           break;
5632       }
5633       distPrev = dist;
5634       i += di;
5635     }
5636     while ( !projected &&
5637             i >= 0 && i+1 < (int)_offPoints.size() );
5638
5639     if ( !projected )
5640     {
5641       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5642       {
5643         _iSeg[0] = 0;
5644         _iSeg[1] = _offPoints.size()-2;
5645         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5646         return false;
5647       }
5648     }
5649   }
5650   if ( _iSeg[0] > _iSeg[1] )
5651   {
5652     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5653     return false;
5654   }
5655
5656   // compute normalized length of the offset segments located between the projections
5657
5658   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5659   vector< double > len( nbSeg + 1 );
5660   len[ iSeg++ ] = 0;
5661   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
5662   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5663   {
5664     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5665   }
5666   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
5667
5668   double d0 = pProj[0].Distance( pExtreme[0]);
5669   double d1 = pProj[1].Distance( pExtreme[1]);
5670   double fullLen = len.back() - d0 - d1;
5671   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5672     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5673
5674   // temporary replace extreme _offPoints by pExtreme
5675   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5676                    _offPoints[ _iSeg[1]+1 ]._xyz };
5677   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5678   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5679
5680   // distribute tgt nodes of _LayerEdge's between the projections
5681
5682   iSeg = 0;
5683   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5684   {
5685     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5686     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5687       iSeg++;
5688     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5689     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5690                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5691
5692     if ( surface.IsNull() )
5693     {
5694       _eos._edges[i]->_pos.back() = p;
5695     }
5696     else // project a new node position to a FACE
5697     {
5698       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5699       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5700
5701       p = surface->Value( uv2 ).XYZ();
5702       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5703     }
5704     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5705     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5706     dumpMove( tgtNode );
5707   }
5708
5709   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5710   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5711
5712   return true;
5713 }
5714
5715 //================================================================================
5716 /*!
5717  * \brief Prepare for smoothing
5718  */
5719 //================================================================================
5720
5721 void _Smoother1D::prepare(_SolidData& data)
5722 {
5723   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5724   _curveLen = SMESH_Algo::EdgeLength( E );
5725
5726   // sort _LayerEdge's by position on the EDGE
5727   data.SortOnEdge( E, _eos._edges );
5728
5729   // compute normalized param of _eos._edges on EDGE
5730   _leParams.resize( _eos._edges.size() + 1 );
5731   {
5732     double curLen;
5733     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5734     _leParams[0] = 0;
5735     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5736     {
5737       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5738       curLen         = p.Distance( pPrev );
5739       _leParams[i+1] = _leParams[i] + curLen;
5740       pPrev          = p;
5741     }
5742     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5743     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5744       _leParams[i] = _leParams[i+1] / fullLen;
5745   }
5746
5747   if ( isAnalytic() )
5748     return;
5749
5750   // divide E to have offset segments with low deflection
5751   BRepAdaptor_Curve c3dAdaptor( E );
5752   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5753   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5754   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5755   if ( discret.NbPoints() <= 2 )
5756   {
5757     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5758     return;
5759   }
5760
5761   const double u0 = c3dAdaptor.FirstParameter();
5762   gp_Pnt p; gp_Vec tangent;
5763   _offPoints.resize( discret.NbPoints() );
5764   for ( size_t i = 0; i < _offPoints.size(); i++ )
5765   {
5766     double u = discret.Parameter( i+1 );
5767     c3dAdaptor.D1( u, p, tangent );
5768     _offPoints[i]._xyz     = p.XYZ();
5769     _offPoints[i]._edgeDir = tangent.XYZ();
5770     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5771   }
5772
5773   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5774
5775   // set _2edges
5776   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5777   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5778   _2NearEdges tmp2edges;
5779   tmp2edges._edges[1] = _eos._edges[0];
5780   _leOnV[0]._2neibors = & tmp2edges;
5781   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5782   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5783   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5784   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5785   {
5786     // find _LayerEdge's located before and after an offset point
5787     // (_eos._edges[ iLE ] is next after ePrev)
5788     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5789       ePrev = _eos._edges[ iLE++ ];
5790     eNext = ePrev->_2neibors->_edges[1];
5791
5792     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5793     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5794     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5795     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5796   }
5797
5798   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5799   for ( size_t i = 0; i < _offPoints.size(); i++ )
5800     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5801       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5802     else break;
5803   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5804     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5805       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5806     else break;
5807
5808   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5809
5810   int iLBO = _offPoints.size() - 2; // last but one
5811
5812   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5813   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5814
5815   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5816   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5817   _leOnV[ 0 ]._len = 0;
5818   _leOnV[ 1 ]._len = 0;
5819   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5820   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5821
5822   _iSeg[0] = 0;
5823   _iSeg[1] = _offPoints.size()-2;
5824
5825   // initialize OffPnt::_len
5826   for ( size_t i = 0; i < _offPoints.size(); ++i )
5827     _offPoints[i]._len = 0;
5828
5829   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5830   {
5831     _leOnV[0]._len = leOnV[0]->_len;
5832     _leOnV[1]._len = leOnV[1]->_len;
5833     for ( size_t i = 0; i < _offPoints.size(); i++ )
5834     {
5835       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5836       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5837       const double w0 = _offPoints[i]._2edges._wgt[0];
5838       const double w1 = _offPoints[i]._2edges._wgt[1];
5839       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5840       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5841                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5842       _offPoints[i]._xyz = avgXYZ;
5843       _offPoints[i]._len = avgLen;
5844     }
5845   }
5846 }
5847
5848 //================================================================================
5849 /*!
5850  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5851  */
5852 //================================================================================
5853
5854 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5855                                      const gp_XYZ&  edgeDir)
5856 {
5857   gp_XYZ cross = normal ^ edgeDir;
5858   gp_XYZ  norm = edgeDir ^ cross;
5859   double  size = norm.Modulus();
5860
5861   return norm / size;
5862 }
5863
5864 //================================================================================
5865 /*!
5866  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5867  */
5868 //================================================================================
5869
5870 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5871                              vector< _LayerEdge* >& edges)
5872 {
5873   map< double, _LayerEdge* > u2edge;
5874   for ( size_t i = 0; i < edges.size(); ++i )
5875     u2edge.insert( u2edge.end(),
5876                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5877
5878   ASSERT( u2edge.size() == edges.size() );
5879   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5880   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5881     edges[i] = u2e->second;
5882
5883   Sort2NeiborsOnEdge( edges );
5884 }
5885
5886 //================================================================================
5887 /*!
5888  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5889  */
5890 //================================================================================
5891
5892 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5893 {
5894   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5895
5896   for ( size_t i = 0; i < edges.size()-1; ++i )
5897     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5898       edges[i]->_2neibors->reverse();
5899
5900   const size_t iLast = edges.size() - 1;
5901   if ( edges.size() > 1 &&
5902        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5903     edges[iLast]->_2neibors->reverse();
5904 }
5905
5906 //================================================================================
5907 /*!
5908  * \brief Return _EdgesOnShape* corresponding to the shape
5909  */
5910 //================================================================================
5911
5912 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5913 {
5914   if ( shapeID < (int)_edgesOnShape.size() &&
5915        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5916     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5917
5918   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5919     if ( _edgesOnShape[i]._shapeID == shapeID )
5920       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5921
5922   return 0;
5923 }
5924
5925 //================================================================================
5926 /*!
5927  * \brief Return _EdgesOnShape* corresponding to the shape
5928  */
5929 //================================================================================
5930
5931 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5932 {
5933   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5934   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5935 }
5936
5937 //================================================================================
5938 /*!
5939  * \brief Prepare data of the _LayerEdge for smoothing on FACE
5940  */
5941 //================================================================================
5942
5943 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5944 {
5945   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5946
5947   set< TGeomID > vertices;
5948   TopoDS_Face F;
5949   if ( eos->ShapeType() == TopAbs_FACE )
5950   {
5951     // check FACE concavity and get concave VERTEXes
5952     F = TopoDS::Face( eos->_shape );
5953     if ( isConcave( F, helper, &vertices ))
5954       _concaveFaces.insert( eos->_shapeID );
5955
5956     // set eos._eosConcaVer
5957     eos->_eosConcaVer.clear();
5958     eos->_eosConcaVer.reserve( vertices.size() );
5959     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5960     {
5961       _EdgesOnShape* eov = GetShapeEdges( *v );
5962       if ( eov && eov->_edges.size() == 1 )
5963       {
5964         eos->_eosConcaVer.push_back( eov );
5965         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5966           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5967       }
5968     }
5969
5970     // SetSmooLen() to _LayerEdge's on FACE
5971     for ( size_t i = 0; i < eos->_edges.size(); ++i )
5972     {
5973       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5974     }
5975     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5976     while ( smIt->more() ) // loop on sub-shapes of the FACE
5977     {
5978       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5979       if ( !eoe ) continue;
5980
5981       vector<_LayerEdge*>& eE = eoe->_edges;
5982       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5983       {
5984         if ( eE[iE]->_cosin <= theMinSmoothCosin )
5985           continue;
5986
5987         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5988         while ( segIt->more() )
5989         {
5990           const SMDS_MeshElement* seg = segIt->next();
5991           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
5992             continue;
5993           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
5994             continue; // not to check a seg twice
5995           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
5996           {
5997             _LayerEdge* eN = eE[iE]->_neibors[iN];
5998             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
5999               continue;
6000             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6001             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6002             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6003             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6004           }
6005         }
6006       }
6007     }
6008   } // if ( eos->ShapeType() == TopAbs_FACE )
6009
6010   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6011   {
6012     eos->_edges[i]->_smooFunction = 0;
6013     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6014   }
6015   bool isCurved = false;
6016   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6017   {
6018     _LayerEdge* edge = eos->_edges[i];
6019
6020     // get simplices sorted
6021     _Simplex::SortSimplices( edge->_simplices );
6022
6023     // smoothing function
6024     edge->ChooseSmooFunction( vertices, _n2eMap );
6025
6026     // set _curvature
6027     double avgNormProj = 0, avgLen = 0;
6028     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6029     {
6030       _Simplex& s = edge->_simplices[iS];
6031
6032       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6033       avgNormProj += edge->_normal * vec;
6034       avgLen      += vec.Modulus();
6035       if ( substituteSrcNodes )
6036       {
6037         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6038         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6039       }
6040     }
6041     avgNormProj /= edge->_simplices.size();
6042     avgLen      /= edge->_simplices.size();
6043     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6044     {
6045       isCurved = true;
6046       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6047       if ( !fPos )
6048         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6049           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6050       if ( fPos )
6051         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6052     }
6053   }
6054
6055   // prepare for putOnOffsetSurface()
6056   if (( eos->ShapeType() == TopAbs_FACE ) &&
6057       ( isCurved || !eos->_eosConcaVer.empty() ))
6058   {
6059     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6060     eos->_edgeForOffset = 0;
6061
6062     double maxCosin = -1;
6063     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6064     {
6065       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6066       if ( !eoe || eoe->_edges.empty() ) continue;
6067
6068       vector<_LayerEdge*>& eE = eoe->_edges;
6069       _LayerEdge* e = eE[ eE.size() / 2 ];
6070       if ( e->_cosin > maxCosin )
6071       {
6072         eos->_edgeForOffset = e;
6073         maxCosin = e->_cosin;
6074       }
6075     }
6076   }
6077 }
6078
6079 //================================================================================
6080 /*!
6081  * \brief Add faces for smoothing
6082  */
6083 //================================================================================
6084
6085 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6086                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6087 {
6088   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6089   for ( ; eos != eosToSmooth.end(); ++eos )
6090   {
6091     if ( !*eos || (*eos)->_toSmooth ) continue;
6092
6093     (*eos)->_toSmooth = true;
6094
6095     if ( (*eos)->ShapeType() == TopAbs_FACE )
6096     {
6097       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6098       (*eos)->_toSmooth = true;
6099     }
6100   }
6101
6102   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6103   if ( edgesNoAnaSmooth )
6104     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6105     {
6106       if ( (*eos)->_edgeSmoother )
6107         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6108     }
6109 }
6110
6111 //================================================================================
6112 /*!
6113  * \brief Limit _LayerEdge::_maxLen according to local curvature
6114  */
6115 //================================================================================
6116
6117 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6118 {
6119   // find intersection of neighbor _LayerEdge's to limit _maxLen
6120   // according to local curvature (IPAL52648)
6121
6122   // This method must be called after findCollisionEdges() where _LayerEdge's
6123   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6124
6125   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6126   {
6127     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6128     if ( eosI._edges.empty() ) continue;
6129     if ( !eosI._hyp.ToSmooth() )
6130     {
6131       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6132       {
6133         _LayerEdge* eI = eosI._edges[i];
6134         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6135         {
6136           _LayerEdge* eN = eI->_neibors[iN];
6137           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6138           {
6139             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6140             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6141           }
6142         }
6143       }
6144     }
6145     else if ( eosI.ShapeType() == TopAbs_EDGE )
6146     {
6147       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6148       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6149
6150       _LayerEdge* e0 = eosI._edges[0];
6151       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6152       {
6153         _LayerEdge* eI = eosI._edges[i];
6154         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6155         e0 = eI;
6156       }
6157     }
6158   }
6159 }
6160
6161 //================================================================================
6162 /*!
6163  * \brief Limit _LayerEdge::_maxLen according to local curvature
6164  */
6165 //================================================================================
6166
6167 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6168                                               _LayerEdge*         e2,
6169                                               _EdgesOnShape&      eos1,
6170                                               _EdgesOnShape&      eos2,
6171                                               SMESH_MesherHelper& helper )
6172 {
6173   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6174   double norSize = plnNorm.SquareModulus();
6175   if ( norSize < std::numeric_limits<double>::min() )
6176     return; // parallel normals
6177
6178   // find closest points of skew _LayerEdge's
6179   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6180   gp_XYZ dir12 = src2 - src1;
6181   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6182   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6183   double  dot1 = perp2 * e1->_normal;
6184   double  dot2 = perp1 * e2->_normal;
6185   double    u1 =   ( perp2 * dir12 ) / dot1;
6186   double    u2 = - ( perp1 * dir12 ) / dot2;
6187   if ( u1 > 0 && u2 > 0 )
6188   {
6189     double ovl = ( u1 * e1->_normal * dir12 -
6190                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6191     if ( ovl > theSmoothThickToElemSizeRatio )
6192     {    
6193       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6194       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6195     }
6196   }
6197 }
6198
6199 //================================================================================
6200 /*!
6201  * \brief Fill data._collisionEdges
6202  */
6203 //================================================================================
6204
6205 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6206 {
6207   data._collisionEdges.clear();
6208
6209   // set the full thickness of the layers to LEs
6210   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6211   {
6212     _EdgesOnShape& eos = data._edgesOnShape[iS];
6213     if ( eos._edges.empty() ) continue;
6214     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6215
6216     for ( size_t i = 0; i < eos._edges.size(); ++i )
6217     {
6218       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6219       double maxLen = eos._edges[i]->_maxLen;
6220       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6221       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6222       eos._edges[i]->_maxLen = maxLen;
6223     }
6224   }
6225
6226   // make temporary quadrangles got by extrusion of
6227   // mesh edges along _LayerEdge._normal's
6228
6229   vector< const SMDS_MeshElement* > tmpFaces;
6230
6231   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6232   {
6233     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6234     if ( eos.ShapeType() != TopAbs_EDGE )
6235       continue;
6236     if ( eos._edges.empty() )
6237     {
6238       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6239       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6240       while ( smIt->more() )
6241         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6242           if ( eov->_edges.size() == 1 )
6243             edge[ bool( edge[0]) ] = eov->_edges[0];
6244
6245       if ( edge[1] )
6246       {
6247         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6248         tmpFaces.push_back( f );
6249       }
6250     }
6251     for ( size_t i = 0; i < eos._edges.size(); ++i )
6252     {
6253       _LayerEdge* edge = eos._edges[i];
6254       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6255       {
6256         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6257         if ( src2->GetPosition()->GetDim() > 0 &&
6258              src2->GetID() < edge->_nodes[0]->GetID() )
6259           continue; // avoid using same segment twice
6260
6261         // a _LayerEdge containg tgt2
6262         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6263
6264         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6265         tmpFaces.push_back( f );
6266       }
6267     }
6268   }
6269
6270   // Find _LayerEdge's intersecting tmpFaces.
6271
6272   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6273                                                             tmpFaces.end()));
6274   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6275     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6276
6277   double dist1, dist2, segLen, eps = 0.5;
6278   _CollisionEdges collEdges;
6279   vector< const SMDS_MeshElement* > suspectFaces;
6280   const double angle45 = Cos( 45. * M_PI / 180. );
6281
6282   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6283   {
6284     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6285     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6286       continue;
6287     // find sub-shapes whose VL can influence VL on eos
6288     set< TGeomID > neighborShapes;
6289     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6290     while ( const TopoDS_Shape* face = fIt->next() )
6291     {
6292       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6293       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6294       {
6295         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6296         while ( subIt->more() )
6297           neighborShapes.insert( subIt->next()->GetId() );
6298       }
6299     }
6300     if ( eos.ShapeType() == TopAbs_VERTEX )
6301     {
6302       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6303       while ( const TopoDS_Shape* edge = eIt->next() )
6304         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6305     }
6306     // find intersecting _LayerEdge's
6307     for ( size_t i = 0; i < eos._edges.size(); ++i )
6308     {
6309       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6310       _LayerEdge*   edge = eos._edges[i];
6311       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6312       segLen *= 1.2;
6313
6314       gp_Vec eSegDir0, eSegDir1;
6315       if ( edge->IsOnEdge() )
6316       {
6317         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6318         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6319         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6320       }
6321       suspectFaces.clear();
6322       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6323                                      SMDSAbs_Face, suspectFaces );
6324       collEdges._intEdges.clear();
6325       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6326       {
6327         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6328         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6329         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6330         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6331         if ( edge->IsOnEdge() ) {
6332           if ( edge->_2neibors->include( f->_le1 ) ||
6333                edge->_2neibors->include( f->_le2 )) continue;
6334         }
6335         else {
6336           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6337               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6338         }
6339         dist1 = dist2 = Precision::Infinite();
6340         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6341           dist1 = Precision::Infinite();
6342         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6343           dist2 = Precision::Infinite();
6344         if (( dist1 > segLen ) && ( dist2 > segLen ))
6345           continue;
6346
6347         if ( edge->IsOnEdge() )
6348         {
6349           // skip perpendicular EDGEs
6350           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6351           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6352                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6353                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6354                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6355           if ( !isParallel )
6356             continue;
6357         }
6358
6359         // either limit inflation of edges or remember them for updating _normal
6360         // double dot = edge->_normal * f->GetDir();
6361         // if ( dot > 0.1 )
6362         {
6363           collEdges._intEdges.push_back( f->_le1 );
6364           collEdges._intEdges.push_back( f->_le2 );
6365         }
6366         // else
6367         // {
6368         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6369         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6370         // }
6371       }
6372
6373       if ( !collEdges._intEdges.empty() )
6374       {
6375         collEdges._edge = edge;
6376         data._collisionEdges.push_back( collEdges );
6377       }
6378     }
6379   }
6380
6381   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6382     delete tmpFaces[i];
6383
6384   // restore the zero thickness
6385   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6386   {
6387     _EdgesOnShape& eos = data._edgesOnShape[iS];
6388     if ( eos._edges.empty() ) continue;
6389     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6390
6391     for ( size_t i = 0; i < eos._edges.size(); ++i )
6392     {
6393       eos._edges[i]->InvalidateStep( 1, eos );
6394       eos._edges[i]->_len = 0;
6395     }
6396   }
6397 }
6398
6399 //================================================================================
6400 /*!
6401  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6402  * _LayerEdge's on neighbor EDGE's
6403  */
6404 //================================================================================
6405
6406 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6407                                      SMESH_MesherHelper& helper,
6408                                      int                 stepNb,
6409                                      double              stepSize)
6410 {
6411   updateNormalsOfC1Vertices( data );
6412
6413   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6414     return false;
6415
6416   // map to store new _normal and _cosin for each intersected edge
6417   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6418   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6419   _LayerEdge zeroEdge;
6420   zeroEdge._normal.SetCoord( 0,0,0 );
6421   zeroEdge._maxLen = Precision::Infinite();
6422   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6423
6424   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6425
6426   double segLen, dist1, dist2, dist;
6427   vector< pair< _LayerEdge*, double > > intEdgesDist;
6428   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6429
6430   for ( int iter = 0; iter < 5; ++iter )
6431   {
6432     edge2newEdge.clear();
6433
6434     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6435     {
6436       _CollisionEdges& ce = data._collisionEdges[iE];
6437       _LayerEdge*   edge1 = ce._edge;
6438       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6439       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6440       if ( !eos1 ) continue;
6441
6442       // detect intersections
6443       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6444       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6445       double     eps = 0.5;
6446       intEdgesDist.clear();
6447       double minIntDist = Precision::Infinite();
6448       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6449       {
6450         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6451              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6452              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6453           continue;
6454         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6455         double fact = ( 1.1 + dot * dot );
6456         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6457         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6458         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6459         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6460         dist1 = dist2 = Precision::Infinite();
6461         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6462              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6463           continue;
6464         dist = dist1;
6465         if ( dist > testLen || dist <= 0 )
6466         {
6467           dist = dist2;
6468           if ( dist > testLen || dist <= 0 )
6469             continue;
6470         }
6471         // choose a closest edge
6472         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6473         double d1 = intP.SquareDistance( pSrc0 );
6474         double d2 = intP.SquareDistance( pSrc1 );
6475         int iClose = i + ( d2 < d1 );
6476         _LayerEdge* edge2 = ce._intEdges[iClose];
6477         edge2->Unset( _LayerEdge::MARKED );
6478
6479         // choose a closest edge among neighbors
6480         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6481         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6482         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6483         {
6484           _LayerEdge * edgeJ = intEdgesDist[j].first;
6485           if ( edge2->IsNeiborOnEdge( edgeJ ))
6486           {
6487             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6488             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6489           }
6490         }
6491         intEdgesDist.push_back( make_pair( edge2, dist ));
6492         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6493         // {
6494         //   iClose = i + !( d2 < d1 );
6495         //   intEdges.push_back( ce._intEdges[iClose] );
6496         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6497         // }
6498         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6499       }
6500
6501       //ce._edge = 0;
6502
6503       // compute new _normals
6504       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6505       {
6506         _LayerEdge* edge2    = intEdgesDist[i].first;
6507         double       distWgt = edge1->_len / intEdgesDist[i].second;
6508         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6509         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6510         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6511         edge2->Set( _LayerEdge::MARKED );
6512
6513         // get a new normal
6514         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6515
6516         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6517         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6518         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6519         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6520         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6521         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6522         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6523         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6524         newNormal.Normalize();
6525
6526         // get new cosin
6527         double newCos;
6528         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6529         if ( cos1 < theMinSmoothCosin )
6530         {
6531           newCos = cos2 * sgn1;
6532         }
6533         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6534         {
6535           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6536         }
6537         else
6538         {
6539           newCos = edge1->_cosin;
6540         }
6541
6542         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6543         e2neIt->second._normal += distWgt * newNormal;
6544         e2neIt->second._cosin   = newCos;
6545         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6546         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6547           e2neIt->second._normal += dir2;
6548         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6549         e2neIt->second._normal += distWgt * newNormal;
6550         e2neIt->second._cosin   = edge2->_cosin;
6551         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6552           e2neIt->second._normal += dir1;
6553       }
6554     }
6555
6556     if ( edge2newEdge.empty() )
6557       break; //return true;
6558
6559     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6560
6561     // Update data of edges depending on a new _normal
6562
6563     data.UnmarkEdges();
6564     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6565     {
6566       _LayerEdge*    edge = e2neIt->first;
6567       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6568       _LayerEdge& newEdge = e2neIt->second;
6569       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6570
6571       // Check if a new _normal is OK:
6572       newEdge._normal.Normalize();
6573       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6574       {
6575         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6576         {
6577           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6578           edge->_maxLen = newEdge._maxLen;
6579           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6580         }
6581         continue; // the new _normal is bad
6582       }
6583       // the new _normal is OK
6584
6585       // find shapes that need smoothing due to change of _normal
6586       if ( edge->_cosin   < theMinSmoothCosin &&
6587            newEdge._cosin > theMinSmoothCosin )
6588       {
6589         if ( eos->_sWOL.IsNull() )
6590         {
6591           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6592           while ( fIt->more() )
6593             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6594         }
6595         else // edge inflates along a FACE
6596         {
6597           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6598           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6599           while ( const TopoDS_Shape* E = eIt->next() )
6600           {
6601             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6602               continue;
6603             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6604             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6605             if ( angle < M_PI / 2 )
6606               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6607           }
6608         }
6609       }
6610
6611       double len = edge->_len;
6612       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6613       edge->SetNormal( newEdge._normal );
6614       edge->SetCosin( newEdge._cosin );
6615       edge->SetNewLength( len, *eos, helper );
6616       edge->Set( _LayerEdge::MARKED );
6617       edge->Set( _LayerEdge::NORMAL_UPDATED );
6618       edgesNoAnaSmooth.insert( eos );
6619     }
6620
6621     // Update normals and other dependent data of not intersecting _LayerEdge's
6622     // neighboring the intersecting ones
6623
6624     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6625     {
6626       _LayerEdge*   edge1 = e2neIt->first;
6627       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6628       if ( !edge1->Is( _LayerEdge::MARKED ))
6629         continue;
6630
6631       if ( edge1->IsOnEdge() )
6632       {
6633         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6634         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6635         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6636       }
6637
6638       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6639         continue;
6640       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6641       {
6642         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6643         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6644           continue; // j-th neighbor is also intersected
6645         _LayerEdge* prevEdge = edge1;
6646         const int nbSteps = 10;
6647         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6648         {
6649           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6650                neighbor->Is( _LayerEdge::MARKED ))
6651             break;
6652           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6653           if ( !eos ) continue;
6654           _LayerEdge* nextEdge = neighbor;
6655           if ( neighbor->_2neibors )
6656           {
6657             int iNext = 0;
6658             nextEdge = neighbor->_2neibors->_edges[iNext];
6659             if ( nextEdge == prevEdge )
6660               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6661           }
6662           double r = double(step-1)/nbSteps/(iter+1);
6663           if ( !nextEdge->_2neibors )
6664             r = Min( r, 0.5 );
6665
6666           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6667           newNorm.Normalize();
6668           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6669             break;
6670
6671           double len = neighbor->_len;
6672           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6673           neighbor->SetNormal( newNorm );
6674           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6675           if ( neighbor->_2neibors )
6676             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6677           neighbor->SetNewLength( len, *eos, helper );
6678           neighbor->Set( _LayerEdge::MARKED );
6679           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6680           edgesNoAnaSmooth.insert( eos );
6681
6682           if ( !neighbor->_2neibors )
6683             break; // neighbor is on VERTEX
6684
6685           // goto the next neighbor
6686           prevEdge = neighbor;
6687           neighbor = nextEdge;
6688         }
6689       }
6690     }
6691     dumpFunctionEnd();
6692   } // iterations
6693
6694   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6695
6696   return true;
6697 }
6698
6699 //================================================================================
6700 /*!
6701  * \brief Check if a new normal is OK
6702  */
6703 //================================================================================
6704
6705 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6706                                      _LayerEdge&   edge,
6707                                      const gp_XYZ& newNormal)
6708 {
6709   // check a min angle between the newNormal and surrounding faces
6710   vector<_Simplex> simplices;
6711   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6712   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6713   double newMinDot = 1, curMinDot = 1;
6714   for ( size_t i = 0; i < simplices.size(); ++i )
6715   {
6716     n1.Set( simplices[i]._nPrev );
6717     n2.Set( simplices[i]._nNext );
6718     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6719     double normLen2 = normFace.SquareModulus();
6720     if ( normLen2 < std::numeric_limits<double>::min() )
6721       continue;
6722     normFace /= Sqrt( normLen2 );
6723     newMinDot = Min( newNormal    * normFace, newMinDot );
6724     curMinDot = Min( edge._normal * normFace, curMinDot );
6725   }
6726   bool ok = true;
6727   if ( newMinDot < 0.5 )
6728   {
6729     ok = ( newMinDot >= curMinDot * 0.9 );
6730     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6731     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6732     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6733   }
6734
6735   return ok;
6736 }
6737
6738 //================================================================================
6739 /*!
6740  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6741  */
6742 //================================================================================
6743
6744 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6745                                                SMESH_MesherHelper& helper,
6746                                                const int           nbSteps,
6747                                                const double        stepSize )
6748 {
6749   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6750     return true; // no shapes needing smoothing
6751
6752   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6753   {
6754     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6755     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6756          !eos._hyp.ToSmooth() ||
6757          eos.ShapeType() != TopAbs_FACE ||
6758          eos._edges.empty() )
6759       continue;
6760
6761     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6762     if ( !toSmooth ) continue;
6763
6764     for ( size_t i = 0; i < eos._edges.size(); ++i )
6765     {
6766       _LayerEdge* edge = eos._edges[i];
6767       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6768         continue;
6769       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6770         continue;
6771
6772       const gp_XYZ& pPrev = edge->PrevPos();
6773       const gp_XYZ& pLast = edge->_pos.back();
6774       gp_XYZ      stepVec = pLast - pPrev;
6775       double realStepSize = stepVec.Modulus();
6776       if ( realStepSize < numeric_limits<double>::min() )
6777         continue;
6778
6779       edge->_lenFactor = realStepSize / stepSize;
6780       edge->_normal    = stepVec / realStepSize;
6781       edge->Set( _LayerEdge::NORMAL_UPDATED );
6782     }
6783   }
6784
6785   return true;
6786 }
6787
6788 //================================================================================
6789 /*!
6790  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6791  */
6792 //================================================================================
6793
6794 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6795 {
6796   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6797   {
6798     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6799     if ( eov._eosC1.empty() ||
6800          eov.ShapeType() != TopAbs_VERTEX ||
6801          eov._edges.empty() )
6802       continue;
6803
6804     gp_XYZ newNorm   = eov._edges[0]->_normal;
6805     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6806     bool normChanged = false;
6807
6808     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6809     {
6810       _EdgesOnShape*   eoe = eov._eosC1[i];
6811       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6812       const double    eLen = SMESH_Algo::EdgeLength( e );
6813       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6814       if ( oppV.IsSame( eov._shape ))
6815         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6816       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6817       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6818       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6819
6820       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6821       if ( curThickOpp + curThick < eLen )
6822         continue;
6823
6824       double wgt = 2. * curThick / eLen;
6825       newNorm += wgt * eovOpp->_edges[0]->_normal;
6826       normChanged = true;
6827     }
6828     if ( normChanged )
6829     {
6830       eov._edges[0]->SetNormal( newNorm.Normalized() );
6831       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6832     }
6833   }
6834 }
6835
6836 //================================================================================
6837 /*!
6838  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6839  */
6840 //================================================================================
6841
6842 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6843                                                   SMESH_MesherHelper& helper,
6844                                                   int                 stepNb )
6845 {
6846   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6847   bool isOK;
6848
6849   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6850   for ( ; id2face != data._convexFaces.end(); ++id2face )
6851   {
6852     _ConvexFace & convFace = (*id2face).second;
6853     if ( convFace._normalsFixed )
6854       continue; // already fixed
6855     if ( convFace.CheckPrisms() )
6856       continue; // nothing to fix
6857
6858     convFace._normalsFixed = true;
6859
6860     BRepAdaptor_Surface surface ( convFace._face, false );
6861     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6862
6863     // check if the convex FACE is of spherical shape
6864
6865     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6866     Bnd_B3d nodesBox;
6867     gp_Pnt  center;
6868
6869     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6870     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6871     {
6872       _EdgesOnShape& eos = *(id2eos->second);
6873       if ( eos.ShapeType() == TopAbs_VERTEX )
6874       {
6875         _LayerEdge* ledge = eos._edges[ 0 ];
6876         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6877           centersBox.Add( center );
6878       }
6879       for ( size_t i = 0; i < eos._edges.size(); ++i )
6880         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6881     }
6882     if ( centersBox.IsVoid() )
6883     {
6884       debugMsg( "Error: centersBox.IsVoid()" );
6885       return false;
6886     }
6887     const bool isSpherical =
6888       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6889
6890     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6891     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6892
6893     if ( isSpherical )
6894     {
6895       // set _LayerEdge::_normal as average of all normals
6896
6897       // WARNING: different density of nodes on EDGEs is not taken into account that
6898       // can lead to an improper new normal
6899
6900       gp_XYZ avgNormal( 0,0,0 );
6901       nbEdges = 0;
6902       id2eos = convFace._subIdToEOS.begin();
6903       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6904       {
6905         _EdgesOnShape& eos = *(id2eos->second);
6906         // set data of _CentralCurveOnEdge
6907         if ( eos.ShapeType() == TopAbs_EDGE )
6908         {
6909           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6910           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6911           if ( !eos._sWOL.IsNull() )
6912             ceCurve._adjFace.Nullify();
6913           else
6914             ceCurve._ledges.insert( ceCurve._ledges.end(),
6915                                     eos._edges.begin(), eos._edges.end());
6916         }
6917         // summarize normals
6918         for ( size_t i = 0; i < eos._edges.size(); ++i )
6919           avgNormal += eos._edges[ i ]->_normal;
6920       }
6921       double normSize = avgNormal.SquareModulus();
6922       if ( normSize < 1e-200 )
6923       {
6924         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6925         return false;
6926       }
6927       avgNormal /= Sqrt( normSize );
6928
6929       // compute new _LayerEdge::_cosin on EDGEs
6930       double avgCosin = 0;
6931       int     nbCosin = 0;
6932       gp_Vec inFaceDir;
6933       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6934       {
6935         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6936         if ( ceCurve._adjFace.IsNull() )
6937           continue;
6938         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6939         {
6940           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6941           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6942           if ( isOK )
6943           {
6944             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6945             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6946             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6947             nbCosin++;
6948           }
6949         }
6950       }
6951       if ( nbCosin > 0 )
6952         avgCosin /= nbCosin;
6953
6954       // set _LayerEdge::_normal = avgNormal
6955       id2eos = convFace._subIdToEOS.begin();
6956       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6957       {
6958         _EdgesOnShape& eos = *(id2eos->second);
6959         if ( eos.ShapeType() != TopAbs_EDGE )
6960           for ( size_t i = 0; i < eos._edges.size(); ++i )
6961             eos._edges[ i ]->_cosin = avgCosin;
6962
6963         for ( size_t i = 0; i < eos._edges.size(); ++i )
6964         {
6965           eos._edges[ i ]->SetNormal( avgNormal );
6966           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6967         }
6968       }
6969     }
6970     else // if ( isSpherical )
6971     {
6972       // We suppose that centers of curvature at all points of the FACE
6973       // lie on some curve, let's call it "central curve". For all _LayerEdge's
6974       // having a common center of curvature we define the same new normal
6975       // as a sum of normals of _LayerEdge's on EDGEs among them.
6976
6977       // get all centers of curvature for each EDGE
6978
6979       helper.SetSubShape( convFace._face );
6980       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6981
6982       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6983       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6984       {
6985         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6986
6987         // set adjacent FACE
6988         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
6989
6990         // get _LayerEdge's of the EDGE
6991         TGeomID edgeID = meshDS->ShapeToIndex( edge );
6992         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
6993         if ( !eos || eos->_edges.empty() )
6994         {
6995           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
6996           for ( int iV = 0; iV < 2; ++iV )
6997           {
6998             TopoDS_Vertex v = helper.IthVertex( iV, edge );
6999             TGeomID     vID = meshDS->ShapeToIndex( v );
7000             eos = data.GetShapeEdges( vID );
7001             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7002           }
7003           edgeLEdge    = &vertexLEdges[0];
7004           edgeLEdgeEnd = edgeLEdge + 2;
7005
7006           centerCurves[ iE ]._adjFace.Nullify();
7007         }
7008         else
7009         {
7010           if ( ! eos->_toSmooth )
7011             data.SortOnEdge( edge, eos->_edges );
7012           edgeLEdge    = &eos->_edges[ 0 ];
7013           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7014           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7015           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7016
7017           if ( ! eos->_sWOL.IsNull() )
7018             centerCurves[ iE ]._adjFace.Nullify();
7019         }
7020
7021         // Get curvature centers
7022
7023         centersBox.Clear();
7024
7025         if ( edgeLEdge[0]->IsOnEdge() &&
7026              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7027         { // 1st VERTEX
7028           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7029           centersBox.Add( center );
7030         }
7031         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7032           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7033           { // EDGE or VERTEXes
7034             centerCurves[ iE ].Append( center, *edgeLEdge );
7035             centersBox.Add( center );
7036           }
7037         if ( edgeLEdge[-1]->IsOnEdge() &&
7038              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7039         { // 2nd VERTEX
7040           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7041           centersBox.Add( center );
7042         }
7043         centerCurves[ iE ]._isDegenerated =
7044           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7045
7046       } // loop on EDGES of convFace._face to set up data of centerCurves
7047
7048       // Compute new normals for _LayerEdge's on EDGEs
7049
7050       double avgCosin = 0;
7051       int     nbCosin = 0;
7052       gp_Vec inFaceDir;
7053       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7054       {
7055         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7056         if ( ceCurve._isDegenerated )
7057           continue;
7058         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7059         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7060         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7061         {
7062           isOK = false;
7063           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7064           {
7065             if ( iE1 != iE2 )
7066               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7067           }
7068           if ( isOK && !ceCurve._adjFace.IsNull() )
7069           {
7070             // compute new _LayerEdge::_cosin
7071             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7072             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7073             if ( isOK )
7074             {
7075               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7076               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7077               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7078               nbCosin++;
7079             }
7080           }
7081         }
7082       }
7083       // set new normals to _LayerEdge's of NOT degenerated central curves
7084       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7085       {
7086         if ( centerCurves[ iE ]._isDegenerated )
7087           continue;
7088         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7089         {
7090           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7091           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7092         }
7093       }
7094       // set new normals to _LayerEdge's of     degenerated central curves
7095       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7096       {
7097         if ( !centerCurves[ iE ]._isDegenerated ||
7098              centerCurves[ iE ]._ledges.size() < 3 )
7099           continue;
7100         // new normal is an average of new normals at VERTEXes that
7101         // was computed on non-degenerated _CentralCurveOnEdge's
7102         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7103                            centerCurves[ iE ]._ledges.back ()->_normal );
7104         double sz = newNorm.Modulus();
7105         if ( sz < 1e-200 )
7106           continue;
7107         newNorm /= sz;
7108         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7109                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7110         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7111         {
7112           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7113           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7114           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7115         }
7116       }
7117
7118       // Find new normals for _LayerEdge's based on FACE
7119
7120       if ( nbCosin > 0 )
7121         avgCosin /= nbCosin;
7122       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7123       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7124       if ( id2eos != convFace._subIdToEOS.end() )
7125       {
7126         int iE = 0;
7127         gp_XYZ newNorm;
7128         _EdgesOnShape& eos = * ( id2eos->second );
7129         for ( size_t i = 0; i < eos._edges.size(); ++i )
7130         {
7131           _LayerEdge* ledge = eos._edges[ i ];
7132           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7133             continue;
7134           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7135           {
7136             iE = iE % centerCurves.size();
7137             if ( centerCurves[ iE ]._isDegenerated )
7138               continue;
7139             newNorm.SetCoord( 0,0,0 );
7140             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7141             {
7142               ledge->SetNormal( newNorm );
7143               ledge->_cosin  = avgCosin;
7144               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7145               break;
7146             }
7147           }
7148         }
7149       }
7150
7151     } // not a quasi-spherical FACE
7152
7153     // Update _LayerEdge's data according to a new normal
7154
7155     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7156                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7157
7158     id2eos = convFace._subIdToEOS.begin();
7159     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7160     {
7161       _EdgesOnShape& eos = * ( id2eos->second );
7162       for ( size_t i = 0; i < eos._edges.size(); ++i )
7163       {
7164         _LayerEdge* & ledge = eos._edges[ i ];
7165         double len = ledge->_len;
7166         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7167         ledge->SetCosin( ledge->_cosin );
7168         ledge->SetNewLength( len, eos, helper );
7169       }
7170       if ( eos.ShapeType() != TopAbs_FACE )
7171         for ( size_t i = 0; i < eos._edges.size(); ++i )
7172         {
7173           _LayerEdge* ledge = eos._edges[ i ];
7174           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7175           {
7176             _LayerEdge* neibor = ledge->_neibors[iN];
7177             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7178             {
7179               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7180               neibor->Set( _LayerEdge::MOVED );
7181               neibor->SetSmooLen( neibor->_len );
7182             }
7183           }
7184         }
7185     } // loop on sub-shapes of convFace._face
7186
7187     // Find FACEs adjacent to convFace._face that got necessity to smooth
7188     // as a result of normals modification
7189
7190     set< _EdgesOnShape* > adjFacesToSmooth;
7191     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7192     {
7193       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7194            centerCurves[ iE ]._adjFaceToSmooth )
7195         continue;
7196       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7197       {
7198         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7199         {
7200           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7201           break;
7202         }
7203       }
7204     }
7205     data.AddShapesToSmooth( adjFacesToSmooth );
7206
7207     dumpFunctionEnd();
7208
7209
7210   } // loop on data._convexFaces
7211
7212   return true;
7213 }
7214
7215 //================================================================================
7216 /*!
7217  * \brief Finds a center of curvature of a surface at a _LayerEdge
7218  */
7219 //================================================================================
7220
7221 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7222                                         BRepLProp_SLProps&  surfProp,
7223                                         SMESH_MesherHelper& helper,
7224                                         gp_Pnt &            center ) const
7225 {
7226   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7227   surfProp.SetParameters( uv.X(), uv.Y() );
7228   if ( !surfProp.IsCurvatureDefined() )
7229     return false;
7230
7231   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7232   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7233   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7234   if ( surfCurvatureMin > surfCurvatureMax )
7235     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7236   else
7237     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7238
7239   return true;
7240 }
7241
7242 //================================================================================
7243 /*!
7244  * \brief Check that prisms are not distorted
7245  */
7246 //================================================================================
7247
7248 bool _ConvexFace::CheckPrisms() const
7249 {
7250   double vol = 0;
7251   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7252   {
7253     const _LayerEdge* edge = _simplexTestEdges[i];
7254     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7255     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7256       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7257       {
7258         debugMsg( "Bad simplex of _simplexTestEdges ("
7259                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7260                   << " "<< edge->_simplices[j]._nPrev->GetID()
7261                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7262         return false;
7263       }
7264   }
7265   return true;
7266 }
7267
7268 //================================================================================
7269 /*!
7270  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7271  *        stored in this _CentralCurveOnEdge.
7272  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7273  *  \param [in,out] newNormal - current normal at this point, to be redefined
7274  *  \return bool - true if succeeded.
7275  */
7276 //================================================================================
7277
7278 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7279 {
7280   if ( this->_isDegenerated )
7281     return false;
7282
7283   // find two centers the given one lies between
7284
7285   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7286   {
7287     double sl2 = 1.001 * _segLength2[ i ];
7288
7289     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7290     if ( d1 > sl2 )
7291       continue;
7292     
7293     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7294     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7295       continue;
7296
7297     d1 = Sqrt( d1 );
7298     d2 = Sqrt( d2 );
7299     double r = d1 / ( d1 + d2 );
7300     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7301                    (      r ) * _ledges[ i+1 ]->_normal );
7302     norm.Normalize();
7303
7304     newNormal += norm;
7305     double sz = newNormal.Modulus();
7306     if ( sz < 1e-200 )
7307       break;
7308     newNormal /= sz;
7309     return true;
7310   }
7311   return false;
7312 }
7313
7314 //================================================================================
7315 /*!
7316  * \brief Set shape members
7317  */
7318 //================================================================================
7319
7320 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7321                                      const _ConvexFace&  convFace,
7322                                      _SolidData&         data,
7323                                      SMESH_MesherHelper& helper)
7324 {
7325   _edge = edge;
7326
7327   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7328   while ( const TopoDS_Shape* F = fIt->next())
7329     if ( !convFace._face.IsSame( *F ))
7330     {
7331       _adjFace = TopoDS::Face( *F );
7332       _adjFaceToSmooth = false;
7333       // _adjFace already in a smoothing queue ?
7334       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7335         _adjFaceToSmooth = eos->_toSmooth;
7336       break;
7337     }
7338 }
7339
7340 //================================================================================
7341 /*!
7342  * \brief Looks for intersection of it's last segment with faces
7343  *  \param distance - returns shortest distance from the last node to intersection
7344  */
7345 //================================================================================
7346
7347 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7348                                    double &                 distance,
7349                                    const double&            epsilon,
7350                                    _EdgesOnShape&           eos,
7351                                    const SMDS_MeshElement** intFace)
7352 {
7353   vector< const SMDS_MeshElement* > suspectFaces;
7354   double segLen;
7355   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7356   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7357
7358   bool segmentIntersected = false;
7359   distance = Precision::Infinite();
7360   int iFace = -1; // intersected face
7361   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7362   {
7363     const SMDS_MeshElement* face = suspectFaces[j];
7364     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7365          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7366       continue; // face sharing _LayerEdge node
7367     const int nbNodes = face->NbCornerNodes();
7368     bool intFound = false;
7369     double dist;
7370     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7371     if ( nbNodes == 3 )
7372     {
7373       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7374     }
7375     else
7376     {
7377       const SMDS_MeshNode* tria[3];
7378       tria[0] = *nIt++;
7379       tria[1] = *nIt++;
7380       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7381       {
7382         tria[2] = *nIt++;
7383         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7384         tria[1] = tria[2];
7385       }
7386     }
7387     if ( intFound )
7388     {
7389       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7390         segmentIntersected = true;
7391       if ( distance > dist )
7392         distance = dist, iFace = j;
7393     }
7394   }
7395   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7396
7397   distance -= segLen;
7398
7399   if ( segmentIntersected )
7400   {
7401 #ifdef __myDEBUG
7402     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7403     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7404     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7405          << ", intersection with face ("
7406          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7407          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7408          << ") distance = " << distance << endl;
7409 #endif
7410   }
7411
7412   return segmentIntersected;
7413 }
7414
7415 //================================================================================
7416 /*!
7417  * \brief Returns a point used to check orientation of _simplices
7418  */
7419 //================================================================================
7420
7421 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7422 {
7423   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7424
7425   if ( !eos || eos->_sWOL.IsNull() )
7426     return _pos[ i ];
7427
7428   if ( eos->SWOLType() == TopAbs_EDGE )
7429   {
7430     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7431   }
7432   //else //  TopAbs_FACE
7433
7434   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7435 }
7436
7437 //================================================================================
7438 /*!
7439  * \brief Returns size and direction of the last segment
7440  */
7441 //================================================================================
7442
7443 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7444 {
7445   // find two non-coincident positions
7446   gp_XYZ orig = _pos.back();
7447   gp_XYZ vec;
7448   int iPrev = _pos.size() - 2;
7449   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7450   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7451   while ( iPrev >= 0 )
7452   {
7453     vec = orig - _pos[iPrev];
7454     if ( vec.SquareModulus() > tol*tol )
7455       break;
7456     else
7457       iPrev--;
7458   }
7459
7460   // make gp_Ax1
7461   gp_Ax1 segDir;
7462   if ( iPrev < 0 )
7463   {
7464     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7465     segDir.SetDirection( _normal );
7466     segLen = 0;
7467   }
7468   else
7469   {
7470     gp_Pnt pPrev = _pos[ iPrev ];
7471     if ( !eos._sWOL.IsNull() )
7472     {
7473       TopLoc_Location loc;
7474       if ( eos.SWOLType() == TopAbs_EDGE )
7475       {
7476         double f,l;
7477         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7478         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7479       }
7480       else
7481       {
7482         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7483         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7484       }
7485       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7486     }
7487     segDir.SetLocation( pPrev );
7488     segDir.SetDirection( vec );
7489     segLen = vec.Modulus();
7490   }
7491
7492   return segDir;
7493 }
7494
7495 //================================================================================
7496 /*!
7497  * \brief Return the last position of the target node on a FACE. 
7498  *  \param [in] F - the FACE this _LayerEdge is inflated along
7499  *  \return gp_XY - result UV
7500  */
7501 //================================================================================
7502
7503 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7504 {
7505   if ( F.IsSame( eos._sWOL )) // F is my FACE
7506     return gp_XY( _pos.back().X(), _pos.back().Y() );
7507
7508   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7509     return gp_XY( 1e100, 1e100 );
7510
7511   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7512   double f, l, u = _pos.back().X();
7513   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7514   if ( !C2d.IsNull() && f <= u && u <= l )
7515     return C2d->Value( u ).XY();
7516
7517   return gp_XY( 1e100, 1e100 );
7518 }
7519
7520 //================================================================================
7521 /*!
7522  * \brief Test intersection of the last segment with a given triangle
7523  *   using Moller-Trumbore algorithm
7524  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7525  */
7526 //================================================================================
7527
7528 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7529                                const gp_XYZ& vert0,
7530                                const gp_XYZ& vert1,
7531                                const gp_XYZ& vert2,
7532                                double&       t,
7533                                const double& EPSILON) const
7534 {
7535   const gp_Pnt& orig = lastSegment.Location();
7536   const gp_Dir& dir  = lastSegment.Direction();
7537
7538   /* calculate distance from vert0 to ray origin */
7539   gp_XYZ tvec = orig.XYZ() - vert0;
7540
7541   //if ( tvec * dir > EPSILON )
7542     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7543     //return false;
7544
7545   gp_XYZ edge1 = vert1 - vert0;
7546   gp_XYZ edge2 = vert2 - vert0;
7547
7548   /* begin calculating determinant - also used to calculate U parameter */
7549   gp_XYZ pvec = dir.XYZ() ^ edge2;
7550
7551   /* if determinant is near zero, ray lies in plane of triangle */
7552   double det = edge1 * pvec;
7553
7554   const double ANGL_EPSILON = 1e-12;
7555   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7556     return false;
7557
7558   /* calculate U parameter and test bounds */
7559   double u = ( tvec * pvec ) / det;
7560   //if (u < 0.0 || u > 1.0)
7561   if ( u < -EPSILON || u > 1.0 + EPSILON )
7562     return false;
7563
7564   /* prepare to test V parameter */
7565   gp_XYZ qvec = tvec ^ edge1;
7566
7567   /* calculate V parameter and test bounds */
7568   double v = (dir.XYZ() * qvec) / det;
7569   //if ( v < 0.0 || u + v > 1.0 )
7570   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7571     return false;
7572
7573   /* calculate t, ray intersects triangle */
7574   t = (edge2 * qvec) / det;
7575
7576   //return true;
7577   return t > 0.;
7578 }
7579
7580 //================================================================================
7581 /*!
7582  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7583  *        neighbor _LayerEdge's by it's own inflation vector.
7584  *  \param [in] eov - EOS of the VERTEX
7585  *  \param [in] eos - EOS of the FACE
7586  *  \param [in] step - inflation step
7587  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7588  */
7589 //================================================================================
7590
7591 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7592                                    const _EdgesOnShape*    eos,
7593                                    const int               step,
7594                                    vector< _LayerEdge* > & badSmooEdges )
7595 {
7596   // check if any of _neibors is in badSmooEdges
7597   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7598                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7599     return;
7600
7601   // get all edges to move
7602
7603   set< _LayerEdge* > edges;
7604
7605   // find a distance between _LayerEdge on VERTEX and its neighbors
7606   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7607   double dist2 = 0;
7608   for ( size_t i = 0; i < _neibors.size(); ++i )
7609   {
7610     _LayerEdge* nEdge = _neibors[i];
7611     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7612     {
7613       edges.insert( nEdge );
7614       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7615     }
7616   }
7617   // add _LayerEdge's close to curPosV
7618   size_t nbE;
7619   do {
7620     nbE = edges.size();
7621     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7622     {
7623       _LayerEdge* edgeF = *e;
7624       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7625       {
7626         _LayerEdge* nEdge = edgeF->_neibors[i];
7627         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7628              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7629           edges.insert( nEdge );
7630       }
7631     }
7632   }
7633   while ( nbE < edges.size() );
7634
7635   // move the target node of the got edges
7636
7637   gp_XYZ prevPosV = PrevPos();
7638   if ( eov->SWOLType() == TopAbs_EDGE )
7639   {
7640     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7641     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7642   }
7643   else if ( eov->SWOLType() == TopAbs_FACE )
7644   {
7645     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7646     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7647   }
7648
7649   SMDS_FacePosition* fPos;
7650   //double r = 1. - Min( 0.9, step / 10. );
7651   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7652   {
7653     _LayerEdge*       edgeF = *e;
7654     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7655     const gp_XYZ    newPosF = curPosV + prevVF;
7656     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7657     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7658     edgeF->_pos.back() = newPosF;
7659     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7660
7661     // set _curvature to make edgeF updated by putOnOffsetSurface()
7662     if ( !edgeF->_curvature )
7663       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7664       {
7665         edgeF->_curvature = new _Curvature;
7666         edgeF->_curvature->_r = 0;
7667         edgeF->_curvature->_k = 0;
7668         edgeF->_curvature->_h2lenRatio = 0;
7669         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7670       }
7671   }
7672   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7673   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7674   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7675   // {
7676   //   _LayerEdge*      edgeF = *e;
7677   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7678   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7679   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7680   //   edgeF->_pos.back() = newPosF;
7681   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7682   // }
7683
7684   // smooth _LayerEdge's around moved nodes
7685   //size_t nbBadBefore = badSmooEdges.size();
7686   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7687   {
7688     _LayerEdge* edgeF = *e;
7689     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7690       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7691         //&& !edges.count( edgeF->_neibors[j] ))
7692       {
7693         _LayerEdge* edgeFN = edgeF->_neibors[j];
7694         edgeFN->Unset( SMOOTHED );
7695         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7696         // if ( nbBad > 0 )
7697         // {
7698         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7699         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7700         //   int        nbBadAfter = edgeFN->_simplices.size();
7701         //   double vol;
7702         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7703         //   {
7704         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7705         //   }
7706         //   if ( nbBadAfter <= nbBad )
7707         //   {
7708         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7709         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7710         //     edgeF->_pos.back() = newPosF;
7711         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7712         //     nbBad = nbBadAfter;
7713         //   }
7714         // }
7715         if ( nbBad > 0 )
7716           badSmooEdges.push_back( edgeFN );
7717       }
7718   }
7719     // move a bit not smoothed around moved nodes
7720   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7721   //   {
7722   //   _LayerEdge*      edgeF = badSmooEdges[i];
7723   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7724   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7725   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7726   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7727   //   edgeF->_pos.back() = newPosF;
7728   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7729   // }
7730 }
7731
7732 //================================================================================
7733 /*!
7734  * \brief Perform smooth of _LayerEdge's based on EDGE's
7735  *  \retval bool - true if node has been moved
7736  */
7737 //================================================================================
7738
7739 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7740                               const TopoDS_Face&             F,
7741                               SMESH_MesherHelper&            helper)
7742 {
7743   ASSERT( IsOnEdge() );
7744
7745   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7746   SMESH_TNodeXYZ oldPos( tgtNode );
7747   double dist01, distNewOld;
7748   
7749   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7750   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7751   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7752
7753   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7754   double lenDelta = 0;
7755   if ( _curvature )
7756   {
7757     //lenDelta = _curvature->lenDelta( _len );
7758     lenDelta = _curvature->lenDeltaByDist( dist01 );
7759     newPos.ChangeCoord() += _normal * lenDelta;
7760   }
7761
7762   distNewOld = newPos.Distance( oldPos );
7763
7764   if ( F.IsNull() )
7765   {
7766     if ( _2neibors->_plnNorm )
7767     {
7768       // put newPos on the plane defined by source node and _plnNorm
7769       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7770       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7771       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7772     }
7773     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7774     _pos.back() = newPos.XYZ();
7775   }
7776   else
7777   {
7778     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7779     gp_XY uv( Precision::Infinite(), 0 );
7780     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7781     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7782
7783     newPos = surface->Value( uv );
7784     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7785   }
7786
7787   // commented for IPAL0052478
7788   // if ( _curvature && lenDelta < 0 )
7789   // {
7790   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7791   //   _len -= prevPos.Distance( oldPos );
7792   //   _len += prevPos.Distance( newPos );
7793   // }
7794   bool moved = distNewOld > dist01/50;
7795   //if ( moved )
7796   dumpMove( tgtNode ); // debug
7797
7798   return moved;
7799 }
7800
7801 //================================================================================
7802 /*!
7803  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7804  */
7805 //================================================================================
7806
7807 void _LayerEdge::SmoothWoCheck()
7808 {
7809   if ( Is( DIFFICULT ))
7810     return;
7811
7812   bool moved = Is( SMOOTHED );
7813   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7814     moved = _neibors[i]->Is( SMOOTHED );
7815   if ( !moved )
7816     return;
7817
7818   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7819
7820   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7821   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7822   _pos.back() = newPos;
7823
7824   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7825 }
7826
7827 //================================================================================
7828 /*!
7829  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7830  */
7831 //================================================================================
7832
7833 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7834 {
7835   if ( ! Is( NEAR_BOUNDARY ))
7836     return 0;
7837
7838   int nbBad = 0;
7839   double vol;
7840   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7841   {
7842     _LayerEdge* eN = _neibors[iN];
7843     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7844       continue;
7845     if ( needSmooth )
7846       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7847                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7848                        eN->_pos.size() != _pos.size() );
7849
7850     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7851     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7852     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7853       if ( eN->_nodes.size() > 1 &&
7854            eN->_simplices[i].Includes( _nodes.back() ) &&
7855            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7856       {
7857         ++nbBad;
7858         if ( badNeibors )
7859         {
7860           badNeibors->push_back( eN );
7861           debugMsg("Bad boundary simplex ( "
7862                    << " "<< eN->_nodes[0]->GetID()
7863                    << " "<< eN->_nodes.back()->GetID()
7864                    << " "<< eN->_simplices[i]._nPrev->GetID()
7865                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7866         }
7867         else
7868         {
7869           break;
7870         }
7871       }
7872   }
7873   return nbBad;
7874 }
7875
7876 //================================================================================
7877 /*!
7878  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7879  *  \retval int - nb of bad simplices around this _LayerEdge
7880  */
7881 //================================================================================
7882
7883 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7884 {
7885   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7886     return 0; // shape of simplices not changed
7887   if ( _simplices.size() < 2 )
7888     return 0; // _LayerEdge inflated along EDGE or FACE
7889
7890   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7891     findBest = true;
7892
7893   const gp_XYZ& curPos  = _pos.back();
7894   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7895
7896   // quality metrics (orientation) of tetras around _tgtNode
7897   int nbOkBefore = 0;
7898   double vol, minVolBefore = 1e100;
7899   for ( size_t i = 0; i < _simplices.size(); ++i )
7900   {
7901     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7902     minVolBefore = Min( minVolBefore, vol );
7903   }
7904   int nbBad = _simplices.size() - nbOkBefore;
7905
7906   bool bndNeedSmooth = false;
7907   if ( nbBad == 0 )
7908     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7909   if ( nbBad > 0 )
7910     Set( DISTORTED );
7911
7912   // evaluate min angle
7913   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7914   {
7915     size_t nbGoodAngles = _simplices.size();
7916     double angle;
7917     for ( size_t i = 0; i < _simplices.size(); ++i )
7918     {
7919       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7920         --nbGoodAngles;
7921     }
7922     if ( nbGoodAngles == _simplices.size() )
7923     {
7924       Unset( MOVED );
7925       return 0;
7926     }
7927   }
7928   if ( Is( ON_CONCAVE_FACE ))
7929     findBest = true;
7930
7931   if ( step % 2 == 0 )
7932     findBest = false;
7933
7934   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7935   {
7936     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7937       _smooFunction = _funs[ FUN_CENTROIDAL ];
7938     else
7939       _smooFunction = _funs[ FUN_LAPLACIAN ];
7940   }
7941
7942   // compute new position for the last _pos using different _funs
7943   gp_XYZ newPos;
7944   bool moved = false;
7945   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7946   {
7947     if ( iFun < 0 )
7948       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7949     else if ( _funs[ iFun ] == _smooFunction )
7950       continue; // _smooFunction again
7951     else if ( step > 1 )
7952       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7953     else
7954       break; // let "easy" functions improve elements around distorted ones
7955
7956     if ( _curvature )
7957     {
7958       double delta  = _curvature->lenDelta( _len );
7959       if ( delta > 0 )
7960         newPos += _normal * delta;
7961       else
7962       {
7963         double segLen = _normal * ( newPos - prevPos );
7964         if ( segLen + delta > 0 )
7965           newPos += _normal * delta;
7966       }
7967       // double segLenChange = _normal * ( curPos - newPos );
7968       // newPos += 0.5 * _normal * segLenChange;
7969     }
7970
7971     int nbOkAfter = 0;
7972     double minVolAfter = 1e100;
7973     for ( size_t i = 0; i < _simplices.size(); ++i )
7974     {
7975       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7976       minVolAfter = Min( minVolAfter, vol );
7977     }
7978     // get worse?
7979     if ( nbOkAfter < nbOkBefore )
7980       continue;
7981
7982     if (( findBest ) &&
7983         ( nbOkAfter == nbOkBefore ) &&
7984         ( minVolAfter <= minVolBefore ))
7985       continue;
7986
7987     nbBad        = _simplices.size() - nbOkAfter;
7988     minVolBefore = minVolAfter;
7989     nbOkBefore   = nbOkAfter;
7990     moved        = true;
7991
7992     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7993     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7994     _pos.back() = newPos;
7995
7996     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7997                   << (nbBad ? " --BAD" : ""));
7998
7999     if ( iFun > -1 )
8000     {
8001       continue; // look for a better function
8002     }
8003
8004     if ( !findBest )
8005       break;
8006
8007   } // loop on smoothing functions
8008
8009   if ( moved ) // notify _neibors
8010   {
8011     Set( SMOOTHED );
8012     for ( size_t i = 0; i < _neibors.size(); ++i )
8013       if ( !_neibors[i]->Is( MOVED ))
8014       {
8015         _neibors[i]->Set( MOVED );
8016         toSmooth.push_back( _neibors[i] );
8017       }
8018   }
8019
8020   return nbBad;
8021 }
8022
8023 //================================================================================
8024 /*!
8025  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8026  *  \retval int - nb of bad simplices around this _LayerEdge
8027  */
8028 //================================================================================
8029
8030 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8031 {
8032   if ( !_smooFunction )
8033     return 0; // _LayerEdge inflated along EDGE or FACE
8034   if ( Is( BLOCKED ))
8035     return 0; // not inflated
8036
8037   const gp_XYZ& curPos  = _pos.back();
8038   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8039
8040   // quality metrics (orientation) of tetras around _tgtNode
8041   int nbOkBefore = 0;
8042   double vol, minVolBefore = 1e100;
8043   for ( size_t i = 0; i < _simplices.size(); ++i )
8044   {
8045     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8046     minVolBefore = Min( minVolBefore, vol );
8047   }
8048   int nbBad = _simplices.size() - nbOkBefore;
8049
8050   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8051   {
8052     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8053       _smooFunction = _funs[ FUN_LAPLACIAN ];
8054     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8055       _smooFunction = _funs[ FUN_CENTROIDAL ];
8056   }
8057
8058   // compute new position for the last _pos using different _funs
8059   gp_XYZ newPos;
8060   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8061   {
8062     if ( iFun < 0 )
8063       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8064     else if ( _funs[ iFun ] == _smooFunction )
8065       continue; // _smooFunction again
8066     else if ( step > 1 )
8067       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8068     else
8069       break; // let "easy" functions improve elements around distorted ones
8070
8071     if ( _curvature )
8072     {
8073       double delta  = _curvature->lenDelta( _len );
8074       if ( delta > 0 )
8075         newPos += _normal * delta;
8076       else
8077       {
8078         double segLen = _normal * ( newPos - prevPos );
8079         if ( segLen + delta > 0 )
8080           newPos += _normal * delta;
8081       }
8082       // double segLenChange = _normal * ( curPos - newPos );
8083       // newPos += 0.5 * _normal * segLenChange;
8084     }
8085
8086     int nbOkAfter = 0;
8087     double minVolAfter = 1e100;
8088     for ( size_t i = 0; i < _simplices.size(); ++i )
8089     {
8090       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8091       minVolAfter = Min( minVolAfter, vol );
8092     }
8093     // get worse?
8094     if ( nbOkAfter < nbOkBefore )
8095       continue;
8096     if (( isConcaveFace || findBest ) &&
8097         ( nbOkAfter == nbOkBefore ) &&
8098         ( minVolAfter <= minVolBefore )
8099         )
8100       continue;
8101
8102     nbBad        = _simplices.size() - nbOkAfter;
8103     minVolBefore = minVolAfter;
8104     nbOkBefore   = nbOkAfter;
8105
8106     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8107     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8108     _pos.back() = newPos;
8109
8110     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8111                   << ( nbBad ? "--BAD" : ""));
8112
8113     // commented for IPAL0052478
8114     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8115     // _len += prevPos.Distance(newPos);
8116
8117     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8118     {
8119       //_smooFunction = _funs[ iFun ];
8120       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8121       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8122       // << " minVol: " << minVolAfter
8123       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8124       // << endl;
8125       continue; // look for a better function
8126     }
8127
8128     if ( !findBest )
8129       break;
8130
8131   } // loop on smoothing functions
8132
8133   return nbBad;
8134 }
8135
8136 //================================================================================
8137 /*!
8138  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8139  *        For a correct result, _simplices must contain nodes lying on geometry.
8140  */
8141 //================================================================================
8142
8143 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8144                                      const TNode2Edge&     n2eMap)
8145 {
8146   if ( _smooFunction ) return;
8147
8148   // use smoothNefPolygon() near concaveVertices
8149   if ( !concaveVertices.empty() )
8150   {
8151     _smooFunction = _funs[ FUN_CENTROIDAL ];
8152
8153     Set( ON_CONCAVE_FACE );
8154
8155     for ( size_t i = 0; i < _simplices.size(); ++i )
8156     {
8157       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8158       {
8159         _smooFunction = _funs[ FUN_NEFPOLY ];
8160
8161         // set FUN_CENTROIDAL to neighbor edges
8162         for ( i = 0; i < _neibors.size(); ++i )
8163         {
8164           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8165           {
8166             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8167           }
8168         }
8169         return;
8170       }
8171     }
8172
8173     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8174     // // where the nodes are smoothed too far along a sphere thus creating
8175     // // inverted _simplices
8176     // double dist[theNbSmooFuns];
8177     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8178     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8179
8180     // double minDist = Precision::Infinite();
8181     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8182     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8183     // {
8184     //   gp_Pnt newP = (this->*_funs[i])();
8185     //   dist[i] = p.SquareDistance( newP );
8186     //   if ( dist[i]*coef[i] < minDist )
8187     //   {
8188     //     _smooFunction = _funs[i];
8189     //     minDist = dist[i]*coef[i];
8190     //   }
8191     // }
8192   }
8193   else
8194   {
8195     _smooFunction = _funs[ FUN_LAPLACIAN ];
8196   }
8197   // int minDim = 3;
8198   // for ( size_t i = 0; i < _simplices.size(); ++i )
8199   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8200   // if ( minDim == 0 )
8201   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8202   // else if ( minDim == 1 )
8203   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8204
8205
8206   // int iMin;
8207   // for ( int i = 0; i < FUN_NB; ++i )
8208   // {
8209   //   //cout << dist[i] << " ";
8210   //   if ( _smooFunction == _funs[i] ) {
8211   //     iMin = i;
8212   //     //debugMsg( fNames[i] );
8213   //     break;
8214   //   }
8215   // }
8216   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8217 }
8218
8219 //================================================================================
8220 /*!
8221  * \brief Returns a name of _SmooFunction
8222  */
8223 //================================================================================
8224
8225 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8226 {
8227   if ( !fun )
8228     fun = _smooFunction;
8229   for ( int i = 0; i < theNbSmooFuns; ++i )
8230     if ( fun == _funs[i] )
8231       return i;
8232
8233   return theNbSmooFuns;
8234 }
8235
8236 //================================================================================
8237 /*!
8238  * \brief Computes a new node position using Laplacian smoothing
8239  */
8240 //================================================================================
8241
8242 gp_XYZ _LayerEdge::smoothLaplacian()
8243 {
8244   gp_XYZ newPos (0,0,0);
8245   for ( size_t i = 0; i < _simplices.size(); ++i )
8246     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8247   newPos /= _simplices.size();
8248
8249   return newPos;
8250 }
8251
8252 //================================================================================
8253 /*!
8254  * \brief Computes a new node position using angular-based smoothing
8255  */
8256 //================================================================================
8257
8258 gp_XYZ _LayerEdge::smoothAngular()
8259 {
8260   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8261   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8262   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8263
8264   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8265   gp_XYZ pN( 0,0,0 );
8266   for ( size_t i = 0; i < _simplices.size(); ++i )
8267   {
8268     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8269     edgeDir.push_back( p - pPrev );
8270     edgeSize.push_back( edgeDir.back().Magnitude() );
8271     if ( edgeSize.back() < numeric_limits<double>::min() )
8272     {
8273       edgeDir.pop_back();
8274       edgeSize.pop_back();
8275     }
8276     else
8277     {
8278       edgeDir.back() /= edgeSize.back();
8279       points.push_back( p );
8280       pN += p;
8281     }
8282     pPrev = p;
8283   }
8284   edgeDir.push_back ( edgeDir[0] );
8285   edgeSize.push_back( edgeSize[0] );
8286   pN /= points.size();
8287
8288   gp_XYZ newPos(0,0,0);
8289   double sumSize = 0;
8290   for ( size_t i = 0; i < points.size(); ++i )
8291   {
8292     gp_Vec toN    = pN - points[i];
8293     double toNLen = toN.Magnitude();
8294     if ( toNLen < numeric_limits<double>::min() )
8295     {
8296       newPos += pN;
8297       continue;
8298     }
8299     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8300     double bisecLen = bisec.SquareMagnitude();
8301     if ( bisecLen < numeric_limits<double>::min() )
8302     {
8303       gp_Vec norm = edgeDir[i] ^ toN;
8304       bisec = norm ^ edgeDir[i];
8305       bisecLen = bisec.SquareMagnitude();
8306     }
8307     bisecLen = Sqrt( bisecLen );
8308     bisec /= bisecLen;
8309
8310 #if 1
8311     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8312     sumSize += bisecLen;
8313 #else
8314     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8315     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8316 #endif
8317     newPos += pNew;
8318   }
8319   newPos /= sumSize;
8320
8321   // project newPos to an average plane
8322
8323   gp_XYZ norm(0,0,0); // plane normal
8324   points.push_back( points[0] );
8325   for ( size_t i = 1; i < points.size(); ++i )
8326   {
8327     gp_XYZ vec1 = points[ i-1 ] - pN;
8328     gp_XYZ vec2 = points[ i   ] - pN;
8329     gp_XYZ cross = vec1 ^ vec2;
8330     try {
8331       cross.Normalize();
8332       if ( cross * norm < numeric_limits<double>::min() )
8333         norm += cross.Reversed();
8334       else
8335         norm += cross;
8336     }
8337     catch (Standard_Failure) { // if |cross| == 0.
8338     }
8339   }
8340   gp_XYZ vec = newPos - pN;
8341   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8342   newPos     = newPos - r * norm;
8343
8344   return newPos;
8345 }
8346
8347 //================================================================================
8348 /*!
8349  * \brief Computes a new node position using weigthed node positions
8350  */
8351 //================================================================================
8352
8353 gp_XYZ _LayerEdge::smoothLengthWeighted()
8354 {
8355   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8356   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8357
8358   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8359   for ( size_t i = 0; i < _simplices.size(); ++i )
8360   {
8361     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8362     edgeSize.push_back( ( p - pPrev ).Modulus() );
8363     if ( edgeSize.back() < numeric_limits<double>::min() )
8364     {
8365       edgeSize.pop_back();
8366     }
8367     else
8368     {
8369       points.push_back( p );
8370     }
8371     pPrev = p;
8372   }
8373   edgeSize.push_back( edgeSize[0] );
8374
8375   gp_XYZ newPos(0,0,0);
8376   double sumSize = 0;
8377   for ( size_t i = 0; i < points.size(); ++i )
8378   {
8379     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8380     sumSize += edgeSize[i] + edgeSize[i+1];
8381   }
8382   newPos /= sumSize;
8383   return newPos;
8384 }
8385
8386 //================================================================================
8387 /*!
8388  * \brief Computes a new node position using angular-based smoothing
8389  */
8390 //================================================================================
8391
8392 gp_XYZ _LayerEdge::smoothCentroidal()
8393 {
8394   gp_XYZ newPos(0,0,0);
8395   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8396   double sumSize = 0;
8397   for ( size_t i = 0; i < _simplices.size(); ++i )
8398   {
8399     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8400     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8401     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8402     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8403
8404     sumSize += size;
8405     newPos += gc * size;
8406   }
8407   newPos /= sumSize;
8408
8409   return newPos;
8410 }
8411
8412 //================================================================================
8413 /*!
8414  * \brief Computes a new node position located inside a Nef polygon
8415  */
8416 //================================================================================
8417
8418 gp_XYZ _LayerEdge::smoothNefPolygon()
8419 #ifdef OLD_NEF_POLYGON
8420 {
8421   gp_XYZ newPos(0,0,0);
8422
8423   // get a plane to seach a solution on
8424
8425   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8426   size_t i;
8427   const double tol = numeric_limits<double>::min();
8428   gp_XYZ center(0,0,0);
8429   for ( i = 0; i < _simplices.size(); ++i )
8430   {
8431     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8432                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8433     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8434   }
8435   vecs.back() = vecs[0];
8436   center /= _simplices.size();
8437
8438   gp_XYZ zAxis(0,0,0);
8439   for ( i = 0; i < _simplices.size(); ++i )
8440     zAxis += vecs[i] ^ vecs[i+1];
8441
8442   gp_XYZ yAxis;
8443   for ( i = 0; i < _simplices.size(); ++i )
8444   {
8445     yAxis = vecs[i];
8446     if ( yAxis.SquareModulus() > tol )
8447       break;
8448   }
8449   gp_XYZ xAxis = yAxis ^ zAxis;
8450   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8451   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8452   //                             p0.Distance( _simplices[2]._nPrev ));
8453   // gp_XYZ center = smoothLaplacian();
8454   // gp_XYZ xAxis, yAxis, zAxis;
8455   // for ( i = 0; i < _simplices.size(); ++i )
8456   // {
8457   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8458   //   if ( xAxis.SquareModulus() > tol*tol )
8459   //     break;
8460   // }
8461   // for ( i = 1; i < _simplices.size(); ++i )
8462   // {
8463   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8464   //   zAxis = xAxis ^ yAxis;
8465   //   if ( zAxis.SquareModulus() > tol*tol )
8466   //     break;
8467   // }
8468   // if ( i == _simplices.size() ) return newPos;
8469
8470   yAxis = zAxis ^ xAxis;
8471   xAxis /= xAxis.Modulus();
8472   yAxis /= yAxis.Modulus();
8473
8474   // get half-planes of _simplices
8475
8476   vector< _halfPlane > halfPlns( _simplices.size() );
8477   int nbHP = 0;
8478   for ( size_t i = 0; i < _simplices.size(); ++i )
8479   {
8480     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8481     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8482     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8483     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8484     gp_XY  vec12 = p2 - p1;
8485     double dist12 = vec12.Modulus();
8486     if ( dist12 < tol )
8487       continue;
8488     vec12 /= dist12;
8489     halfPlns[ nbHP ]._pos = p1;
8490     halfPlns[ nbHP ]._dir = vec12;
8491     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8492     ++nbHP;
8493   }
8494
8495   // intersect boundaries of half-planes, define state of intersection points
8496   // in relation to all half-planes and calculate internal point of a 2D polygon
8497
8498   double sumLen = 0;
8499   gp_XY newPos2D (0,0);
8500
8501   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8502   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8503   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8504
8505   vector< vector< TIntPntState > > allIntPnts( nbHP );
8506   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8507   {
8508     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8509     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8510
8511     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8512     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8513
8514     int nbNotOut = 0;
8515     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8516
8517     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8518     {
8519       if ( iHP1 == iHP2 ) continue;
8520
8521       TIntPntState & ips1 = intPnts1[ iHP2 ];
8522       if ( ips1.second == UNDEF )
8523       {
8524         // find an intersection point of boundaries of iHP1 and iHP2
8525
8526         if ( iHP2 == iPrev ) // intersection with neighbors is known
8527           ips1.first = halfPlns[ iHP1 ]._pos;
8528         else if ( iHP2 == iNext )
8529           ips1.first = halfPlns[ iHP2 ]._pos;
8530         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8531           ips1.second = NO_INT;
8532
8533         // classify the found intersection point
8534         if ( ips1.second != NO_INT )
8535         {
8536           ips1.second = NOT_OUT;
8537           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8538             if ( i != iHP1 && i != iHP2 &&
8539                  halfPlns[ i ].IsOut( ips1.first, tol ))
8540               ips1.second = IS_OUT;
8541         }
8542         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8543         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8544         TIntPntState & ips2 = intPnts2[ iHP1 ];
8545         ips2 = ips1;
8546       }
8547       if ( ips1.second == NOT_OUT )
8548       {
8549         ++nbNotOut;
8550         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8551       }
8552     }
8553
8554     // find a NOT_OUT segment of boundary which is located between
8555     // two NOT_OUT int points
8556
8557     if ( nbNotOut < 2 )
8558       continue; // no such a segment
8559
8560     if ( nbNotOut > 2 )
8561     {
8562       // sort points along the boundary
8563       map< double, TIntPntState* > ipsByParam;
8564       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8565       {
8566         TIntPntState & ips1 = intPnts1[ iHP2 ];
8567         if ( ips1.second != NO_INT )
8568         {
8569           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8570           double param = op * halfPlns[ iHP1 ]._dir;
8571           ipsByParam.insert( make_pair( param, & ips1 ));
8572         }
8573       }
8574       // look for two neighboring NOT_OUT points
8575       nbNotOut = 0;
8576       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8577       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8578       {
8579         TIntPntState & ips1 = *(u2ips->second);
8580         if ( ips1.second == NOT_OUT )
8581           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8582         else if ( nbNotOut >= 2 )
8583           break;
8584         else
8585           nbNotOut = 0;
8586       }
8587     }
8588
8589     if ( nbNotOut >= 2 )
8590     {
8591       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8592       sumLen += len;
8593
8594       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8595     }
8596   }
8597
8598   if ( sumLen > 0 )
8599   {
8600     newPos2D /= sumLen;
8601     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8602   }
8603   else
8604   {
8605     newPos = center;
8606   }
8607
8608   return newPos;
8609 }
8610 #else // OLD_NEF_POLYGON
8611 { ////////////////////////////////// NEW
8612   gp_XYZ newPos(0,0,0);
8613
8614   // get a plane to seach a solution on
8615
8616   size_t i;
8617   gp_XYZ center(0,0,0);
8618   for ( i = 0; i < _simplices.size(); ++i )
8619     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8620   center /= _simplices.size();
8621
8622   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8623   for ( i = 0; i < _simplices.size(); ++i )
8624     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8625   vecs.back() = vecs[0];
8626
8627   const double tol = numeric_limits<double>::min();
8628   gp_XYZ zAxis(0,0,0);
8629   for ( i = 0; i < _simplices.size(); ++i )
8630   {
8631     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8632     try {
8633       cross.Normalize();
8634       if ( cross * zAxis < tol )
8635         zAxis += cross.Reversed();
8636       else
8637         zAxis += cross;
8638     }
8639     catch (Standard_Failure) { // if |cross| == 0.
8640     }
8641   }
8642
8643   gp_XYZ yAxis;
8644   for ( i = 0; i < _simplices.size(); ++i )
8645   {
8646     yAxis = vecs[i];
8647     if ( yAxis.SquareModulus() > tol )
8648       break;
8649   }
8650   gp_XYZ xAxis = yAxis ^ zAxis;
8651   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8652   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8653   //                             p0.Distance( _simplices[2]._nPrev ));
8654   // gp_XYZ center = smoothLaplacian();
8655   // gp_XYZ xAxis, yAxis, zAxis;
8656   // for ( i = 0; i < _simplices.size(); ++i )
8657   // {
8658   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8659   //   if ( xAxis.SquareModulus() > tol*tol )
8660   //     break;
8661   // }
8662   // for ( i = 1; i < _simplices.size(); ++i )
8663   // {
8664   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8665   //   zAxis = xAxis ^ yAxis;
8666   //   if ( zAxis.SquareModulus() > tol*tol )
8667   //     break;
8668   // }
8669   // if ( i == _simplices.size() ) return newPos;
8670
8671   yAxis = zAxis ^ xAxis;
8672   xAxis /= xAxis.Modulus();
8673   yAxis /= yAxis.Modulus();
8674
8675   // get half-planes of _simplices
8676
8677   vector< _halfPlane > halfPlns( _simplices.size() );
8678   int nbHP = 0;
8679   for ( size_t i = 0; i < _simplices.size(); ++i )
8680   {
8681     const gp_XYZ& OP1 = vecs[ i   ];
8682     const gp_XYZ& OP2 = vecs[ i+1 ];
8683     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8684     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8685     gp_XY  vec12 = p2 - p1;
8686     double dist12 = vec12.Modulus();
8687     if ( dist12 < tol )
8688       continue;
8689     vec12 /= dist12;
8690     halfPlns[ nbHP ]._pos = p1;
8691     halfPlns[ nbHP ]._dir = vec12;
8692     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8693     ++nbHP;
8694   }
8695
8696   // intersect boundaries of half-planes, define state of intersection points
8697   // in relation to all half-planes and calculate internal point of a 2D polygon
8698
8699   double sumLen = 0;
8700   gp_XY newPos2D (0,0);
8701
8702   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8703   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8704   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8705
8706   vector< vector< TIntPntState > > allIntPnts( nbHP );
8707   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8708   {
8709     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8710     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8711
8712     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8713     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8714
8715     int nbNotOut = 0;
8716     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8717
8718     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8719     {
8720       if ( iHP1 == iHP2 ) continue;
8721
8722       TIntPntState & ips1 = intPnts1[ iHP2 ];
8723       if ( ips1.second == UNDEF )
8724       {
8725         // find an intersection point of boundaries of iHP1 and iHP2
8726
8727         if ( iHP2 == iPrev ) // intersection with neighbors is known
8728           ips1.first = halfPlns[ iHP1 ]._pos;
8729         else if ( iHP2 == iNext )
8730           ips1.first = halfPlns[ iHP2 ]._pos;
8731         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8732           ips1.second = NO_INT;
8733
8734         // classify the found intersection point
8735         if ( ips1.second != NO_INT )
8736         {
8737           ips1.second = NOT_OUT;
8738           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8739             if ( i != iHP1 && i != iHP2 &&
8740                  halfPlns[ i ].IsOut( ips1.first, tol ))
8741               ips1.second = IS_OUT;
8742         }
8743         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8744         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8745         TIntPntState & ips2 = intPnts2[ iHP1 ];
8746         ips2 = ips1;
8747       }
8748       if ( ips1.second == NOT_OUT )
8749       {
8750         ++nbNotOut;
8751         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8752       }
8753     }
8754
8755     // find a NOT_OUT segment of boundary which is located between
8756     // two NOT_OUT int points
8757
8758     if ( nbNotOut < 2 )
8759       continue; // no such a segment
8760
8761     if ( nbNotOut > 2 )
8762     {
8763       // sort points along the boundary
8764       map< double, TIntPntState* > ipsByParam;
8765       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8766       {
8767         TIntPntState & ips1 = intPnts1[ iHP2 ];
8768         if ( ips1.second != NO_INT )
8769         {
8770           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8771           double param = op * halfPlns[ iHP1 ]._dir;
8772           ipsByParam.insert( make_pair( param, & ips1 ));
8773         }
8774       }
8775       // look for two neighboring NOT_OUT points
8776       nbNotOut = 0;
8777       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8778       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8779       {
8780         TIntPntState & ips1 = *(u2ips->second);
8781         if ( ips1.second == NOT_OUT )
8782           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8783         else if ( nbNotOut >= 2 )
8784           break;
8785         else
8786           nbNotOut = 0;
8787       }
8788     }
8789
8790     if ( nbNotOut >= 2 )
8791     {
8792       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8793       sumLen += len;
8794
8795       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8796     }
8797   }
8798
8799   if ( sumLen > 0 )
8800   {
8801     newPos2D /= sumLen;
8802     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8803   }
8804   else
8805   {
8806     newPos = center;
8807   }
8808
8809   return newPos;
8810 }
8811 #endif // OLD_NEF_POLYGON
8812
8813 //================================================================================
8814 /*!
8815  * \brief Add a new segment to _LayerEdge during inflation
8816  */
8817 //================================================================================
8818
8819 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8820 {
8821   if ( Is( BLOCKED ))
8822     return;
8823
8824   if ( len > _maxLen )
8825   {
8826     len = _maxLen;
8827     Block( eos.GetData() );
8828   }
8829   const double lenDelta = len - _len;
8830   if ( lenDelta < len * 1e-3  )
8831   {
8832     Block( eos.GetData() );
8833     return;
8834   }
8835
8836   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8837   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8838   gp_XYZ newXYZ;
8839   if ( eos._hyp.IsOffsetMethod() )
8840   {
8841     newXYZ = oldXYZ;
8842     gp_Vec faceNorm;
8843     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8844     while ( faceIt->more() )
8845     {
8846       const SMDS_MeshElement* face = faceIt->next();
8847       if ( !eos.GetNormal( face, faceNorm ))
8848         continue;
8849
8850       // translate plane of a face
8851       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8852
8853       // find point of intersection of the face plane located at baryCenter
8854       // and _normal located at newXYZ
8855       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8856       double dot =  ( faceNorm.XYZ() * _normal );
8857       if ( dot < std::numeric_limits<double>::min() )
8858         dot = lenDelta * 1e-3;
8859       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8860       newXYZ += step * _normal;
8861     }
8862     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8863   }
8864   else
8865   {
8866     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8867   }
8868
8869   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8870   _pos.push_back( newXYZ );
8871
8872   if ( !eos._sWOL.IsNull() )
8873   {
8874     double distXYZ[4];
8875     bool uvOK = false;
8876     if ( eos.SWOLType() == TopAbs_EDGE )
8877     {
8878       double u = Precision::Infinite(); // to force projection w/o distance check
8879       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8880                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8881       _pos.back().SetCoord( u, 0, 0 );
8882       if ( _nodes.size() > 1 && uvOK )
8883       {
8884         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8885         pos->SetUParameter( u );
8886       }
8887     }
8888     else //  TopAbs_FACE
8889     {
8890       gp_XY uv( Precision::Infinite(), 0 );
8891       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8892                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8893       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8894       if ( _nodes.size() > 1 && uvOK )
8895       {
8896         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8897         pos->SetUParameter( uv.X() );
8898         pos->SetVParameter( uv.Y() );
8899       }
8900     }
8901     if ( uvOK )
8902     {
8903       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8904     }
8905     else
8906     {
8907       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8908       _pos.pop_back();
8909       Block( eos.GetData() );
8910       return;
8911     }
8912   }
8913
8914   _len = len;
8915
8916   // notify _neibors
8917   if ( eos.ShapeType() != TopAbs_FACE )
8918   {
8919     for ( size_t i = 0; i < _neibors.size(); ++i )
8920       //if (  _len > _neibors[i]->GetSmooLen() )
8921         _neibors[i]->Set( MOVED );
8922
8923     Set( MOVED );
8924   }
8925   dumpMove( n ); //debug
8926 }
8927
8928 //================================================================================
8929 /*!
8930  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8931  */
8932 //================================================================================
8933
8934 void _LayerEdge::Block( _SolidData& data )
8935 {
8936   //if ( Is( BLOCKED )) return;
8937   Set( BLOCKED );
8938
8939   _maxLen = _len;
8940   std::queue<_LayerEdge*> queue;
8941   queue.push( this );
8942
8943   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8944   while ( !queue.empty() )
8945   {
8946     _LayerEdge* edge = queue.front(); queue.pop();
8947     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8948     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8949     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8950     {
8951       _LayerEdge* neibor = edge->_neibors[iN];
8952       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
8953         continue;
8954       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8955       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8956       double minDist = pSrc.SquareDistance( pSrcN );
8957       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
8958       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
8959       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
8960       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8961       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
8962       {
8963         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
8964       }
8965       if ( neibor->_maxLen > newMaxLen )
8966       {
8967         neibor->_maxLen = newMaxLen;
8968         if ( neibor->_maxLen < neibor->_len )
8969         {
8970           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8971           while ( neibor->_len > neibor->_maxLen &&
8972                   neibor->NbSteps() > 1 )
8973             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8974           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8975           //neibor->Block( data );
8976         }
8977         queue.push( neibor );
8978       }
8979     }
8980   }
8981 }
8982
8983 //================================================================================
8984 /*!
8985  * \brief Remove last inflation step
8986  */
8987 //================================================================================
8988
8989 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
8990 {
8991   if ( _pos.size() > curStep && _nodes.size() > 1 )
8992   {
8993     _pos.resize( curStep );
8994
8995     gp_Pnt      nXYZ = _pos.back();
8996     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8997     SMESH_TNodeXYZ curXYZ( n );
8998     if ( !eos._sWOL.IsNull() )
8999     {
9000       TopLoc_Location loc;
9001       if ( eos.SWOLType() == TopAbs_EDGE )
9002       {
9003         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9004         pos->SetUParameter( nXYZ.X() );
9005         double f,l;
9006         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9007         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9008       }
9009       else
9010       {
9011         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9012         pos->SetUParameter( nXYZ.X() );
9013         pos->SetVParameter( nXYZ.Y() );
9014         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9015         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9016       }
9017     }
9018     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9019     dumpMove( n );
9020
9021     if ( restoreLength )
9022     {
9023       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9024     }
9025   }
9026 }
9027
9028 //================================================================================
9029 /*!
9030  * \brief Return index of a _pos distant from _normal
9031  */
9032 //================================================================================
9033
9034 int _LayerEdge::GetSmoothedPos( const double tol )
9035 {
9036   int iSmoothed = 0;
9037   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9038   {
9039     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9040     if ( normDist > tol * tol )
9041       iSmoothed = i;
9042   }
9043   return iSmoothed;
9044 }
9045
9046 //================================================================================
9047 /*!
9048  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9049  */
9050 //================================================================================
9051
9052 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9053 {
9054   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9055     return;
9056
9057   // find the 1st smoothed _pos
9058   int iSmoothed = GetSmoothedPos( tol );
9059   if ( !iSmoothed ) return;
9060
9061   //if ( 1 || Is( DISTORTED ))
9062   {
9063     gp_XYZ normal = _normal;
9064     if ( Is( NORMAL_UPDATED ))
9065       for ( size_t i = 1; i < _pos.size(); ++i )
9066       {
9067         normal = _pos[i] - _pos[0];
9068         double size = normal.Modulus();
9069         if ( size > RealSmall() )
9070         {
9071           normal /= size;
9072           break;
9073         }
9074       }
9075     const double r = 0.2;
9076     for ( int iter = 0; iter < 50; ++iter )
9077     {
9078       double minDot = 1;
9079       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9080       {
9081         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9082         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9083         _pos[i] = newPos;
9084         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9085         double newLen = ( 1-r ) * midLen + r * segLen[i];
9086         const_cast< double& >( segLen[i] ) = newLen;
9087         // check angle between normal and (_pos[i+1], _pos[i] )
9088         gp_XYZ posDir = _pos[i+1] - _pos[i];
9089         double size   = posDir.SquareModulus();
9090         if ( size > RealSmall() )
9091           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9092       }
9093       if ( minDot > 0.5 * 0.5 )
9094         break;
9095     }
9096   }
9097   // else
9098   // {
9099   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9100   //   {
9101   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9102   //       continue;
9103
9104   //     double     wgt = segLen[i] / segLen.back();
9105   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9106   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9107   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9108   //     _pos[i] = newPos;
9109   //   }
9110   // }
9111 }
9112
9113 //================================================================================
9114 /*!
9115  * \brief Create layers of prisms
9116  */
9117 //================================================================================
9118
9119 bool _ViscousBuilder::refine(_SolidData& data)
9120 {
9121   SMESH_MesherHelper& helper = data.GetHelper();
9122   helper.SetElementsOnShape(false);
9123
9124   Handle(Geom_Curve) curve;
9125   Handle(ShapeAnalysis_Surface) surface;
9126   TopoDS_Edge geomEdge;
9127   TopoDS_Face geomFace;
9128   TopLoc_Location loc;
9129   double f,l, u = 0;
9130   gp_XY uv;
9131   vector< gp_XYZ > pos3D;
9132   bool isOnEdge;
9133   TGeomID prevBaseId = -1;
9134   TNode2Edge* n2eMap = 0;
9135   TNode2Edge::iterator n2e;
9136
9137   // Create intermediate nodes on each _LayerEdge
9138
9139   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9140   {
9141     _EdgesOnShape& eos = data._edgesOnShape[iS];
9142     if ( eos._edges.empty() ) continue;
9143
9144     if ( eos._edges[0]->_nodes.size() < 2 )
9145       continue; // on _noShrinkShapes
9146
9147     // get data of a shrink shape
9148     isOnEdge = false;
9149     geomEdge.Nullify(); geomFace.Nullify();
9150     curve.Nullify(); surface.Nullify();
9151     if ( !eos._sWOL.IsNull() )
9152     {
9153       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9154       if ( isOnEdge )
9155       {
9156         geomEdge = TopoDS::Edge( eos._sWOL );
9157         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9158       }
9159       else
9160       {
9161         geomFace = TopoDS::Face( eos._sWOL );
9162         surface  = helper.GetSurface( geomFace );
9163       }
9164     }
9165     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9166     {
9167       geomFace = TopoDS::Face( eos._shape );
9168       surface  = helper.GetSurface( geomFace );
9169       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9170       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9171       {
9172         eos._eosC1[ i ]->_toSmooth = true;
9173         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9174           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9175       }
9176     }
9177
9178     vector< double > segLen;
9179     for ( size_t i = 0; i < eos._edges.size(); ++i )
9180     {
9181       _LayerEdge& edge = *eos._edges[i];
9182       if ( edge._pos.size() < 2 )
9183         continue;
9184
9185       // get accumulated length of segments
9186       segLen.resize( edge._pos.size() );
9187       segLen[0] = 0.0;
9188       if ( eos._sWOL.IsNull() )
9189       {
9190         bool useNormal = true;
9191         bool   usePos  = false;
9192         bool smoothed  = false;
9193         double   preci = 0.1 * edge._len;
9194         if ( eos._toSmooth && edge._pos.size() > 2 )
9195         {
9196           smoothed = edge.GetSmoothedPos( preci );
9197         }
9198         if ( smoothed )
9199         {
9200           if ( !surface.IsNull() &&
9201                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9202           {
9203             useNormal = usePos = false;
9204             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9205             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9206             {
9207               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9208               if ( surface->Gap() < 2. * edge._len )
9209                 segLen[j] = surface->Gap();
9210               else
9211                 useNormal = true;
9212             }
9213           }
9214         }
9215         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9216         {
9217 #ifndef __NODES_AT_POS
9218           useNormal = usePos = false;
9219           edge._pos[1] = edge._pos.back();
9220           edge._pos.resize( 2 );
9221           segLen.resize( 2 );
9222           segLen[ 1 ] = edge._len;
9223 #endif
9224         }
9225         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9226         {
9227           useNormal = usePos = false;
9228           _LayerEdge tmpEdge; // get original _normal
9229           tmpEdge._nodes.push_back( edge._nodes[0] );
9230           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9231             usePos = true;
9232           else
9233             for ( size_t j = 1; j < edge._pos.size(); ++j )
9234               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9235         }
9236         if ( useNormal )
9237         {
9238           for ( size_t j = 1; j < edge._pos.size(); ++j )
9239             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9240         }
9241         if ( usePos )
9242         {
9243           for ( size_t j = 1; j < edge._pos.size(); ++j )
9244             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9245         }
9246         else
9247         {
9248           bool swapped = ( edge._pos.size() > 2 );
9249           while ( swapped )
9250           {
9251             swapped = false;
9252             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9253               if ( segLen[j] > segLen.back() )
9254               {
9255                 segLen.erase( segLen.begin() + j );
9256                 edge._pos.erase( edge._pos.begin() + j );
9257                 --j;
9258               }
9259               else if ( segLen[j] < segLen[j-1] )
9260               {
9261                 std::swap( segLen[j], segLen[j-1] );
9262                 std::swap( edge._pos[j], edge._pos[j-1] );
9263                 swapped = true;
9264               }
9265           }
9266         }
9267         // smooth a path formed by edge._pos
9268 #ifndef __NODES_AT_POS
9269         if (( smoothed ) /*&&
9270             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9271           edge.SmoothPos( segLen, preci );
9272 #endif
9273       }
9274       else if ( eos._isRegularSWOL ) // usual SWOL
9275       {
9276         for ( size_t j = 1; j < edge._pos.size(); ++j )
9277           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9278       }
9279       else if ( !surface.IsNull() ) // SWOL surface with singularities
9280       {
9281         pos3D.resize( edge._pos.size() );
9282         for ( size_t j = 0; j < edge._pos.size(); ++j )
9283           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9284
9285         for ( size_t j = 1; j < edge._pos.size(); ++j )
9286           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9287       }
9288
9289       // allocate memory for new nodes if it is not yet refined
9290       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9291       if ( edge._nodes.size() == 2 )
9292       {
9293 #ifdef __NODES_AT_POS
9294         int nbNodes = edge._pos.size();
9295 #else
9296         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9297 #endif
9298         edge._nodes.resize( nbNodes, 0 );
9299         edge._nodes[1] = 0;
9300         edge._nodes.back() = tgtNode;
9301       }
9302       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9303       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9304       if ( baseShapeId != prevBaseId )
9305       {
9306         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9307         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9308         prevBaseId = baseShapeId;
9309       }
9310       _LayerEdge* edgeOnSameNode = 0;
9311       bool        useExistingPos = false;
9312       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9313       {
9314         edgeOnSameNode = n2e->second;
9315         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9316         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9317         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9318         if ( isOnEdge )
9319         {
9320           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9321           epos->SetUParameter( otherTgtPos.X() );
9322         }
9323         else
9324         {
9325           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9326           fpos->SetUParameter( otherTgtPos.X() );
9327           fpos->SetVParameter( otherTgtPos.Y() );
9328         }
9329       }
9330       // calculate height of the first layer
9331       double h0;
9332       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9333       const double f = eos._hyp.GetStretchFactor();
9334       const int    N = eos._hyp.GetNumberLayers();
9335       const double fPowN = pow( f, N );
9336       if ( fPowN - 1 <= numeric_limits<double>::min() )
9337         h0 = T / N;
9338       else
9339         h0 = T * ( f - 1 )/( fPowN - 1 );
9340
9341       const double zeroLen = std::numeric_limits<double>::min();
9342
9343       // create intermediate nodes
9344       double hSum = 0, hi = h0/f;
9345       size_t iSeg = 1;
9346       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9347       {
9348         // compute an intermediate position
9349         hi *= f;
9350         hSum += hi;
9351         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9352           ++iSeg;
9353         int iPrevSeg = iSeg-1;
9354         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9355           --iPrevSeg;
9356         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9357         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9358 #ifdef __NODES_AT_POS
9359         pos = edge._pos[ iStep ];
9360 #endif
9361         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9362         if ( !eos._sWOL.IsNull() )
9363         {
9364           // compute XYZ by parameters <pos>
9365           if ( isOnEdge )
9366           {
9367             u = pos.X();
9368             if ( !node )
9369               pos = curve->Value( u ).Transformed(loc);
9370           }
9371           else if ( eos._isRegularSWOL )
9372           {
9373             uv.SetCoord( pos.X(), pos.Y() );
9374             if ( !node )
9375               pos = surface->Value( pos.X(), pos.Y() );
9376           }
9377           else
9378           {
9379             uv.SetCoord( pos.X(), pos.Y() );
9380             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9381             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9382             if ( !node )
9383               pos = surface->Value( uv );
9384           }
9385         }
9386         // create or update the node
9387         if ( !node )
9388         {
9389           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9390           if ( !eos._sWOL.IsNull() )
9391           {
9392             if ( isOnEdge )
9393               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9394             else
9395               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9396           }
9397           else
9398           {
9399             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9400           }
9401         }
9402         else
9403         {
9404           if ( !eos._sWOL.IsNull() )
9405           {
9406             // make average pos from new and current parameters
9407             if ( isOnEdge )
9408             {
9409               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9410               if ( useExistingPos )
9411                 u = helper.GetNodeU( geomEdge, node );
9412               pos = curve->Value( u ).Transformed(loc);
9413
9414               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9415               epos->SetUParameter( u );
9416             }
9417             else
9418             {
9419               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9420               if ( useExistingPos )
9421                 uv = helper.GetNodeUV( geomFace, node );
9422               pos = surface->Value( uv );
9423
9424               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9425               fpos->SetUParameter( uv.X() );
9426               fpos->SetVParameter( uv.Y() );
9427             }
9428           }
9429           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9430         }
9431       } // loop on edge._nodes
9432
9433       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9434       {
9435         if ( isOnEdge )
9436           edge._pos.back().SetCoord( u, 0,0);
9437         else
9438           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9439
9440         if ( edgeOnSameNode )
9441           edgeOnSameNode->_pos.back() = edge._pos.back();
9442       }
9443
9444     } // loop on eos._edges to create nodes
9445
9446
9447     if ( !getMeshDS()->IsEmbeddedMode() )
9448       // Log node movement
9449       for ( size_t i = 0; i < eos._edges.size(); ++i )
9450       {
9451         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9452         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9453       }
9454   }
9455
9456
9457   // Create volumes
9458
9459   helper.SetElementsOnShape(true);
9460
9461   vector< vector<const SMDS_MeshNode*>* > nnVec;
9462   set< vector<const SMDS_MeshNode*>* >    nnSet;
9463   set< int >                       degenEdgeInd;
9464   vector<const SMDS_MeshElement*>     degenVols;
9465   vector<int>                       isRiskySWOL;
9466
9467   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9468   for ( ; exp.More(); exp.Next() )
9469   {
9470     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9471     if ( data._ignoreFaceIds.count( faceID ))
9472       continue;
9473     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9474     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9475     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9476     while ( fIt->more() )
9477     {
9478       const SMDS_MeshElement* face = fIt->next();
9479       const int            nbNodes = face->NbCornerNodes();
9480       nnVec.resize( nbNodes );
9481       nnSet.clear();
9482       degenEdgeInd.clear();
9483       isRiskySWOL.resize( nbNodes );
9484       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9485       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9486       for ( int iN = 0; iN < nbNodes; ++iN )
9487       {
9488         const SMDS_MeshNode* n = nIt->next();
9489         _LayerEdge*       edge = data._n2eMap[ n ];
9490         const int i = isReversedFace ? nbNodes-1-iN : iN;
9491         nnVec[ i ] = & edge->_nodes;
9492         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9493         minZ = std::min( minZ, nnVec[ i ]->size() );
9494         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9495
9496         if ( helper.HasDegeneratedEdges() )
9497           nnSet.insert( nnVec[ i ]);
9498       }
9499
9500       if ( maxZ == 0 )
9501         continue;
9502       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9503         continue;
9504
9505       switch ( nbNodes )
9506       {
9507       case 3: // TRIA
9508       {
9509         // PENTA
9510         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9511           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9512                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9513
9514         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9515         {
9516           for ( int iN = 0; iN < nbNodes; ++iN )
9517             if ( nnVec[ iN ]->size() < iZ+1 )
9518               degenEdgeInd.insert( iN );
9519
9520           if ( degenEdgeInd.size() == 1 )  // PYRAM
9521           {
9522             int i2 = *degenEdgeInd.begin();
9523             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9524             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9525             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9526                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9527           }
9528           else  // TETRA
9529           {
9530             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9531             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9532                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9533                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9534                               (*nnVec[ i3 ])[ iZ ]);
9535           }
9536         }
9537         break; // TRIA
9538       }
9539       case 4: // QUAD
9540       {
9541         // HEX
9542         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9543           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9544                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9545                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9546                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9547
9548         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9549         {
9550           for ( int iN = 0; iN < nbNodes; ++iN )
9551             if ( nnVec[ iN ]->size() < iZ+1 )
9552               degenEdgeInd.insert( iN );
9553
9554           switch ( degenEdgeInd.size() )
9555           {
9556           case 2: // PENTA
9557           {
9558             int i2 = *degenEdgeInd.begin();
9559             int i3 = *degenEdgeInd.rbegin();
9560             bool ok = ( i3 - i2 == 1 );
9561             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9562             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9563             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9564
9565             const SMDS_MeshElement* vol =
9566               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9567                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9568             if ( !ok && vol )
9569               degenVols.push_back( vol );
9570           }
9571           break;
9572
9573           default: // degen HEX
9574           {
9575             const SMDS_MeshElement* vol =
9576               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9577                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9578                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9579                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9580                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9581                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9582                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9583                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9584             degenVols.push_back( vol );
9585           }
9586           }
9587         }
9588         break; // HEX
9589       }
9590       default:
9591         return error("Not supported type of element", data._index);
9592
9593       } // switch ( nbNodes )
9594     } // while ( fIt->more() )
9595   } // loop on FACEs
9596
9597   if ( !degenVols.empty() )
9598   {
9599     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9600     if ( !err || err->IsOK() )
9601     {
9602       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9603                                          "Degenerated volumes created" ));
9604       err->myBadElements.insert( err->myBadElements.end(),
9605                                  degenVols.begin(),degenVols.end() );
9606     }
9607   }
9608
9609   return true;
9610 }
9611
9612 //================================================================================
9613 /*!
9614  * \brief Shrink 2D mesh on faces to let space for inflated layers
9615  */
9616 //================================================================================
9617
9618 bool _ViscousBuilder::shrink()
9619 {
9620   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9621   // inflated along FACE or EDGE)
9622   map< TGeomID, _SolidData* > f2sdMap;
9623   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9624   {
9625     _SolidData& data = _sdVec[i];
9626     TopTools_MapOfShape FFMap;
9627     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9628     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9629       if ( s2s->second.ShapeType() == TopAbs_FACE )
9630       {
9631         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9632
9633         if ( FFMap.Add( (*s2s).second ))
9634           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9635           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9636           // by StdMeshers_QuadToTriaAdaptor
9637           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9638           {
9639             SMESH_ProxyMesh::SubMesh* proxySub =
9640               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9641             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9642             while ( fIt->more() )
9643               proxySub->AddElement( fIt->next() );
9644             // as a result 3D algo will use elements from proxySub and not from smDS
9645           }
9646       }
9647   }
9648
9649   SMESH_MesherHelper helper( *_mesh );
9650   helper.ToFixNodeParameters( true );
9651
9652   // EDGE's to shrink
9653   map< TGeomID, _Shrinker1D > e2shrMap;
9654   vector< _EdgesOnShape* > subEOS;
9655   vector< _LayerEdge* > lEdges;
9656
9657   // loop on FACES to srink mesh on
9658   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9659   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9660   {
9661     _SolidData&      data = *f2sd->second;
9662     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9663     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9664     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9665
9666     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9667
9668     helper.SetSubShape(F);
9669
9670     // ===========================
9671     // Prepare data for shrinking
9672     // ===========================
9673
9674     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9675     // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9676     vector < const SMDS_MeshNode* > smoothNodes;
9677     {
9678       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9679       while ( nIt->more() )
9680       {
9681         const SMDS_MeshNode* n = nIt->next();
9682         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9683           smoothNodes.push_back( n );
9684       }
9685     }
9686     // Find out face orientation
9687     double refSign = 1;
9688     const set<TGeomID> ignoreShapes;
9689     bool isOkUV;
9690     if ( !smoothNodes.empty() )
9691     {
9692       vector<_Simplex> simplices;
9693       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9694       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9695       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9696       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9697       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9698         refSign = -1;
9699     }
9700
9701     // Find _LayerEdge's inflated along F
9702     subEOS.clear();
9703     lEdges.clear();
9704     {
9705       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9706                                                                 /*complexFirst=*/true); //!!!
9707       while ( subIt->more() )
9708       {
9709         const TGeomID subID = subIt->next()->GetId();
9710         if ( data._noShrinkShapes.count( subID ))
9711           continue;
9712         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9713         if ( !eos || eos->_sWOL.IsNull() ) continue;
9714
9715         subEOS.push_back( eos );
9716
9717         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9718         {
9719           lEdges.push_back( eos->_edges[ i ] );
9720           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9721         }
9722       }
9723     }
9724
9725     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9726     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9727     while ( fIt->more() )
9728       if ( const SMDS_MeshElement* f = fIt->next() )
9729         dumpChangeNodes( f );
9730     dumpFunctionEnd();
9731
9732     // Replace source nodes by target nodes in mesh faces to shrink
9733     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9734     const SMDS_MeshNode* nodes[20];
9735     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9736     {
9737       _EdgesOnShape& eos = * subEOS[ iS ];
9738       for ( size_t i = 0; i < eos._edges.size(); ++i )
9739       {
9740         _LayerEdge& edge = *eos._edges[i];
9741         const SMDS_MeshNode* srcNode = edge._nodes[0];
9742         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9743         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9744         while ( fIt->more() )
9745         {
9746           const SMDS_MeshElement* f = fIt->next();
9747           if ( !smDS->Contains( f ))
9748             continue;
9749           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9750           for ( int iN = 0; nIt->more(); ++iN )
9751           {
9752             const SMDS_MeshNode* n = nIt->next();
9753             nodes[iN] = ( n == srcNode ? tgtNode : n );
9754           }
9755           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9756           dumpChangeNodes( f );
9757         }
9758       }
9759     }
9760     dumpFunctionEnd();
9761
9762     // find out if a FACE is concave
9763     const bool isConcaveFace = isConcave( F, helper );
9764
9765     // Create _SmoothNode's on face F
9766     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9767     {
9768       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9769       const bool sortSimplices = isConcaveFace;
9770       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9771       {
9772         const SMDS_MeshNode* n = smoothNodes[i];
9773         nodesToSmooth[ i ]._node = n;
9774         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9775         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9776         // fix up incorrect uv of nodes on the FACE
9777         helper.GetNodeUV( F, n, 0, &isOkUV);
9778         dumpMove( n );
9779       }
9780       dumpFunctionEnd();
9781     }
9782     //if ( nodesToSmooth.empty() ) continue;
9783
9784     // Find EDGE's to shrink and set simpices to LayerEdge's
9785     set< _Shrinker1D* > eShri1D;
9786     {
9787       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9788       {
9789         _EdgesOnShape& eos = * subEOS[ iS ];
9790         if ( eos.SWOLType() == TopAbs_EDGE )
9791         {
9792           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9793           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9794           eShri1D.insert( & srinker );
9795           srinker.AddEdge( eos._edges[0], eos, helper );
9796           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9797           // restore params of nodes on EGDE if the EDGE has been already
9798           // srinked while srinking other FACE
9799           srinker.RestoreParams();
9800         }
9801         for ( size_t i = 0; i < eos._edges.size(); ++i )
9802         {
9803           _LayerEdge& edge = * eos._edges[i];
9804           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9805         }
9806       }
9807     }
9808
9809     bool toFixTria = false; // to improve quality of trias by diagonal swap
9810     if ( isConcaveFace )
9811     {
9812       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9813       if ( hasTria != hasQuad ) {
9814         toFixTria = hasTria;
9815       }
9816       else {
9817         set<int> nbNodesSet;
9818         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9819         while ( fIt->more() && nbNodesSet.size() < 2 )
9820           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9821         toFixTria = ( *nbNodesSet.begin() == 3 );
9822       }
9823     }
9824
9825     // ==================
9826     // Perform shrinking
9827     // ==================
9828
9829     bool shrinked = true;
9830     int nbBad, shriStep=0, smooStep=0;
9831     _SmoothNode::SmoothType smoothType
9832       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9833     SMESH_Comment errMsg;
9834     while ( shrinked )
9835     {
9836       shriStep++;
9837       // Move boundary nodes (actually just set new UV)
9838       // -----------------------------------------------
9839       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9840       shrinked = false;
9841       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9842       {
9843         _EdgesOnShape& eos = * subEOS[ iS ];
9844         for ( size_t i = 0; i < eos._edges.size(); ++i )
9845         {
9846           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9847         }
9848       }
9849       dumpFunctionEnd();
9850
9851       // Move nodes on EDGE's
9852       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9853       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9854       for ( ; shr != eShri1D.end(); ++shr )
9855         (*shr)->Compute( /*set3D=*/false, helper );
9856
9857       // Smoothing in 2D
9858       // -----------------
9859       int nbNoImpSteps = 0;
9860       bool       moved = true;
9861       nbBad = 1;
9862       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9863       {
9864         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9865
9866         int oldBadNb = nbBad;
9867         nbBad = 0;
9868         moved = false;
9869         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9870         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9871         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9872         {
9873           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9874                                             smooTy, /*set3D=*/isConcaveFace);
9875         }
9876         if ( nbBad < oldBadNb )
9877           nbNoImpSteps = 0;
9878         else
9879           nbNoImpSteps++;
9880
9881         dumpFunctionEnd();
9882       }
9883
9884       errMsg.clear();
9885       if ( nbBad > 0 )
9886         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9887       if ( shriStep > 200 )
9888         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9889       if ( !errMsg.empty() )
9890         break;
9891
9892       // Fix narrow triangles by swapping diagonals
9893       // ---------------------------------------
9894       if ( toFixTria )
9895       {
9896         set<const SMDS_MeshNode*> usedNodes;
9897         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9898
9899         // update working data
9900         set<const SMDS_MeshNode*>::iterator n;
9901         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9902         {
9903           n = usedNodes.find( nodesToSmooth[ i ]._node );
9904           if ( n != usedNodes.end())
9905           {
9906             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9907                                     nodesToSmooth[ i ]._simplices,
9908                                     ignoreShapes, NULL,
9909                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9910             usedNodes.erase( n );
9911           }
9912         }
9913         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9914         {
9915           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9916           if ( n != usedNodes.end())
9917           {
9918             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9919                                     lEdges[i]->_simplices,
9920                                     ignoreShapes );
9921             usedNodes.erase( n );
9922           }
9923         }
9924       }
9925       // TODO: check effect of this additional smooth
9926       // additional laplacian smooth to increase allowed shrink step
9927       // for ( int st = 1; st; --st )
9928       // {
9929       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9930       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9931       //   {
9932       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9933       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
9934       //   }
9935       // }
9936
9937     } // while ( shrinked )
9938
9939     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9940     {
9941       // remove faces
9942       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9943       {
9944         vector< const SMDS_MeshElement* > facesToRm;
9945         if ( psm )
9946         {
9947           facesToRm.reserve( psm->NbElements() );
9948           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9949             facesToRm.push_back( ite->next() );
9950
9951           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9952             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9953               psm->Clear();
9954         }
9955         for ( size_t i = 0; i < facesToRm.size(); ++i )
9956           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9957       }
9958       // remove nodes
9959       {
9960         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9961         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9962           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9963             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9964                                 subEOS[iS]->_edges[i]->_nodes.end() );
9965         }
9966         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9967         while ( itn->more() ) {
9968           const SMDS_MeshNode* n = itn->next();
9969           if ( !nodesToKeep.count( n ))
9970             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9971         }
9972       }
9973       // restore position and UV of target nodes
9974       gp_Pnt p;
9975       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9976         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9977         {
9978           _LayerEdge*       edge = subEOS[iS]->_edges[i];
9979           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9980           if ( edge->_pos.empty() ) continue;
9981           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9982           {
9983             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9984             pos->SetUParameter( edge->_pos[0].X() );
9985             pos->SetVParameter( edge->_pos[0].Y() );
9986             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
9987           }
9988           else
9989           {
9990             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9991             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
9992             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
9993           }
9994           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
9995           dumpMove( tgtNode );
9996         }
9997       // shrink EDGE sub-meshes and set proxy sub-meshes
9998       UVPtStructVec uvPtVec;
9999       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10000       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10001       {
10002         _Shrinker1D* shr = (*shrIt);
10003         shr->Compute( /*set3D=*/true, helper );
10004
10005         // set proxy mesh of EDGEs w/o layers
10006         map< double, const SMDS_MeshNode* > nodes;
10007         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10008         // remove refinement nodes
10009         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10010         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10011         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10012         if ( u2n->second == sn0 || u2n->second == sn1 )
10013         {
10014           while ( u2n->second != tn0 && u2n->second != tn1 )
10015             ++u2n;
10016           nodes.erase( nodes.begin(), u2n );
10017         }
10018         u2n = --nodes.end();
10019         if ( u2n->second == sn0 || u2n->second == sn1 )
10020         {
10021           while ( u2n->second != tn0 && u2n->second != tn1 )
10022             --u2n;
10023           nodes.erase( ++u2n, nodes.end() );
10024         }
10025         // set proxy sub-mesh
10026         uvPtVec.resize( nodes.size() );
10027         u2n = nodes.begin();
10028         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10029         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10030         {
10031           uvPtVec[ i ].node = u2n->second;
10032           uvPtVec[ i ].param = u2n->first;
10033           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10034         }
10035         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10036         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10037       }
10038
10039       // set proxy mesh of EDGEs with layers
10040       vector< _LayerEdge* > edges;
10041       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10042       {
10043         _EdgesOnShape& eos = * subEOS[ iS ];
10044         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10045
10046         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10047         data.SortOnEdge( E, eos._edges );
10048
10049         edges.clear();
10050         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10051           if ( !eov->_edges.empty() )
10052             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10053
10054         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10055
10056         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10057           if ( !eov->_edges.empty() )
10058             edges.push_back( eov->_edges[0] ); // on last VERTEX
10059
10060         uvPtVec.resize( edges.size() );
10061         for ( size_t i = 0; i < edges.size(); ++i )
10062         {
10063           uvPtVec[ i ].node = edges[i]->_nodes.back();
10064           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10065           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10066         }
10067         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10068         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10069         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10070       }
10071       // temporary clear the FACE sub-mesh from faces made by refine()
10072       vector< const SMDS_MeshElement* > elems;
10073       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10074       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10075         elems.push_back( ite->next() );
10076       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10077         elems.push_back( ite->next() );
10078       smDS->Clear();
10079
10080       // compute the mesh on the FACE
10081       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10082       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10083
10084       // re-fill proxy sub-meshes of the FACE
10085       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10086         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10087           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10088             psm->AddElement( ite->next() );
10089
10090       // re-fill smDS
10091       for ( size_t i = 0; i < elems.size(); ++i )
10092         smDS->AddElement( elems[i] );
10093
10094       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10095         return error( errMsg );
10096
10097     } // end of re-meshing in case of failed smoothing
10098     else
10099     {
10100       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10101       bool isStructuredFixed = false;
10102       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10103         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10104       if ( !isStructuredFixed )
10105       {
10106         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10107           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10108
10109         for ( int st = 3; st; --st )
10110         {
10111           switch( st ) {
10112           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10113           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10114           case 3: smoothType = _SmoothNode::ANGULAR; break;
10115           }
10116           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10117           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10118           {
10119             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10120                                      smoothType,/*set3D=*/st==1 );
10121           }
10122           dumpFunctionEnd();
10123         }
10124       }
10125       if ( !getMeshDS()->IsEmbeddedMode() )
10126         // Log node movement
10127         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10128         {
10129           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10130           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10131         }
10132     }
10133
10134     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10135     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10136
10137   } // loop on FACES to srink mesh on
10138
10139
10140   // Replace source nodes by target nodes in shrinked mesh edges
10141
10142   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10143   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10144     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10145
10146   return true;
10147 }
10148
10149 //================================================================================
10150 /*!
10151  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10152  */
10153 //================================================================================
10154
10155 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10156                                            _EdgesOnShape&         eos,
10157                                            SMESH_MesherHelper&    helper,
10158                                            const SMESHDS_SubMesh* faceSubMesh)
10159 {
10160   const SMDS_MeshNode* srcNode = edge._nodes[0];
10161   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10162
10163   if ( eos.SWOLType() == TopAbs_FACE )
10164   {
10165     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10166     {
10167       edge._pos.clear();
10168       return srcNode == tgtNode;
10169     }
10170     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10171     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10172     gp_Vec2d uvDir( srcUV, tgtUV );
10173     double uvLen = uvDir.Magnitude();
10174     uvDir /= uvLen;
10175     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10176     edge._len = uvLen;
10177
10178     edge._pos.resize(1);
10179     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10180
10181     // set UV of source node to target node
10182     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10183     pos->SetUParameter( srcUV.X() );
10184     pos->SetVParameter( srcUV.Y() );
10185   }
10186   else // _sWOL is TopAbs_EDGE
10187   {
10188     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10189     {
10190       edge._pos.clear();
10191       return srcNode == tgtNode;
10192     }
10193     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10194     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10195     if ( !edgeSM || edgeSM->NbElements() == 0 )
10196       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10197
10198     const SMDS_MeshNode* n2 = 0;
10199     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10200     while ( eIt->more() && !n2 )
10201     {
10202       const SMDS_MeshElement* e = eIt->next();
10203       if ( !edgeSM->Contains(e)) continue;
10204       n2 = e->GetNode( 0 );
10205       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10206     }
10207     if ( !n2 )
10208       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10209
10210     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10211     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10212     double u2   = helper.GetNodeU( E, n2, srcNode );
10213
10214     edge._pos.clear();
10215
10216     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10217     {
10218       // tgtNode is located so that it does not make faces with wrong orientation
10219       return true;
10220     }
10221     edge._pos.resize(1);
10222     edge._pos[0].SetCoord( U_TGT, uTgt );
10223     edge._pos[0].SetCoord( U_SRC, uSrc );
10224     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10225
10226     edge._simplices.resize( 1 );
10227     edge._simplices[0]._nPrev = n2;
10228
10229     // set U of source node to the target node
10230     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10231     pos->SetUParameter( uSrc );
10232   }
10233   return true;
10234 }
10235
10236 //================================================================================
10237 /*!
10238  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10239  */
10240 //================================================================================
10241
10242 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10243 {
10244   if ( edge._nodes.size() == 1 )
10245   {
10246     edge._pos.clear();
10247     edge._len = 0;
10248
10249     const SMDS_MeshNode* srcNode = edge._nodes[0];
10250     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10251     if ( S.IsNull() ) return;
10252
10253     gp_Pnt p;
10254
10255     switch ( S.ShapeType() )
10256     {
10257     case TopAbs_EDGE:
10258     {
10259       double f,l;
10260       TopLoc_Location loc;
10261       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10262       if ( curve.IsNull() ) return;
10263       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10264       p = curve->Value( ePos->GetUParameter() );
10265       break;
10266     }
10267     case TopAbs_VERTEX:
10268     {
10269       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10270       break;
10271     }
10272     default: return;
10273     }
10274     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10275     dumpMove( srcNode );
10276   }
10277 }
10278
10279 //================================================================================
10280 /*!
10281  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10282  */
10283 //================================================================================
10284
10285 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10286                                   SMESH_MesherHelper&         helper,
10287                                   const bool                  is2D,
10288                                   const int                   step,
10289                                   set<const SMDS_MeshNode*> * involvedNodes)
10290 {
10291   SMESH::Controls::AspectRatio qualifier;
10292   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10293   const double maxAspectRatio = is2D ? 4. : 2;
10294   _NodeCoordHelper xyz( F, helper, is2D );
10295
10296   // find bad triangles
10297
10298   vector< const SMDS_MeshElement* > badTrias;
10299   vector< double >                  badAspects;
10300   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10301   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10302   while ( fIt->more() )
10303   {
10304     const SMDS_MeshElement * f = fIt->next();
10305     if ( f->NbCornerNodes() != 3 ) continue;
10306     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10307     double aspect = qualifier.GetValue( points );
10308     if ( aspect > maxAspectRatio )
10309     {
10310       badTrias.push_back( f );
10311       badAspects.push_back( aspect );
10312     }
10313   }
10314   if ( step == 1 )
10315   {
10316     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10317     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10318     while ( fIt->more() )
10319     {
10320       const SMDS_MeshElement * f = fIt->next();
10321       if ( f->NbCornerNodes() == 3 )
10322         dumpChangeNodes( f );
10323     }
10324     dumpFunctionEnd();
10325   }
10326   if ( badTrias.empty() )
10327     return;
10328
10329   // find couples of faces to swap diagonal
10330
10331   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10332   vector< T2Trias > triaCouples; 
10333
10334   TIDSortedElemSet involvedFaces, emptySet;
10335   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10336   {
10337     T2Trias trias    [3];
10338     double  aspRatio [3];
10339     int i1, i2, i3;
10340
10341     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10342       continue;
10343     for ( int iP = 0; iP < 3; ++iP )
10344       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10345
10346     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10347     int bestCouple = -1;
10348     for ( int iSide = 0; iSide < 3; ++iSide )
10349     {
10350       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10351       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10352       trias [iSide].first  = badTrias[iTia];
10353       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10354                                                              & i1, & i2 );
10355       if (( ! trias[iSide].second ) ||
10356           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10357           ( ! sm->Contains( trias[iSide].second )))
10358         continue;
10359
10360       // aspect ratio of an adjacent tria
10361       for ( int iP = 0; iP < 3; ++iP )
10362         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10363       double aspectInit = qualifier.GetValue( points2 );
10364
10365       // arrange nodes as after diag-swaping
10366       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10367         i3 = helper.WrapIndex( i1-1, 3 );
10368       else
10369         i3 = helper.WrapIndex( i1+1, 3 );
10370       points1 = points;
10371       points1( 1+ iSide ) = points2( 1+ i3 );
10372       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10373
10374       // aspect ratio after diag-swaping
10375       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10376       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10377         continue;
10378
10379       // prevent inversion of a triangle
10380       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10381       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10382       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10383         continue;
10384
10385       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10386         bestCouple = iSide;
10387     }
10388
10389     if ( bestCouple >= 0 )
10390     {
10391       triaCouples.push_back( trias[bestCouple] );
10392       involvedFaces.insert ( trias[bestCouple].second );
10393     }
10394     else
10395     {
10396       involvedFaces.erase( badTrias[iTia] );
10397     }
10398   }
10399   if ( triaCouples.empty() )
10400     return;
10401
10402   // swap diagonals
10403
10404   SMESH_MeshEditor editor( helper.GetMesh() );
10405   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10406   for ( size_t i = 0; i < triaCouples.size(); ++i )
10407   {
10408     dumpChangeNodes( triaCouples[i].first );
10409     dumpChangeNodes( triaCouples[i].second );
10410     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10411   }
10412
10413   if ( involvedNodes )
10414     for ( size_t i = 0; i < triaCouples.size(); ++i )
10415     {
10416       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10417                              triaCouples[i].first->end_nodes() );
10418       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10419                              triaCouples[i].second->end_nodes() );
10420     }
10421
10422   // just for debug dump resulting triangles
10423   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10424   for ( size_t i = 0; i < triaCouples.size(); ++i )
10425   {
10426     dumpChangeNodes( triaCouples[i].first );
10427     dumpChangeNodes( triaCouples[i].second );
10428   }
10429 }
10430
10431 //================================================================================
10432 /*!
10433  * \brief Move target node to it's final position on the FACE during shrinking
10434  */
10435 //================================================================================
10436
10437 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10438                                  const TopoDS_Face&    F,
10439                                  _EdgesOnShape&        eos,
10440                                  SMESH_MesherHelper&   helper )
10441 {
10442   if ( _pos.empty() )
10443     return false; // already at the target position
10444
10445   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10446
10447   if ( eos.SWOLType() == TopAbs_FACE )
10448   {
10449     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10450     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10451     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10452     const double uvLen = tgtUV.Distance( curUV );
10453     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10454
10455     // Select shrinking step such that not to make faces with wrong orientation.
10456     double stepSize = 1e100;
10457     for ( size_t i = 0; i < _simplices.size(); ++i )
10458     {
10459       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10460       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10461       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10462       gp_XY dirN = uvN2 - uvN1;
10463       double det = uvDir.Crossed( dirN );
10464       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10465       gp_XY dirN2Cur = curUV - uvN1;
10466       double step = dirN.Crossed( dirN2Cur ) / det;
10467       if ( step > 0 )
10468         stepSize = Min( step, stepSize );
10469     }
10470     gp_Pnt2d newUV;
10471     if ( uvLen <= stepSize )
10472     {
10473       newUV = tgtUV;
10474       _pos.clear();
10475     }
10476     else if ( stepSize > 0 )
10477     {
10478       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10479     }
10480     else
10481     {
10482       return true;
10483     }
10484     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10485     pos->SetUParameter( newUV.X() );
10486     pos->SetVParameter( newUV.Y() );
10487
10488 #ifdef __myDEBUG
10489     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10490     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10491     dumpMove( tgtNode );
10492 #endif
10493   }
10494   else // _sWOL is TopAbs_EDGE
10495   {
10496     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10497     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10498     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10499
10500     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10501     const double uSrc   = _pos[0].Coord( U_SRC );
10502     const double lenTgt = _pos[0].Coord( LEN_TGT );
10503
10504     double newU = _pos[0].Coord( U_TGT );
10505     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10506     {
10507       _pos.clear();
10508     }
10509     else
10510     {
10511       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10512     }
10513     tgtPos->SetUParameter( newU );
10514 #ifdef __myDEBUG
10515     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10516     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10517     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10518     dumpMove( tgtNode );
10519 #endif
10520   }
10521
10522   return true;
10523 }
10524
10525 //================================================================================
10526 /*!
10527  * \brief Perform smooth on the FACE
10528  *  \retval bool - true if the node has been moved
10529  */
10530 //================================================================================
10531
10532 bool _SmoothNode::Smooth(int&                  nbBad,
10533                          Handle(Geom_Surface)& surface,
10534                          SMESH_MesherHelper&   helper,
10535                          const double          refSign,
10536                          SmoothType            how,
10537                          bool                  set3D)
10538 {
10539   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10540
10541   // get uv of surrounding nodes
10542   vector<gp_XY> uv( _simplices.size() );
10543   for ( size_t i = 0; i < _simplices.size(); ++i )
10544     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10545
10546   // compute new UV for the node
10547   gp_XY newPos (0,0);
10548   if ( how == TFI && _simplices.size() == 4 )
10549   {
10550     gp_XY corners[4];
10551     for ( size_t i = 0; i < _simplices.size(); ++i )
10552       if ( _simplices[i]._nOpp )
10553         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10554       else
10555         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10556
10557     newPos = helper.calcTFI ( 0.5, 0.5,
10558                               corners[0], corners[1], corners[2], corners[3],
10559                               uv[1], uv[2], uv[3], uv[0] );
10560   }
10561   else if ( how == ANGULAR )
10562   {
10563     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10564   }
10565   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10566   {
10567     // average centers of diagonals wieghted with their reciprocal lengths
10568     if ( _simplices.size() == 4 )
10569     {
10570       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10571       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10572       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10573     }
10574     else
10575     {
10576       double sumWeight = 0;
10577       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10578       for ( int i = 0; i < nb; ++i )
10579       {
10580         int iFrom = i + 2;
10581         int iTo   = i + _simplices.size() - 1;
10582         for ( int j = iFrom; j < iTo; ++j )
10583         {
10584           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10585           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10586           sumWeight += w;
10587           newPos += w * ( uv[i]+uv[i2] );
10588         }
10589       }
10590       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10591     }
10592   }
10593   else
10594   {
10595     // Laplacian smooth
10596     for ( size_t i = 0; i < _simplices.size(); ++i )
10597       newPos += uv[i];
10598     newPos /= _simplices.size();
10599   }
10600
10601   // count quality metrics (orientation) of triangles around the node
10602   int nbOkBefore = 0;
10603   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10604   for ( size_t i = 0; i < _simplices.size(); ++i )
10605     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10606
10607   int nbOkAfter = 0;
10608   for ( size_t i = 0; i < _simplices.size(); ++i )
10609     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10610
10611   if ( nbOkAfter < nbOkBefore )
10612   {
10613     nbBad += _simplices.size() - nbOkBefore;
10614     return false;
10615   }
10616
10617   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10618   pos->SetUParameter( newPos.X() );
10619   pos->SetVParameter( newPos.Y() );
10620
10621 #ifdef __myDEBUG
10622   set3D = true;
10623 #endif
10624   if ( set3D )
10625   {
10626     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10627     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10628     dumpMove( _node );
10629   }
10630
10631   nbBad += _simplices.size() - nbOkAfter;
10632   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10633 }
10634
10635 //================================================================================
10636 /*!
10637  * \brief Computes new UV using angle based smoothing technic
10638  */
10639 //================================================================================
10640
10641 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10642                                      const gp_XY&   uvToFix,
10643                                      const double   refSign)
10644 {
10645   uv.push_back( uv.front() );
10646
10647   vector< gp_XY >  edgeDir ( uv.size() );
10648   vector< double > edgeSize( uv.size() );
10649   for ( size_t i = 1; i < edgeDir.size(); ++i )
10650   {
10651     edgeDir [i-1] = uv[i] - uv[i-1];
10652     edgeSize[i-1] = edgeDir[i-1].Modulus();
10653     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10654       edgeDir[i-1].SetX( 100 );
10655     else
10656       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10657   }
10658   edgeDir.back()  = edgeDir.front();
10659   edgeSize.back() = edgeSize.front();
10660
10661   gp_XY  newPos(0,0);
10662   //int    nbEdges = 0;
10663   double sumSize = 0;
10664   for ( size_t i = 1; i < edgeDir.size(); ++i )
10665   {
10666     if ( edgeDir[i-1].X() > 1. ) continue;
10667     int i1 = i-1;
10668     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10669     if ( i == edgeDir.size() ) break;
10670     gp_XY p = uv[i];
10671     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10672     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10673     gp_XY bisec = norm1 + norm2;
10674     double bisecSize = bisec.Modulus();
10675     if ( bisecSize < numeric_limits<double>::min() )
10676     {
10677       bisec = -edgeDir[i1] + edgeDir[i];
10678       bisecSize = bisec.Modulus();
10679     }
10680     bisec /= bisecSize;
10681
10682     gp_XY  dirToN  = uvToFix - p;
10683     double distToN = dirToN.Modulus();
10684     if ( bisec * dirToN < 0 )
10685       distToN = -distToN;
10686
10687     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10688     //++nbEdges;
10689     sumSize += edgeSize[i1] + edgeSize[i];
10690   }
10691   newPos /= /*nbEdges * */sumSize;
10692   return newPos;
10693 }
10694
10695 //================================================================================
10696 /*!
10697  * \brief Delete _SolidData
10698  */
10699 //================================================================================
10700
10701 _SolidData::~_SolidData()
10702 {
10703   TNode2Edge::iterator n2e = _n2eMap.begin();
10704   for ( ; n2e != _n2eMap.end(); ++n2e )
10705   {
10706     _LayerEdge* & e = n2e->second;
10707     if ( e )
10708     {
10709       delete e->_curvature;
10710       if ( e->_2neibors )
10711         delete e->_2neibors->_plnNorm;
10712       delete e->_2neibors;
10713     }
10714     delete e;
10715     e = 0;
10716   }
10717   _n2eMap.clear();
10718
10719   delete _helper;
10720   _helper = 0;
10721 }
10722
10723 //================================================================================
10724 /*!
10725  * \brief Keep a _LayerEdge inflated along the EDGE
10726  */
10727 //================================================================================
10728
10729 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10730                            _EdgesOnShape&      eos,
10731                            SMESH_MesherHelper& helper )
10732 {
10733   // init
10734   if ( _nodes.empty() )
10735   {
10736     _edges[0] = _edges[1] = 0;
10737     _done = false;
10738   }
10739   // check _LayerEdge
10740   if ( e == _edges[0] || e == _edges[1] )
10741     return;
10742   if ( eos.SWOLType() != TopAbs_EDGE )
10743     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10744   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10745     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10746
10747   // store _LayerEdge
10748   _geomEdge = TopoDS::Edge( eos._sWOL );
10749   double f,l;
10750   BRep_Tool::Range( _geomEdge, f,l );
10751   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10752   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10753
10754   // Update _nodes
10755
10756   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10757   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10758
10759   if ( _nodes.empty() )
10760   {
10761     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10762     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10763       return;
10764     TopLoc_Location loc;
10765     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10766     GeomAdaptor_Curve aCurve(C, f,l);
10767     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10768
10769     int nbExpectNodes = eSubMesh->NbNodes();
10770     _initU  .reserve( nbExpectNodes );
10771     _normPar.reserve( nbExpectNodes );
10772     _nodes  .reserve( nbExpectNodes );
10773     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10774     while ( nIt->more() )
10775     {
10776       const SMDS_MeshNode* node = nIt->next();
10777       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10778            node == tgtNode0 || node == tgtNode1 )
10779         continue; // refinement nodes
10780       _nodes.push_back( node );
10781       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10782       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10783       _normPar.push_back(  len / totLen );
10784     }
10785   }
10786   else
10787   {
10788     // remove target node of the _LayerEdge from _nodes
10789     size_t nbFound = 0;
10790     for ( size_t i = 0; i < _nodes.size(); ++i )
10791       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10792         _nodes[i] = 0, nbFound++;
10793     if ( nbFound == _nodes.size() )
10794       _nodes.clear();
10795   }
10796 }
10797
10798 //================================================================================
10799 /*!
10800  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10801  */
10802 //================================================================================
10803
10804 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10805 {
10806   if ( _done || _nodes.empty())
10807     return;
10808   const _LayerEdge* e = _edges[0];
10809   if ( !e ) e = _edges[1];
10810   if ( !e ) return;
10811
10812   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10813             ( !_edges[1] || _edges[1]->_pos.empty() ));
10814
10815   double f,l;
10816   if ( set3D || _done )
10817   {
10818     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10819     GeomAdaptor_Curve aCurve(C, f,l);
10820
10821     if ( _edges[0] )
10822       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10823     if ( _edges[1] )
10824       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10825     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10826
10827     for ( size_t i = 0; i < _nodes.size(); ++i )
10828     {
10829       if ( !_nodes[i] ) continue;
10830       double len = totLen * _normPar[i];
10831       GCPnts_AbscissaPoint discret( aCurve, len, f );
10832       if ( !discret.IsDone() )
10833         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10834       double u = discret.Parameter();
10835       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10836       pos->SetUParameter( u );
10837       gp_Pnt p = C->Value( u );
10838       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10839     }
10840   }
10841   else
10842   {
10843     BRep_Tool::Range( _geomEdge, f,l );
10844     if ( _edges[0] )
10845       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10846     if ( _edges[1] )
10847       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10848     
10849     for ( size_t i = 0; i < _nodes.size(); ++i )
10850     {
10851       if ( !_nodes[i] ) continue;
10852       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10853       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10854       pos->SetUParameter( u );
10855     }
10856   }
10857 }
10858
10859 //================================================================================
10860 /*!
10861  * \brief Restore initial parameters of nodes on EDGE
10862  */
10863 //================================================================================
10864
10865 void _Shrinker1D::RestoreParams()
10866 {
10867   if ( _done )
10868     for ( size_t i = 0; i < _nodes.size(); ++i )
10869     {
10870       if ( !_nodes[i] ) continue;
10871       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10872       pos->SetUParameter( _initU[i] );
10873     }
10874   _done = false;
10875 }
10876
10877 //================================================================================
10878 /*!
10879  * \brief Replace source nodes by target nodes in shrinked mesh edges
10880  */
10881 //================================================================================
10882
10883 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10884 {
10885   const SMDS_MeshNode* nodes[3];
10886   for ( int i = 0; i < 2; ++i )
10887   {
10888     if ( !_edges[i] ) continue;
10889
10890     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10891     if ( !eSubMesh ) return;
10892     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10893     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10894     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10895     while ( eIt->more() )
10896     {
10897       const SMDS_MeshElement* e = eIt->next();
10898       if ( !eSubMesh->Contains( e ))
10899           continue;
10900       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10901       for ( int iN = 0; iN < e->NbNodes(); ++iN )
10902       {
10903         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10904         nodes[iN] = ( n == srcNode ? tgtNode : n );
10905       }
10906       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10907     }
10908   }
10909 }
10910
10911 //================================================================================
10912 /*!
10913  * \brief Creates 2D and 1D elements on boundaries of new prisms
10914  */
10915 //================================================================================
10916
10917 bool _ViscousBuilder::addBoundaryElements()
10918 {
10919   SMESH_MesherHelper helper( *_mesh );
10920
10921   vector< const SMDS_MeshNode* > faceNodes;
10922
10923   for ( size_t i = 0; i < _sdVec.size(); ++i )
10924   {
10925     _SolidData& data = _sdVec[i];
10926     TopTools_IndexedMapOfShape geomEdges;
10927     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10928     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10929     {
10930       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10931       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10932         continue;
10933
10934       // Get _LayerEdge's based on E
10935
10936       map< double, const SMDS_MeshNode* > u2nodes;
10937       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10938         continue;
10939
10940       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10941       TNode2Edge & n2eMap = data._n2eMap;
10942       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10943       {
10944         //check if 2D elements are needed on E
10945         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10946         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10947         ledges.push_back( n2e->second );
10948         u2n++;
10949         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10950           continue; // no layers on E
10951         ledges.push_back( n2eMap[ u2n->second ]);
10952
10953         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10954         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10955         int nbSharedPyram = 0;
10956         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10957         while ( vIt->more() )
10958         {
10959           const SMDS_MeshElement* v = vIt->next();
10960           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10961         }
10962         if ( nbSharedPyram > 1 )
10963           continue; // not free border of the pyramid
10964
10965         faceNodes.clear();
10966         faceNodes.push_back( ledges[0]->_nodes[0] );
10967         faceNodes.push_back( ledges[1]->_nodes[0] );
10968         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10969         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10970
10971         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10972           continue; // faces already created
10973       }
10974       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10975         ledges.push_back( n2eMap[ u2n->second ]);
10976
10977       // Find out orientation and type of face to create
10978
10979       bool reverse = false, isOnFace;
10980       
10981       map< TGeomID, TopoDS_Shape >::iterator e2f =
10982         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10983       TopoDS_Shape F;
10984       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10985       {
10986         F = e2f->second.Oriented( TopAbs_FORWARD );
10987         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
10988         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
10989           reverse = !reverse, F.Reverse();
10990         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
10991           reverse = !reverse;
10992       }
10993       else
10994       {
10995         // find FACE with layers sharing E
10996         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
10997         while ( fIt->more() && F.IsNull() )
10998         {
10999           const TopoDS_Shape* pF = fIt->next();
11000           if ( helper.IsSubShape( *pF, data._solid) &&
11001                !data._ignoreFaceIds.count( e2f->first ))
11002             F = *pF;
11003         }
11004       }
11005       // Find the sub-mesh to add new faces
11006       SMESHDS_SubMesh* sm = 0;
11007       if ( isOnFace )
11008         sm = getMeshDS()->MeshElements( F );
11009       else
11010         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11011       if ( !sm )
11012         return error("error in addBoundaryElements()", data._index);
11013
11014       // Make faces
11015       const int dj1 = reverse ? 0 : 1;
11016       const int dj2 = reverse ? 1 : 0;
11017       for ( size_t j = 1; j < ledges.size(); ++j )
11018       {
11019         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11020         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11021         if ( nn1.size() == nn2.size() )
11022         {
11023           if ( isOnFace )
11024             for ( size_t z = 1; z < nn1.size(); ++z )
11025               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11026           else
11027             for ( size_t z = 1; z < nn1.size(); ++z )
11028               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11029         }
11030         else if ( nn1.size() == 1 )
11031         {
11032           if ( isOnFace )
11033             for ( size_t z = 1; z < nn2.size(); ++z )
11034               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11035           else
11036             for ( size_t z = 1; z < nn2.size(); ++z )
11037               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11038         }
11039         else
11040         {
11041           if ( isOnFace )
11042             for ( size_t z = 1; z < nn1.size(); ++z )
11043               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11044           else
11045             for ( size_t z = 1; z < nn1.size(); ++z )
11046               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11047         }
11048       }
11049
11050       // Make edges
11051       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11052       {
11053         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11054         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11055         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11056         {
11057           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11058           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11059             continue;
11060           helper.SetSubShape( eos->_sWOL );
11061           helper.SetElementsOnShape( true );
11062           for ( size_t z = 1; z < nn.size(); ++z )
11063             helper.AddEdge( nn[z-1], nn[z] );
11064         }
11065       }
11066
11067     } // loop on EDGE's
11068   } // loop on _SolidData's
11069
11070   return true;
11071 }