Salome HOME
f84fc5b5e791102a8d181afa598a336bcce75639
[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                   SHRUNK          = 0x0004000, // target node reached a tgt position while shrink()
443                   UNUSED_FLAG     = 0x0100000
444     };
445     bool Is   ( int flag ) const { return _flags & flag; }
446     void Set  ( int flag ) { _flags |= flag; }
447     void Unset( int flag ) { _flags &= ~flag; }
448
449     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
450     bool SetNewLength2d( Handle(Geom_Surface)& surface,
451                          const TopoDS_Face&    F,
452                          _EdgesOnShape&        eos,
453                          SMESH_MesherHelper&   helper );
454     void SetDataByNeighbors( const SMDS_MeshNode* n1,
455                              const SMDS_MeshNode* n2,
456                              const _EdgesOnShape& eos,
457                              SMESH_MesherHelper&  helper);
458     void Block( _SolidData& data );
459     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
460     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
461                             const TNode2Edge&     n2eMap);
462     void SmoothPos( const vector< double >& segLen, const double tol );
463     int  GetSmoothedPos( const double tol );
464     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
465     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
466     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
467     void SmoothWoCheck();
468     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
469                       const TopoDS_Face&             F,
470                       SMESH_MesherHelper&            helper);
471     void MoveNearConcaVer( const _EdgesOnShape*    eov,
472                            const _EdgesOnShape*    eos,
473                            const int               step,
474                            vector< _LayerEdge* > & badSmooEdges);
475     bool FindIntersection( SMESH_ElementSearcher&   searcher,
476                            double &                 distance,
477                            const double&            epsilon,
478                            _EdgesOnShape&           eos,
479                            const SMDS_MeshElement** face = 0);
480     bool SegTriaInter( const gp_Ax1&        lastSegment,
481                        const gp_XYZ&        p0,
482                        const gp_XYZ&        p1,
483                        const gp_XYZ&        p2,
484                        double&              dist,
485                        const double&        epsilon) const;
486     bool SegTriaInter( const gp_Ax1&        lastSegment,
487                        const SMDS_MeshNode* n0,
488                        const SMDS_MeshNode* n1,
489                        const SMDS_MeshNode* n2,
490                        double&              dist,
491                        const double&        epsilon) const
492     { return SegTriaInter( lastSegment,
493                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
494                            dist, epsilon );
495     }
496     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
497     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
498     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
499     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
500     bool   IsOnEdge() const { return _2neibors; }
501     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
502     void   SetCosin( double cosin );
503     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
504     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
505     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
506     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
507       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
508     }
509     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
510
511     gp_XYZ smoothLaplacian();
512     gp_XYZ smoothAngular();
513     gp_XYZ smoothLengthWeighted();
514     gp_XYZ smoothCentroidal();
515     gp_XYZ smoothNefPolygon();
516
517     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
518     static const int theNbSmooFuns = FUN_NB;
519     static PSmooFun _funs[theNbSmooFuns];
520     static const char* _funNames[theNbSmooFuns+1];
521     int smooFunID( PSmooFun fun=0) const;
522   };
523   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
524                                                             &_LayerEdge::smoothLengthWeighted,
525                                                             &_LayerEdge::smoothCentroidal,
526                                                             &_LayerEdge::smoothNefPolygon,
527                                                             &_LayerEdge::smoothAngular };
528   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
529                                                          "LengthWeighted",
530                                                          "Centroidal",
531                                                          "NefPolygon",
532                                                          "Angular",
533                                                          "None"};
534   struct _LayerEdgeCmp
535   {
536     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
537     {
538       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
539       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
540     }
541   };
542   //--------------------------------------------------------------------------------
543   /*!
544    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
545    */
546   struct _halfPlane
547   {
548     gp_XY _pos, _dir, _inNorm;
549     bool IsOut( const gp_XY p, const double tol ) const
550     {
551       return _inNorm * ( p - _pos ) < -tol;
552     }
553     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
554     {
555       //const double eps = 1e-10;
556       double D = _dir.Crossed( hp._dir );
557       if ( fabs(D) < std::numeric_limits<double>::min())
558         return false;
559       gp_XY vec21 = _pos - hp._pos; 
560       double u = hp._dir.Crossed( vec21 ) / D; 
561       intPnt = _pos + _dir * u;
562       return true;
563     }
564   };
565   //--------------------------------------------------------------------------------
566   /*!
567    * Structure used to smooth a _LayerEdge based on an EDGE.
568    */
569   struct _2NearEdges
570   {
571     double               _wgt  [2]; // weights of _nodes
572     _LayerEdge*          _edges[2];
573
574      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
575     gp_XYZ*              _plnNorm;
576
577     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
578     const SMDS_MeshNode* tgtNode(bool is2nd) {
579       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
580     }
581     const SMDS_MeshNode* srcNode(bool is2nd) {
582       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
583     }
584     void reverse() {
585       std::swap( _wgt  [0], _wgt  [1] );
586       std::swap( _edges[0], _edges[1] );
587     }
588     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
589       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
590     }
591     bool include( const _LayerEdge* e ) {
592       return ( _edges[0] == e || _edges[1] == e );
593     }
594   };
595
596
597   //--------------------------------------------------------------------------------
598   /*!
599    * \brief Layers parameters got by averaging several hypotheses
600    */
601   struct AverageHyp
602   {
603     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
604       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
605     {
606       Add( hyp );
607     }
608     void Add( const StdMeshers_ViscousLayers* hyp )
609     {
610       if ( hyp )
611       {
612         _nbHyps++;
613         _nbLayers       = hyp->GetNumberLayers();
614         //_thickness     += hyp->GetTotalThickness();
615         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
616         _stretchFactor += hyp->GetStretchFactor();
617         _method         = hyp->GetMethod();
618       }
619     }
620     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
621     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
622     int    GetNumberLayers()   const { return _nbLayers; }
623     int    GetMethod()         const { return _method; }
624
625     bool   UseSurfaceNormal()  const
626     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
627     bool   ToSmooth()          const
628     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
629     bool   IsOffsetMethod()    const
630     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
631
632   private:
633     int     _nbLayers, _nbHyps, _method;
634     double  _thickness, _stretchFactor;
635   };
636
637   //--------------------------------------------------------------------------------
638   /*!
639    * \brief _LayerEdge's on a shape and other shape data
640    */
641   struct _EdgesOnShape
642   {
643     vector< _LayerEdge* > _edges;
644
645     TopoDS_Shape          _shape;
646     TGeomID               _shapeID;
647     SMESH_subMesh *       _subMesh;
648     // face or edge w/o layer along or near which _edges are inflated
649     TopoDS_Shape          _sWOL;
650     bool                  _isRegularSWOL; // w/o singularities
651     // averaged StdMeshers_ViscousLayers parameters
652     AverageHyp            _hyp;
653     bool                  _toSmooth;
654     _Smoother1D*          _edgeSmoother;
655     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
656     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
657
658     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
659     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
660
661     Handle(ShapeAnalysis_Surface) _offsetSurf;
662     _LayerEdge*                   _edgeForOffset;
663
664     _SolidData*            _data; // parent SOLID
665
666     TopAbs_ShapeEnum ShapeType() const
667     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
668     TopAbs_ShapeEnum SWOLType() const
669     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
670     bool             HasC1( const _EdgesOnShape* other ) const
671     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
672     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
673     _SolidData&      GetData() const { return *_data; }
674
675     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
676   };
677
678   //--------------------------------------------------------------------------------
679   /*!
680    * \brief Convex FACE whose radius of curvature is less than the thickness of 
681    *        layers. It is used to detect distortion of prisms based on a convex
682    *        FACE and to update normals to enable further increasing the thickness
683    */
684   struct _ConvexFace
685   {
686     TopoDS_Face                     _face;
687
688     // edges whose _simplices are used to detect prism distortion
689     vector< _LayerEdge* >           _simplexTestEdges;
690
691     // map a sub-shape to _SolidData::_edgesOnShape
692     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
693
694     bool                            _normalsFixed;
695
696     bool GetCenterOfCurvature( _LayerEdge*         ledge,
697                                BRepLProp_SLProps&  surfProp,
698                                SMESH_MesherHelper& helper,
699                                gp_Pnt &            center ) const;
700     bool CheckPrisms() const;
701   };
702
703   //--------------------------------------------------------------------------------
704   /*!
705    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
706    *        at inflation up to the full thickness. A detected collision
707    *        is fixed in updateNormals()
708    */
709   struct _CollisionEdges
710   {
711     _LayerEdge*           _edge;
712     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
713     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
714     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
715   };
716
717   //--------------------------------------------------------------------------------
718   /*!
719    * \brief Data of a SOLID
720    */
721   struct _SolidData
722   {
723     typedef const StdMeshers_ViscousLayers* THyp;
724     TopoDS_Shape                    _solid;
725     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
726     TGeomID                         _index; // SOLID id
727     _MeshOfSolid*                   _proxyMesh;
728     list< THyp >                    _hyps;
729     list< TopoDS_Shape >            _hypShapes;
730     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
731     set< TGeomID >                  _reversedFaceIds;
732     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
733
734     double                          _stepSize, _stepSizeCoeff, _geomSize;
735     const SMDS_MeshNode*            _stepSizeNodes[2];
736
737     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
738
739     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
740     map< TGeomID, TNode2Edge* >     _s2neMap;
741     // _LayerEdge's with underlying shapes
742     vector< _EdgesOnShape >         _edgesOnShape;
743
744     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
745     //        layers and a FACE w/o layers
746     // value: the shape (FACE or EDGE) to shrink mesh on.
747     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
748     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
749
750     // Convex FACEs whose radius of curvature is less than the thickness of layers
751     map< TGeomID, _ConvexFace >      _convexFaces;
752
753     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
754     // the adjacent SOLID
755     set< TGeomID >                   _noShrinkShapes;
756
757     int                              _nbShapesToSmooth;
758
759     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
760
761     vector< _CollisionEdges >        _collisionEdges;
762     set< TGeomID >                   _concaveFaces;
763
764     double                           _maxThickness; // of all _hyps
765     double                           _minThickness; // of all _hyps
766
767     double                           _epsilon; // precision for SegTriaInter()
768
769     SMESH_MesherHelper*              _helper;
770
771     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
772                _MeshOfSolid*       m=0)
773       :_solid(s), _proxyMesh(m), _helper(0) {}
774     ~_SolidData();
775
776     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
777     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
778
779     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
780       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
781       return id2face == _convexFaces.end() ? 0 : & id2face->second;
782     }
783     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
784     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
785     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
786     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
787
788     SMESH_MesherHelper& GetHelper() const { return *_helper; }
789
790     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
791       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
792         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
793           _edgesOnShape[i]._edges[j]->Unset( flag );
794     }
795     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
796                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
797
798     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
799   };
800   //--------------------------------------------------------------------------------
801   /*!
802    * \brief Offset plane used in getNormalByOffset()
803    */
804   struct _OffsetPlane
805   {
806     gp_Pln _plane;
807     int    _faceIndex;
808     int    _faceIndexNext[2];
809     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
810     bool   _isLineOK[2];
811     _OffsetPlane() {
812       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
813     }
814     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
815                                     const TopoDS_Edge&   E,
816                                     const TopoDS_Vertex& V );
817     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
818     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
819   };
820   //--------------------------------------------------------------------------------
821   /*!
822    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
823    */
824   struct _CentralCurveOnEdge
825   {
826     bool                  _isDegenerated;
827     vector< gp_Pnt >      _curvaCenters;
828     vector< _LayerEdge* > _ledges;
829     vector< gp_XYZ >      _normals; // new normal for each of _ledges
830     vector< double >      _segLength2;
831
832     TopoDS_Edge           _edge;
833     TopoDS_Face           _adjFace;
834     bool                  _adjFaceToSmooth;
835
836     void Append( const gp_Pnt& center, _LayerEdge* ledge )
837     {
838       if ( _curvaCenters.size() > 0 )
839         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
840       _curvaCenters.push_back( center );
841       _ledges.push_back( ledge );
842       _normals.push_back( ledge->_normal );
843     }
844     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
845     void SetShapes( const TopoDS_Edge&  edge,
846                     const _ConvexFace&  convFace,
847                     _SolidData&         data,
848                     SMESH_MesherHelper& helper);
849   };
850   //--------------------------------------------------------------------------------
851   /*!
852    * \brief Data of node on a shrinked FACE
853    */
854   struct _SmoothNode
855   {
856     const SMDS_MeshNode*         _node;
857     vector<_Simplex>             _simplices; // for quality check
858
859     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
860
861     bool Smooth(int&                  badNb,
862                 Handle(Geom_Surface)& surface,
863                 SMESH_MesherHelper&   helper,
864                 const double          refSign,
865                 SmoothType            how,
866                 bool                  set3D);
867
868     gp_XY computeAngularPos(vector<gp_XY>& uv,
869                             const gp_XY&   uvToFix,
870                             const double   refSign );
871   };
872   //--------------------------------------------------------------------------------
873   /*!
874    * \brief Builder of viscous layers
875    */
876   class _ViscousBuilder
877   {
878   public:
879     _ViscousBuilder();
880     // does it's job
881     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
882                                   const TopoDS_Shape& shape);
883     // check validity of hypotheses
884     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
885                                            const TopoDS_Shape& shape );
886
887     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
888     void RestoreListeners();
889
890     // computes SMESH_ProxyMesh::SubMesh::_n2n;
891     bool MakeN2NMap( _MeshOfSolid* pm );
892
893   private:
894
895     bool findSolidsWithLayers();
896     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
897     bool findFacesWithLayers(const bool onlyWith=false);
898     void getIgnoreFaces(const TopoDS_Shape&             solid,
899                         const StdMeshers_ViscousLayers* hyp,
900                         const TopoDS_Shape&             hypShape,
901                         set<TGeomID>&                   ignoreFaces);
902     bool makeLayer(_SolidData& data);
903     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
904     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
905                       SMESH_MesherHelper& helper, _SolidData& data);
906     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
907                          const TopoDS_Face&   face,
908                          SMESH_MesherHelper&  helper,
909                          bool&                isOK,
910                          bool                 shiftInside=false);
911     bool getFaceNormalAtSingularity(const gp_XY&        uv,
912                                     const TopoDS_Face&  face,
913                                     SMESH_MesherHelper& helper,
914                                     gp_Dir&             normal );
915     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
916     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
917                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
918                               int                              nbFaces,
919                               bool                             lastNoOffset = false);
920     bool findNeiborsOnEdge(const _LayerEdge*     edge,
921                            const SMDS_MeshNode*& n1,
922                            const SMDS_MeshNode*& n2,
923                            _EdgesOnShape&        eos,
924                            _SolidData&           data);
925     void findSimplexTestEdges( _SolidData&                    data,
926                                vector< vector<_LayerEdge*> >& edgesByGeom);
927     void computeGeomSize( _SolidData& data );
928     bool findShapesToSmooth( _SolidData& data);
929     void limitStepSizeByCurvature( _SolidData&  data );
930     void limitStepSize( _SolidData&             data,
931                         const SMDS_MeshElement* face,
932                         const _LayerEdge*       maxCosinEdge );
933     void limitStepSize( _SolidData& data, const double minSize);
934     bool inflate(_SolidData& data);
935     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
936     int  invalidateBadSmooth( _SolidData&               data,
937                               SMESH_MesherHelper&       helper,
938                               vector< _LayerEdge* >&    badSmooEdges,
939                               vector< _EdgesOnShape* >& eosC1,
940                               const int                 infStep );
941     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
942     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
943                              vector< _EdgesOnShape* >& eosC1,
944                              int smooStep=0, bool moveAll=false );
945     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
946     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
947     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
948                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
949                                  SMESH_MesherHelper& helper );
950     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
951     bool updateNormalsOfConvexFaces( _SolidData&         data,
952                                      SMESH_MesherHelper& helper,
953                                      int                 stepNb );
954     void updateNormalsOfC1Vertices( _SolidData& data );
955     bool updateNormalsOfSmoothed( _SolidData&         data,
956                                   SMESH_MesherHelper& helper,
957                                   const int           nbSteps,
958                                   const double        stepSize );
959     bool isNewNormalOk( _SolidData&   data,
960                         _LayerEdge&   edge,
961                         const gp_XYZ& newNormal);
962     bool refine(_SolidData& data);
963     bool shrink(_SolidData& data);
964     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
965                               SMESH_MesherHelper& helper,
966                               const SMESHDS_SubMesh* faceSubMesh );
967     void restoreNoShrink( _LayerEdge& edge ) const;
968     void fixBadFaces(const TopoDS_Face&          F,
969                      SMESH_MesherHelper&         helper,
970                      const bool                  is2D,
971                      const int                   step,
972                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
973     bool addBoundaryElements(_SolidData& data);
974
975     bool error( const string& text, int solidID=-1 );
976     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
977
978     // debug
979     void makeGroupOfLE();
980
981     SMESH_Mesh*                _mesh;
982     SMESH_ComputeErrorPtr      _error;
983
984     vector<                    _SolidData >  _sdVec;
985     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
986     TopTools_MapOfShape        _shrinkedFaces;
987
988     int                        _tmpFaceID;
989   };
990   //--------------------------------------------------------------------------------
991   /*!
992    * \brief Shrinker of nodes on the EDGE
993    */
994   class _Shrinker1D
995   {
996     TopoDS_Edge                   _geomEdge;
997     vector<double>                _initU;
998     vector<double>                _normPar;
999     vector<const SMDS_MeshNode*>  _nodes;
1000     const _LayerEdge*             _edges[2];
1001     bool                          _done;
1002   public:
1003     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1004     void Compute(bool set3D, SMESH_MesherHelper& helper);
1005     void RestoreParams();
1006     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1007     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1008     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1009     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1010     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1011     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1012   };
1013   //--------------------------------------------------------------------------------
1014   /*!
1015    * \brief Smoother of _LayerEdge's on EDGE.
1016    */
1017   struct _Smoother1D
1018   {
1019     struct OffPnt // point of the offsetted EDGE
1020     {
1021       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1022       double      _len;    // length reached at previous inflation step
1023       double      _param;  // on EDGE
1024       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1025       gp_XYZ      _edgeDir;// EDGE tangent at _param
1026       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1027     };
1028     vector< OffPnt >   _offPoints;
1029     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1030     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1031     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1032     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1033     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1034     _EdgesOnShape&     _eos;
1035     double             _curveLen; // length of the EDGE
1036
1037     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1038                                               _EdgesOnShape&      eos,
1039                                               SMESH_MesherHelper& helper);
1040
1041     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1042                  _EdgesOnShape&     eos )
1043       : _anaCurve( curveForSmooth ), _eos( eos )
1044     {
1045     }
1046     bool Perform(_SolidData&                    data,
1047                  Handle(ShapeAnalysis_Surface)& surface,
1048                  const TopoDS_Face&             F,
1049                  SMESH_MesherHelper&            helper )
1050     {
1051       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1052         prepare( data );
1053
1054       if ( isAnalytic() )
1055         return smoothAnalyticEdge( data, surface, F, helper );
1056       else
1057         return smoothComplexEdge ( data, surface, F, helper );
1058     }
1059     void prepare(_SolidData& data );
1060
1061     bool smoothAnalyticEdge( _SolidData&                    data,
1062                              Handle(ShapeAnalysis_Surface)& surface,
1063                              const TopoDS_Face&             F,
1064                              SMESH_MesherHelper&            helper);
1065
1066     bool smoothComplexEdge( _SolidData&                    data,
1067                             Handle(ShapeAnalysis_Surface)& surface,
1068                             const TopoDS_Face&             F,
1069                             SMESH_MesherHelper&            helper);
1070
1071     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1072                             const gp_XYZ&  edgeDir);
1073
1074     _LayerEdge* getLEdgeOnV( bool is2nd )
1075     {
1076       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1077     }
1078     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1079   };
1080   //--------------------------------------------------------------------------------
1081   /*!
1082    * \brief Class of temporary mesh face.
1083    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1084    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1085    */
1086   struct _TmpMeshFace : public SMDS_MeshElement
1087   {
1088     vector<const SMDS_MeshNode* > _nn;
1089     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1090                   int id, int faceID=-1, int idInFace=-1):
1091       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1092     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1093     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1094     virtual vtkIdType GetVtkType() const                      { return -1; }
1095     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1096     virtual SMDSAbs_GeometryType GetGeomType() const
1097     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1098     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1099     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1100   };
1101   //--------------------------------------------------------------------------------
1102   /*!
1103    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1104    */
1105   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1106   {
1107     _LayerEdge *_le1, *_le2;
1108     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1109       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1110     {
1111       _nn[0]=_le1->_nodes[0];
1112       _nn[1]=_le1->_nodes.back();
1113       _nn[2]=_le2->_nodes.back();
1114       _nn[3]=_le2->_nodes[0];
1115     }
1116     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1117     {
1118       SMESH_TNodeXYZ p0s( _nn[0] );
1119       SMESH_TNodeXYZ p0t( _nn[1] );
1120       SMESH_TNodeXYZ p1t( _nn[2] );
1121       SMESH_TNodeXYZ p1s( _nn[3] );
1122       gp_XYZ  v0 = p0t - p0s;
1123       gp_XYZ  v1 = p1t - p1s;
1124       gp_XYZ v01 = p1s - p0s;
1125       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1126       gp_XYZ   d = v01 ^ n;
1127       d.Normalize();
1128       return d;
1129     }
1130     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1131     {
1132       _nn[0]=le1->_nodes[0];
1133       _nn[1]=le1->_nodes.back();
1134       _nn[2]=le2->_nodes.back();
1135       _nn[3]=le2->_nodes[0];
1136       return GetDir();
1137     }
1138   };
1139   //--------------------------------------------------------------------------------
1140   /*!
1141    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1142    * \warning Location of a surface is ignored
1143    */
1144   struct _NodeCoordHelper
1145   {
1146     SMESH_MesherHelper&        _helper;
1147     const TopoDS_Face&         _face;
1148     Handle(Geom_Surface)       _surface;
1149     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1150
1151     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1152       : _helper( helper ), _face( F )
1153     {
1154       if ( is2D )
1155       {
1156         TopLoc_Location loc;
1157         _surface = BRep_Tool::Surface( _face, loc );
1158       }
1159       if ( _surface.IsNull() )
1160         _fun = & _NodeCoordHelper::direct;
1161       else
1162         _fun = & _NodeCoordHelper::byUV;
1163     }
1164     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1165
1166   private:
1167     gp_XYZ direct(const SMDS_MeshNode* n) const
1168     {
1169       return SMESH_TNodeXYZ( n );
1170     }
1171     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1172     {
1173       gp_XY uv = _helper.GetNodeUV( _face, n );
1174       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1175     }
1176   };
1177
1178   //================================================================================
1179   /*!
1180    * \brief Check angle between vectors 
1181    */
1182   //================================================================================
1183
1184   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1185   {
1186     double dot = v1 * v2; // cos * |v1| * |v2|
1187     double l1  = v1.SquareMagnitude();
1188     double l2  = v2.SquareMagnitude();
1189     return (( dot * cos >= 0 ) && 
1190             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1191   }
1192
1193 } // namespace VISCOUS_3D
1194
1195
1196
1197 //================================================================================
1198 // StdMeshers_ViscousLayers hypothesis
1199 //
1200 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1201   :SMESH_Hypothesis(hypId, studyId, gen),
1202    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1203    _method( SURF_OFFSET_SMOOTH )
1204 {
1205   _name = StdMeshers_ViscousLayers::GetHypType();
1206   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1207 } // --------------------------------------------------------------------------------
1208 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1209 {
1210   if ( faceIds != _shapeIds )
1211     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1212   if ( _isToIgnoreShapes != toIgnore )
1213     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1214 } // --------------------------------------------------------------------------------
1215 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1216 {
1217   if ( thickness != _thickness )
1218     _thickness = thickness, NotifySubMeshesHypothesisModification();
1219 } // --------------------------------------------------------------------------------
1220 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1221 {
1222   if ( _nbLayers != nb )
1223     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1224 } // --------------------------------------------------------------------------------
1225 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1226 {
1227   if ( _stretchFactor != factor )
1228     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1229 } // --------------------------------------------------------------------------------
1230 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1231 {
1232   if ( _method != method )
1233     _method = method, NotifySubMeshesHypothesisModification();
1234 } // --------------------------------------------------------------------------------
1235 SMESH_ProxyMesh::Ptr
1236 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1237                                   const TopoDS_Shape& theShape,
1238                                   const bool          toMakeN2NMap) const
1239 {
1240   using namespace VISCOUS_3D;
1241   _ViscousBuilder builder;
1242   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1243   if ( err && !err->IsOK() )
1244     return SMESH_ProxyMesh::Ptr();
1245
1246   vector<SMESH_ProxyMesh::Ptr> components;
1247   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1248   for ( ; exp.More(); exp.Next() )
1249   {
1250     if ( _MeshOfSolid* pm =
1251          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1252     {
1253       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1254         if ( !builder.MakeN2NMap( pm ))
1255           return SMESH_ProxyMesh::Ptr();
1256       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1257       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1258
1259       if ( pm->_warning && !pm->_warning->IsOK() )
1260       {
1261         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1262         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1263         if ( !smError || smError->IsOK() )
1264           smError = pm->_warning;
1265       }
1266     }
1267     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1268   }
1269   switch ( components.size() )
1270   {
1271   case 0: break;
1272
1273   case 1: return components[0];
1274
1275   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1276   }
1277   return SMESH_ProxyMesh::Ptr();
1278 } // --------------------------------------------------------------------------------
1279 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1280 {
1281   save << " " << _nbLayers
1282        << " " << _thickness
1283        << " " << _stretchFactor
1284        << " " << _shapeIds.size();
1285   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1286     save << " " << _shapeIds[i];
1287   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1288   save << " " << _method;
1289   return save;
1290 } // --------------------------------------------------------------------------------
1291 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1292 {
1293   int nbFaces, faceID, shapeToTreat, method;
1294   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1295   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1296     _shapeIds.push_back( faceID );
1297   if ( load >> shapeToTreat ) {
1298     _isToIgnoreShapes = !shapeToTreat;
1299     if ( load >> method )
1300       _method = (ExtrusionMethod) method;
1301   }
1302   else {
1303     _isToIgnoreShapes = true; // old behavior
1304   }
1305   return load;
1306 } // --------------------------------------------------------------------------------
1307 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1308                                                    const TopoDS_Shape& theShape)
1309 {
1310   // TODO
1311   return false;
1312 } // --------------------------------------------------------------------------------
1313 SMESH_ComputeErrorPtr
1314 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1315                                           const TopoDS_Shape&                  theShape,
1316                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1317 {
1318   VISCOUS_3D::_ViscousBuilder builder;
1319   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1320   if ( err && !err->IsOK() )
1321     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1322   else
1323     theStatus = SMESH_Hypothesis::HYP_OK;
1324
1325   return err;
1326 }
1327 // --------------------------------------------------------------------------------
1328 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1329 {
1330   bool isIn =
1331     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1332   return IsToIgnoreShapes() ? !isIn : isIn;
1333 }
1334 // END StdMeshers_ViscousLayers hypothesis
1335 //================================================================================
1336
1337 namespace VISCOUS_3D
1338 {
1339   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1340   {
1341     gp_Vec dir;
1342     double f,l;
1343     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1344     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1345     gp_Pnt p = BRep_Tool::Pnt( fromV );
1346     double distF = p.SquareDistance( c->Value( f ));
1347     double distL = p.SquareDistance( c->Value( l ));
1348     c->D1(( distF < distL ? f : l), p, dir );
1349     if ( distL < distF ) dir.Reverse();
1350     return dir.XYZ();
1351   }
1352   //--------------------------------------------------------------------------------
1353   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1354                      SMESH_MesherHelper& helper)
1355   {
1356     gp_Vec dir;
1357     double f,l; gp_Pnt p;
1358     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1359     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1360     double u = helper.GetNodeU( E, atNode );
1361     c->D1( u, p, dir );
1362     return dir.XYZ();
1363   }
1364   //--------------------------------------------------------------------------------
1365   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1366                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1367                      double* cosin=0);
1368   //--------------------------------------------------------------------------------
1369   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1370                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1371   {
1372     double f,l;
1373     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1374     if ( c.IsNull() )
1375     {
1376       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1377       return getFaceDir( F, v, node, helper, ok );
1378     }
1379     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1380     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1381     gp_Pnt p; gp_Vec du, dv, norm;
1382     surface->D1( uv.X(),uv.Y(), p, du,dv );
1383     norm = du ^ dv;
1384
1385     double u = helper.GetNodeU( fromE, node, 0, &ok );
1386     c->D1( u, p, du );
1387     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1388     if ( o == TopAbs_REVERSED )
1389       du.Reverse();
1390
1391     gp_Vec dir = norm ^ du;
1392
1393     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1394          helper.IsClosedEdge( fromE ))
1395     {
1396       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1397       else                        c->D1( f, p, dv );
1398       if ( o == TopAbs_REVERSED )
1399         dv.Reverse();
1400       gp_Vec dir2 = norm ^ dv;
1401       dir = dir.Normalized() + dir2.Normalized();
1402     }
1403     return dir.XYZ();
1404   }
1405   //--------------------------------------------------------------------------------
1406   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1407                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1408                      bool& ok, double* cosin)
1409   {
1410     TopoDS_Face faceFrw = F;
1411     faceFrw.Orientation( TopAbs_FORWARD );
1412     //double f,l; TopLoc_Location loc;
1413     TopoDS_Edge edges[2]; // sharing a vertex
1414     size_t nbEdges = 0;
1415     {
1416       TopoDS_Vertex VV[2];
1417       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1418       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1419       {
1420         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1421         if ( SMESH_Algo::isDegenerated( e )) continue;
1422         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1423         if ( VV[1].IsSame( fromV )) {
1424           nbEdges += edges[ 0 ].IsNull();
1425           edges[ 0 ] = e;
1426         }
1427         else if ( VV[0].IsSame( fromV )) {
1428           nbEdges += edges[ 1 ].IsNull();
1429           edges[ 1 ] = e;
1430         }
1431       }
1432     }
1433     gp_XYZ dir(0,0,0), edgeDir[2];
1434     if ( nbEdges == 2 )
1435     {
1436       // get dirs of edges going fromV
1437       ok = true;
1438       for ( size_t i = 0; i < nbEdges && ok; ++i )
1439       {
1440         edgeDir[i] = getEdgeDir( edges[i], fromV );
1441         double size2 = edgeDir[i].SquareModulus();
1442         if (( ok = size2 > numeric_limits<double>::min() ))
1443           edgeDir[i] /= sqrt( size2 );
1444       }
1445       if ( !ok ) return dir;
1446
1447       // get angle between the 2 edges
1448       gp_Vec faceNormal;
1449       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1450       if ( Abs( angle ) < 5 * M_PI/180 )
1451       {
1452         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1453       }
1454       else
1455       {
1456         dir = edgeDir[0] + edgeDir[1];
1457         if ( angle < 0 )
1458           dir.Reverse();
1459       }
1460       if ( cosin ) {
1461         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1462         *cosin = Cos( angle );
1463       }
1464     }
1465     else if ( nbEdges == 1 )
1466     {
1467       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1468       if ( cosin ) *cosin = 1.;
1469     }
1470     else
1471     {
1472       ok = false;
1473     }
1474
1475     return dir;
1476   }
1477
1478   //================================================================================
1479   /*!
1480    * \brief Finds concave VERTEXes of a FACE
1481    */
1482   //================================================================================
1483
1484   bool getConcaveVertices( const TopoDS_Face&  F,
1485                            SMESH_MesherHelper& helper,
1486                            set< TGeomID >*     vertices = 0)
1487   {
1488     // check angles at VERTEXes
1489     TError error;
1490     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1491     for ( size_t iW = 0; iW < wires.size(); ++iW )
1492     {
1493       const int nbEdges = wires[iW]->NbEdges();
1494       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1495         continue;
1496       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1497       {
1498         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1499         int iE2 = ( iE1 + 1 ) % nbEdges;
1500         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1501           iE2 = ( iE2 + 1 ) % nbEdges;
1502         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1503         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1504                                         wires[iW]->Edge( iE2 ), F, V );
1505         if ( angle < -5. * M_PI / 180. )
1506         {
1507           if ( !vertices )
1508             return true;
1509           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1510         }
1511       }
1512     }
1513     return vertices ? !vertices->empty() : false;
1514   }
1515
1516   //================================================================================
1517   /*!
1518    * \brief Returns true if a FACE is bound by a concave EDGE
1519    */
1520   //================================================================================
1521
1522   bool isConcave( const TopoDS_Face&  F,
1523                   SMESH_MesherHelper& helper,
1524                   set< TGeomID >*     vertices = 0 )
1525   {
1526     bool isConcv = false;
1527     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1528     //   return true;
1529     gp_Vec2d drv1, drv2;
1530     gp_Pnt2d p;
1531     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1532     for ( ; eExp.More(); eExp.Next() )
1533     {
1534       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1535       if ( SMESH_Algo::isDegenerated( E )) continue;
1536       // check if 2D curve is concave
1537       BRepAdaptor_Curve2d curve( E, F );
1538       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1539       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1540       curve.Intervals( intervals, GeomAbs_C2 );
1541       bool isConvex = true;
1542       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1543       {
1544         double u1 = intervals( i );
1545         double u2 = intervals( i+1 );
1546         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1547         double cross = drv1 ^ drv2;
1548         if ( E.Orientation() == TopAbs_REVERSED )
1549           cross = -cross;
1550         isConvex = ( cross > -1e-9 ); // 0.1 );
1551       }
1552       if ( !isConvex )
1553       {
1554         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1555         isConcv = true;
1556         if ( vertices )
1557           break;
1558         else
1559           return true;
1560       }
1561     }
1562
1563     // check angles at VERTEXes
1564     if ( getConcaveVertices( F, helper, vertices ))
1565       isConcv = true;
1566
1567     return isConcv;
1568   }
1569
1570   //================================================================================
1571   /*!
1572    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1573    *  \param [in] face - the mesh face to treat
1574    *  \param [in] nodeOnEdge - a node on the EDGE
1575    *  \param [out] faceSize - the computed distance
1576    *  \return bool - true if faceSize computed
1577    */
1578   //================================================================================
1579
1580   bool getDistFromEdge( const SMDS_MeshElement* face,
1581                         const SMDS_MeshNode*    nodeOnEdge,
1582                         double &                faceSize )
1583   {
1584     faceSize = Precision::Infinite();
1585     bool done = false;
1586
1587     int nbN  = face->NbCornerNodes();
1588     int iOnE = face->GetNodeIndex( nodeOnEdge );
1589     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1590                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1591     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1592                                       face->GetNode( iNext[1] ) };
1593     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1594     double segLen = -1.;
1595     // look for two neighbor not in-FACE nodes of face
1596     for ( int i = 0; i < 2; ++i )
1597     {
1598       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1599            nNext[i]->GetID() < nodeOnEdge->GetID() )
1600       {
1601         // look for an in-FACE node
1602         for ( int iN = 0; iN < nbN; ++iN )
1603         {
1604           if ( iN == iOnE || iN == iNext[i] )
1605             continue;
1606           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1607           gp_XYZ v = pInFace - segEnd;
1608           if ( segLen < 0 )
1609           {
1610             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1611             segLen = segVec.Modulus();
1612           }
1613           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1614           faceSize = Min( faceSize, distToSeg );
1615           done = true;
1616         }
1617         segLen = -1;
1618       }
1619     }
1620     return done;
1621   }
1622   //================================================================================
1623   /*!
1624    * \brief Return direction of axis or revolution of a surface
1625    */
1626   //================================================================================
1627
1628   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1629                           gp_Dir &                 axis )
1630   {
1631     switch ( surface.GetType() ) {
1632     case GeomAbs_Cone:
1633     {
1634       gp_Cone cone = surface.Cone();
1635       axis = cone.Axis().Direction();
1636       break;
1637     }
1638     case GeomAbs_Sphere:
1639     {
1640       gp_Sphere sphere = surface.Sphere();
1641       axis = sphere.Position().Direction();
1642       break;
1643     }
1644     case GeomAbs_SurfaceOfRevolution:
1645     {
1646       axis = surface.AxeOfRevolution().Direction();
1647       break;
1648     }
1649     //case GeomAbs_SurfaceOfExtrusion:
1650     case GeomAbs_OffsetSurface:
1651     {
1652       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1653       return getRovolutionAxis( base->Surface(), axis );
1654     }
1655     default: return false;
1656     }
1657     return true;
1658   }
1659
1660   //--------------------------------------------------------------------------------
1661   // DEBUG. Dump intermediate node positions into a python script
1662   // HOWTO use: run python commands written in a console to see
1663   //  construction steps of viscous layers
1664 #ifdef __myDEBUG
1665   ofstream* py;
1666   int       theNbPyFunc;
1667   struct PyDump {
1668     PyDump(SMESH_Mesh& m) {
1669       int tag = 3 + m.GetId();
1670       const char* fname = "/tmp/viscous.py";
1671       cout << "execfile('"<<fname<<"')"<<endl;
1672       py = new ofstream(fname);
1673       *py << "import SMESH" << endl
1674           << "from salome.smesh import smeshBuilder" << endl
1675           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1676           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1677           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1678       theNbPyFunc = 0;
1679     }
1680     void Finish() {
1681       if (py) {
1682         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1683           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1684         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1685           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1686       }
1687       delete py; py=0;
1688     }
1689     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1690   };
1691 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1692 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1693 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1694 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1695   void _dumpFunction(const string& fun, int ln)
1696   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1697   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1698   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1699                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1700   void _dumpCmd(const string& txt, int ln)
1701   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1702   void dumpFunctionEnd()
1703   { if (py) *py<< "  return"<< endl; }
1704   void dumpChangeNodes( const SMDS_MeshElement* f )
1705   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1706       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1707       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1708 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1709
1710 #else
1711
1712   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1713 #define dumpFunction(f) f
1714 #define dumpMove(n)
1715 #define dumpMoveComm(n,txt)
1716 #define dumpCmd(txt)
1717 #define dumpFunctionEnd()
1718 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1719 #define debugMsg( txt ) {}
1720
1721 #endif
1722 }
1723
1724 using namespace VISCOUS_3D;
1725
1726 //================================================================================
1727 /*!
1728  * \brief Constructor of _ViscousBuilder
1729  */
1730 //================================================================================
1731
1732 _ViscousBuilder::_ViscousBuilder()
1733 {
1734   _error = SMESH_ComputeError::New(COMPERR_OK);
1735   _tmpFaceID = 0;
1736 }
1737
1738 //================================================================================
1739 /*!
1740  * \brief Stores error description and returns false
1741  */
1742 //================================================================================
1743
1744 bool _ViscousBuilder::error(const string& text, int solidId )
1745 {
1746   const string prefix = string("Viscous layers builder: ");
1747   _error->myName    = COMPERR_ALGO_FAILED;
1748   _error->myComment = prefix + text;
1749   if ( _mesh )
1750   {
1751     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1752     if ( !sm && !_sdVec.empty() )
1753       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1754     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1755     {
1756       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1757       if ( smError && smError->myAlgo )
1758         _error->myAlgo = smError->myAlgo;
1759       smError = _error;
1760       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1761     }
1762     // set KO to all solids
1763     for ( size_t i = 0; i < _sdVec.size(); ++i )
1764     {
1765       if ( _sdVec[i]._index == solidId )
1766         continue;
1767       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1768       if ( !sm->IsEmpty() )
1769         continue;
1770       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1771       if ( !smError || smError->IsOK() )
1772       {
1773         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1774         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1775       }
1776     }
1777   }
1778   makeGroupOfLE(); // debug
1779
1780   return false;
1781 }
1782
1783 //================================================================================
1784 /*!
1785  * \brief At study restoration, restore event listeners used to clear an inferior
1786  *  dim sub-mesh modified by viscous layers
1787  */
1788 //================================================================================
1789
1790 void _ViscousBuilder::RestoreListeners()
1791 {
1792   // TODO
1793 }
1794
1795 //================================================================================
1796 /*!
1797  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1798  */
1799 //================================================================================
1800
1801 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1802 {
1803   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1804   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1805   for ( ; fExp.More(); fExp.Next() )
1806   {
1807     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1808     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1809
1810     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1811       continue;
1812     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1813       continue;
1814
1815     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1816       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1817
1818     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1819     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1820     while( prxIt->more() )
1821     {
1822       const SMDS_MeshElement* fSrc = srcIt->next();
1823       const SMDS_MeshElement* fPrx = prxIt->next();
1824       if ( fSrc->NbNodes() != fPrx->NbNodes())
1825         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1826       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1827         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1828     }
1829   }
1830   pm->_n2nMapComputed = true;
1831   return true;
1832 }
1833
1834 //================================================================================
1835 /*!
1836  * \brief Does its job
1837  */
1838 //================================================================================
1839
1840 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1841                                                const TopoDS_Shape& theShape)
1842 {
1843   _mesh = & theMesh;
1844
1845   // check if proxy mesh already computed
1846   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1847   if ( !exp.More() )
1848     return error("No SOLID's in theShape"), _error;
1849
1850   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1851     return SMESH_ComputeErrorPtr(); // everything already computed
1852
1853   PyDump debugDump( theMesh );
1854
1855   // TODO: ignore already computed SOLIDs 
1856   if ( !findSolidsWithLayers())
1857     return _error;
1858
1859   if ( !findFacesWithLayers() )
1860     return _error;
1861
1862   for ( size_t i = 0; i < _sdVec.size(); ++i )
1863   {
1864     size_t iSD = 0;
1865     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1866       if ( _sdVec[iSD]._before.IsEmpty() &&
1867            _sdVec[iSD]._n2eMap.empty() )
1868         break;
1869
1870     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1871       return _error;
1872
1873     if ( _sdVec[iSD]._n2eMap.size() == 0 )
1874       continue;
1875     
1876     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1877       return _error;
1878
1879     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1880       return _error;
1881
1882     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1883       return _error;
1884
1885     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1886
1887     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1888     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1889       _sdVec[iSD]._before.Remove( solid );
1890   }
1891
1892   makeGroupOfLE(); // debug
1893   debugDump.Finish();
1894
1895   return _error;
1896 }
1897
1898 //================================================================================
1899 /*!
1900  * \brief Check validity of hypotheses
1901  */
1902 //================================================================================
1903
1904 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1905                                                         const TopoDS_Shape& shape )
1906 {
1907   _mesh = & mesh;
1908
1909   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1910     return SMESH_ComputeErrorPtr(); // everything already computed
1911
1912
1913   findSolidsWithLayers();
1914   bool ok = findFacesWithLayers( true );
1915
1916   // remove _MeshOfSolid's of _SolidData's
1917   for ( size_t i = 0; i < _sdVec.size(); ++i )
1918     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1919
1920   if ( !ok )
1921     return _error;
1922
1923   return SMESH_ComputeErrorPtr();
1924 }
1925
1926 //================================================================================
1927 /*!
1928  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1929  */
1930 //================================================================================
1931
1932 bool _ViscousBuilder::findSolidsWithLayers()
1933 {
1934   // get all solids
1935   TopTools_IndexedMapOfShape allSolids;
1936   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1937   _sdVec.reserve( allSolids.Extent());
1938
1939   SMESH_HypoFilter filter;
1940   for ( int i = 1; i <= allSolids.Extent(); ++i )
1941   {
1942     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1943     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1944     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1945       continue; // solid is already meshed
1946     SMESH_Algo* algo = sm->GetAlgo();
1947     if ( !algo ) continue;
1948     // TODO: check if algo is hidden
1949     const list <const SMESHDS_Hypothesis *> & allHyps =
1950       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1951     _SolidData* soData = 0;
1952     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1953     const StdMeshers_ViscousLayers* viscHyp = 0;
1954     for ( ; hyp != allHyps.end(); ++hyp )
1955       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1956       {
1957         TopoDS_Shape hypShape;
1958         filter.Init( filter.Is( viscHyp ));
1959         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1960
1961         if ( !soData )
1962         {
1963           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1964                                                                     allSolids(i),
1965                                                                     /*toCreate=*/true);
1966           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1967           soData = & _sdVec.back();
1968           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1969           soData->_helper = new SMESH_MesherHelper( *_mesh );
1970           soData->_helper->SetSubShape( allSolids(i) );
1971           _solids.Add( allSolids(i) );
1972         }
1973         soData->_hyps.push_back( viscHyp );
1974         soData->_hypShapes.push_back( hypShape );
1975       }
1976   }
1977   if ( _sdVec.empty() )
1978     return error
1979       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1980
1981   return true;
1982 }
1983
1984 //================================================================================
1985 /*!
1986  * \brief Set a _SolidData to be computed before another
1987  */
1988 //================================================================================
1989
1990 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1991 {
1992   // check possibility to set this order; get all solids before solidBefore
1993   TopTools_IndexedMapOfShape allSolidsBefore;
1994   allSolidsBefore.Add( solidBefore._solid );
1995   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1996   {
1997     int iSD = _solids.FindIndex( allSolidsBefore(i) );
1998     if ( iSD )
1999     {
2000       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2001       for ( ; soIt.More(); soIt.Next() )
2002         allSolidsBefore.Add( soIt.Value() );
2003     }
2004   }
2005   if ( allSolidsBefore.Contains( solidAfter._solid ))
2006     return false;
2007
2008   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2009     solidAfter._before.Add( allSolidsBefore(i) );
2010
2011   return true;
2012 }
2013
2014 //================================================================================
2015 /*!
2016  * \brief
2017  */
2018 //================================================================================
2019
2020 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2021 {
2022   SMESH_MesherHelper helper( *_mesh );
2023   TopExp_Explorer exp;
2024
2025   // collect all faces-to-ignore defined by hyp
2026   for ( size_t i = 0; i < _sdVec.size(); ++i )
2027   {
2028     // get faces-to-ignore defined by each hyp
2029     typedef const StdMeshers_ViscousLayers* THyp;
2030     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2031     list< TFacesOfHyp > ignoreFacesOfHyps;
2032     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2033     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2034     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2035     {
2036       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2037       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2038     }
2039
2040     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2041     const int nbHyps = _sdVec[i]._hyps.size();
2042     if ( nbHyps > 1 )
2043     {
2044       // check if two hypotheses define different parameters for the same FACE
2045       list< TFacesOfHyp >::iterator igFacesOfHyp;
2046       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2047       {
2048         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2049         THyp hyp = 0;
2050         igFacesOfHyp = ignoreFacesOfHyps.begin();
2051         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2052           if ( ! igFacesOfHyp->first.count( faceID ))
2053           {
2054             if ( hyp )
2055               return error(SMESH_Comment("Several hypotheses define "
2056                                          "Viscous Layers on the face #") << faceID );
2057             hyp = igFacesOfHyp->second;
2058           }
2059         if ( hyp )
2060           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2061         else
2062           _sdVec[i]._ignoreFaceIds.insert( faceID );
2063       }
2064
2065       // check if two hypotheses define different number of viscous layers for
2066       // adjacent faces of a solid
2067       set< int > nbLayersSet;
2068       igFacesOfHyp = ignoreFacesOfHyps.begin();
2069       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2070       {
2071         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2072       }
2073       if ( nbLayersSet.size() > 1 )
2074       {
2075         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2076         {
2077           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2078           THyp hyp1 = 0, hyp2 = 0;
2079           while( const TopoDS_Shape* face = fIt->next() )
2080           {
2081             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2082             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2083             if ( f2h != _sdVec[i]._face2hyp.end() )
2084             {
2085               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2086             }
2087           }
2088           if ( hyp1 && hyp2 &&
2089                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2090           {
2091             return error("Two hypotheses define different number of "
2092                          "viscous layers on adjacent faces");
2093           }
2094         }
2095       }
2096     } // if ( nbHyps > 1 )
2097     else
2098     {
2099       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2100     }
2101   } // loop on _sdVec
2102
2103   if ( onlyWith ) // is called to check hypotheses compatibility only
2104     return true;
2105
2106   // fill _SolidData::_reversedFaceIds
2107   for ( size_t i = 0; i < _sdVec.size(); ++i )
2108   {
2109     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2110     for ( ; exp.More(); exp.Next() )
2111     {
2112       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2113       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2114       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2115           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2116           helper.IsReversedSubMesh( face ))
2117       {
2118         _sdVec[i]._reversedFaceIds.insert( faceID );
2119       }
2120     }
2121   }
2122
2123   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2124   TopTools_IndexedMapOfShape shapes;
2125   std::string structAlgoName = "Hexa_3D";
2126   for ( size_t i = 0; i < _sdVec.size(); ++i )
2127   {
2128     shapes.Clear();
2129     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2130     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2131     {
2132       const TopoDS_Shape& edge = shapes(iE);
2133       // find 2 FACEs sharing an EDGE
2134       TopoDS_Shape FF[2];
2135       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2136       while ( fIt->more())
2137       {
2138         const TopoDS_Shape* f = fIt->next();
2139         FF[ int( !FF[0].IsNull()) ] = *f;
2140       }
2141       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2142
2143       // check presence of layers on them
2144       int ignore[2];
2145       for ( int j = 0; j < 2; ++j )
2146         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2147       if ( ignore[0] == ignore[1] )
2148         continue; // nothing interesting
2149       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2150
2151       // add EDGE to maps
2152       if ( !fWOL.IsNull())
2153       {
2154         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2155         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2156       }
2157     }
2158   }
2159
2160   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2161
2162   for ( size_t i = 0; i < _sdVec.size(); ++i )
2163   {
2164     shapes.Clear();
2165     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2166     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2167     {
2168       const TopoDS_Shape& vertex = shapes(iV);
2169       // find faces WOL sharing the vertex
2170       vector< TopoDS_Shape > facesWOL;
2171       size_t totalNbFaces = 0;
2172       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2173       while ( fIt->more())
2174       {
2175         const TopoDS_Shape* f = fIt->next();
2176         totalNbFaces++;
2177         const int fID = getMeshDS()->ShapeToIndex( *f );
2178         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2179           facesWOL.push_back( *f );
2180       }
2181       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2182         continue; // no layers at this vertex or no WOL
2183       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2184       switch ( facesWOL.size() )
2185       {
2186       case 1:
2187       {
2188         helper.SetSubShape( facesWOL[0] );
2189         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2190         {
2191           TopoDS_Shape seamEdge;
2192           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2193           while ( eIt->more() && seamEdge.IsNull() )
2194           {
2195             const TopoDS_Shape* e = eIt->next();
2196             if ( helper.IsRealSeam( *e ) )
2197               seamEdge = *e;
2198           }
2199           if ( !seamEdge.IsNull() )
2200           {
2201             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2202             break;
2203           }
2204         }
2205         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2206         break;
2207       }
2208       case 2:
2209       {
2210         // find an edge shared by 2 faces
2211         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2212         while ( eIt->more())
2213         {
2214           const TopoDS_Shape* e = eIt->next();
2215           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2216                helper.IsSubShape( *e, facesWOL[1]))
2217           {
2218             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2219           }
2220         }
2221         break;
2222       }
2223       default:
2224         return error("Not yet supported case", _sdVec[i]._index);
2225       }
2226     }
2227   }
2228
2229   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2230   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2231   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2232   for ( size_t i = 0; i < _sdVec.size(); ++i )
2233   {
2234     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2235     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2236     {
2237       const TopoDS_Shape& fWOL = e2f->second;
2238       const TGeomID     edgeID = e2f->first;
2239       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2240       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2241       if ( edge.ShapeType() != TopAbs_EDGE )
2242         continue; // shrink shape is VERTEX
2243
2244       TopoDS_Shape solid;
2245       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2246       while ( soIt->more() && solid.IsNull() )
2247       {
2248         const TopoDS_Shape* so = soIt->next();
2249         if ( !so->IsSame( _sdVec[i]._solid ))
2250           solid = *so;
2251       }
2252       if ( solid.IsNull() )
2253         continue;
2254
2255       bool noShrinkE = false;
2256       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2257       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2258       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2259       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2260       {
2261         // the adjacent SOLID has NO layers on fWOL;
2262         // shrink allowed if
2263         // - there are layers on the EDGE in the adjacent SOLID
2264         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2265         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2266         bool shrinkAllowed = (( hasWLAdj ) ||
2267                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2268         noShrinkE = !shrinkAllowed;
2269       }
2270       else if ( iSolid < _sdVec.size() )
2271       {
2272         // the adjacent SOLID has layers on fWOL;
2273         // check if SOLID's mesh is unstructured and then try to set it
2274         // to be computed after the i-th solid
2275         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2276           noShrinkE = true; // don't shrink fWOL
2277       }
2278       else
2279       {
2280         // the adjacent SOLID has NO layers at all
2281         noShrinkE = isStructured;
2282       }
2283
2284       if ( noShrinkE )
2285       {
2286         _sdVec[i]._noShrinkShapes.insert( edgeID );
2287
2288         // check if there is a collision with to-shrink-from EDGEs in iSolid
2289         // if ( iSolid < _sdVec.size() )
2290         // {
2291         //   shapes.Clear();
2292         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2293         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2294         //   {
2295         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2296         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2297         //     if ( eID == edgeID ||
2298         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2299         //          _sdVec[i]._noShrinkShapes.count( eID ))
2300         //       continue;
2301         //     for ( int is1st = 0; is1st < 2; ++is1st )
2302         //     {
2303         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2304         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2305         //       {
2306         //         return error("No way to make a conformal mesh with "
2307         //                      "the given set of faces with layers", _sdVec[i]._index);
2308         //       }
2309         //     }
2310         //   }
2311         // }
2312       }
2313
2314       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2315       // _shrinkShape2Shape is different in the adjacent SOLID
2316       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2317       {
2318         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2319         bool noShrinkV = false;
2320
2321         if ( iSolid < _sdVec.size() )
2322         {
2323           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2324           {
2325             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2326             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2327             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2328             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2329               noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2330             else
2331               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2332           }
2333           else
2334           {
2335             noShrinkV = noShrinkE;
2336           }
2337         }
2338         else
2339         {
2340           // the adjacent SOLID has NO layers at all
2341           noShrinkV = ( isStructured ||
2342                         _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2343         }
2344         if ( noShrinkV )
2345           _sdVec[i]._noShrinkShapes.insert( vID );
2346       }
2347
2348     } // loop on _sdVec[i]._shrinkShape2Shape
2349   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2350
2351
2352     // add FACEs of other SOLIDs to _ignoreFaceIds
2353   for ( size_t i = 0; i < _sdVec.size(); ++i )
2354   {
2355     shapes.Clear();
2356     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2357
2358     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2359     {
2360       if ( !shapes.Contains( exp.Current() ))
2361         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2362     }
2363   }
2364
2365   return true;
2366 }
2367
2368 //================================================================================
2369 /*!
2370  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2371  */
2372 //================================================================================
2373
2374 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2375                                      const StdMeshers_ViscousLayers* hyp,
2376                                      const TopoDS_Shape&             hypShape,
2377                                      set<TGeomID>&                   ignoreFaceIds)
2378 {
2379   TopExp_Explorer exp;
2380
2381   vector<TGeomID> ids = hyp->GetBndShapes();
2382   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2383   {
2384     for ( size_t ii = 0; ii < ids.size(); ++ii )
2385     {
2386       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2387       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2388         ignoreFaceIds.insert( ids[ii] );
2389     }
2390   }
2391   else // FACEs with layers are given
2392   {
2393     exp.Init( solid, TopAbs_FACE );
2394     for ( ; exp.More(); exp.Next() )
2395     {
2396       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2397       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2398         ignoreFaceIds.insert( faceInd );
2399     }
2400   }
2401
2402   // ignore internal FACEs if inlets and outlets are specified
2403   if ( hyp->IsToIgnoreShapes() )
2404   {
2405     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2406     TopExp::MapShapesAndAncestors( hypShape,
2407                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2408
2409     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2410     {
2411       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2412       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2413         continue;
2414
2415       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2416       if ( nbSolids > 1 )
2417         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2418     }
2419   }
2420 }
2421
2422 //================================================================================
2423 /*!
2424  * \brief Create the inner surface of the viscous layer and prepare data for infation
2425  */
2426 //================================================================================
2427
2428 bool _ViscousBuilder::makeLayer(_SolidData& data)
2429 {
2430   // get all sub-shapes to make layers on
2431   set<TGeomID> subIds, faceIds;
2432   subIds = data._noShrinkShapes;
2433   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2434   for ( ; exp.More(); exp.Next() )
2435   {
2436     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2437     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2438       faceIds.insert( fSubM->GetId() );
2439   }
2440
2441   // make a map to find new nodes on sub-shapes shared with other SOLID
2442   map< TGeomID, TNode2Edge* >::iterator s2ne;
2443   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2444   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2445   {
2446     TGeomID shapeInd = s2s->first;
2447     for ( size_t i = 0; i < _sdVec.size(); ++i )
2448     {
2449       if ( _sdVec[i]._index == data._index ) continue;
2450       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2451       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2452            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2453       {
2454         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2455         break;
2456       }
2457     }
2458   }
2459
2460   // Create temporary faces and _LayerEdge's
2461
2462   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2463
2464   data._stepSize = Precision::Infinite();
2465   data._stepSizeNodes[0] = 0;
2466
2467   SMESH_MesherHelper helper( *_mesh );
2468   helper.SetSubShape( data._solid );
2469   helper.SetElementsOnShape( true );
2470
2471   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2472   TNode2Edge::iterator n2e2;
2473
2474   // collect _LayerEdge's of shapes they are based on
2475   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2476   const int nbShapes = getMeshDS()->MaxShapeIndex();
2477   edgesByGeom.resize( nbShapes+1 );
2478
2479   // set data of _EdgesOnShape's
2480   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2481   {
2482     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2483     while ( smIt->more() )
2484     {
2485       sm = smIt->next();
2486       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2487            !faceIds.count( sm->GetId() ))
2488         continue;
2489       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2490     }
2491   }
2492   // make _LayerEdge's
2493   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2494   {
2495     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2496     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2497     SMESH_ProxyMesh::SubMesh* proxySub =
2498       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2499
2500     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2501     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2502
2503     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2504     while ( eIt->more() )
2505     {
2506       const SMDS_MeshElement* face = eIt->next();
2507       double          faceMaxCosin = -1;
2508       _LayerEdge*     maxCosinEdge = 0;
2509       int             nbDegenNodes = 0;
2510
2511       newNodes.resize( face->NbCornerNodes() );
2512       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2513       {
2514         const SMDS_MeshNode* n = face->GetNode( i );
2515         const int      shapeID = n->getshapeId();
2516         const bool onDegenShap = helper.IsDegenShape( shapeID );
2517         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2518         if ( onDegenShap )
2519         {
2520           if ( onDegenEdge )
2521           {
2522             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2523             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2524             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2525             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2526               n = vN;
2527               nbDegenNodes++;
2528             }
2529           }
2530           else
2531           {
2532             nbDegenNodes++;
2533           }
2534         }
2535         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2536         if ( !(*n2e).second )
2537         {
2538           // add a _LayerEdge
2539           _LayerEdge* edge = new _LayerEdge();
2540           edge->_nodes.push_back( n );
2541           n2e->second = edge;
2542           edgesByGeom[ shapeID ]._edges.push_back( edge );
2543           const bool noShrink = data._noShrinkShapes.count( shapeID );
2544
2545           SMESH_TNodeXYZ xyz( n );
2546
2547           // set edge data or find already refined _LayerEdge and get data from it
2548           if (( !noShrink                                                     ) &&
2549               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2550               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2551               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2552           {
2553             _LayerEdge* foundEdge = (*n2e2).second;
2554             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2555             foundEdge->_pos.push_back( lastPos );
2556             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2557             const_cast< SMDS_MeshNode* >
2558               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2559           }
2560           else
2561           {
2562             if ( !noShrink )
2563             {
2564               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2565             }
2566             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2567               return false;
2568
2569             if ( edge->_nodes.size() < 2 )
2570               edge->Block( data );
2571               //data._noShrinkShapes.insert( shapeID );
2572           }
2573           dumpMove(edge->_nodes.back());
2574
2575           if ( edge->_cosin > faceMaxCosin )
2576           {
2577             faceMaxCosin = edge->_cosin;
2578             maxCosinEdge = edge;
2579           }
2580         }
2581         newNodes[ i ] = n2e->second->_nodes.back();
2582
2583         if ( onDegenEdge )
2584           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2585       }
2586       if ( newNodes.size() - nbDegenNodes < 2 )
2587         continue;
2588
2589       // create a temporary face
2590       const SMDS_MeshElement* newFace =
2591         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2592       proxySub->AddElement( newFace );
2593
2594       // compute inflation step size by min size of element on a convex surface
2595       if ( faceMaxCosin > theMinSmoothCosin )
2596         limitStepSize( data, face, maxCosinEdge );
2597
2598     } // loop on 2D elements on a FACE
2599   } // loop on FACEs of a SOLID to create _LayerEdge's
2600
2601
2602   // Set _LayerEdge::_neibors
2603   TNode2Edge::iterator n2e;
2604   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2605   {
2606     _EdgesOnShape& eos = data._edgesOnShape[iS];
2607     for ( size_t i = 0; i < eos._edges.size(); ++i )
2608     {
2609       _LayerEdge* edge = eos._edges[i];
2610       TIDSortedNodeSet nearNodes;
2611       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2612       while ( fIt->more() )
2613       {
2614         const SMDS_MeshElement* f = fIt->next();
2615         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2616           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2617       }
2618       nearNodes.erase( edge->_nodes[0] );
2619       edge->_neibors.reserve( nearNodes.size() );
2620       TIDSortedNodeSet::iterator node = nearNodes.begin();
2621       for ( ; node != nearNodes.end(); ++node )
2622         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2623           edge->_neibors.push_back( n2e->second );
2624     }
2625   }
2626
2627   data._epsilon = 1e-7;
2628   if ( data._stepSize < 1. )
2629     data._epsilon *= data._stepSize;
2630
2631   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2632     return false;
2633
2634   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2635   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2636
2637   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2638   const SMDS_MeshNode* nn[2];
2639   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2640   {
2641     _EdgesOnShape& eos = data._edgesOnShape[iS];
2642     for ( size_t i = 0; i < eos._edges.size(); ++i )
2643     {
2644       _LayerEdge* edge = eos._edges[i];
2645       if ( edge->IsOnEdge() )
2646       {
2647         // get neighbor nodes
2648         bool hasData = ( edge->_2neibors->_edges[0] );
2649         if ( hasData ) // _LayerEdge is a copy of another one
2650         {
2651           nn[0] = edge->_2neibors->srcNode(0);
2652           nn[1] = edge->_2neibors->srcNode(1);
2653         }
2654         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2655         {
2656           return false;
2657         }
2658         // set neighbor _LayerEdge's
2659         for ( int j = 0; j < 2; ++j )
2660         {
2661           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2662             return error("_LayerEdge not found by src node", data._index);
2663           edge->_2neibors->_edges[j] = n2e->second;
2664         }
2665         if ( !hasData )
2666           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2667       }
2668
2669       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2670       {
2671         _Simplex& s = edge->_simplices[j];
2672         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2673         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2674       }
2675
2676       // For an _LayerEdge on a degenerated EDGE, copy some data from
2677       // a corresponding _LayerEdge on a VERTEX
2678       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2679       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2680       {
2681         // Generally we should not get here
2682         if ( eos.ShapeType() != TopAbs_EDGE )
2683           continue;
2684         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2685         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2686         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2687           continue;
2688         const _LayerEdge* vEdge = n2e->second;
2689         edge->_normal    = vEdge->_normal;
2690         edge->_lenFactor = vEdge->_lenFactor;
2691         edge->_cosin     = vEdge->_cosin;
2692       }
2693
2694     } // loop on data._edgesOnShape._edges
2695   } // loop on data._edgesOnShape
2696
2697   // fix _LayerEdge::_2neibors on EDGEs to smooth
2698   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2699   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2700   //   if ( !e2c->second.IsNull() )
2701   //   {
2702   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2703   //       data.Sort2NeiborsOnEdge( eos->_edges );
2704   //   }
2705
2706   dumpFunctionEnd();
2707   return true;
2708 }
2709
2710 //================================================================================
2711 /*!
2712  * \brief Compute inflation step size by min size of element on a convex surface
2713  */
2714 //================================================================================
2715
2716 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2717                                      const SMDS_MeshElement* face,
2718                                      const _LayerEdge*       maxCosinEdge )
2719 {
2720   int iN = 0;
2721   double minSize = 10 * data._stepSize;
2722   const int nbNodes = face->NbCornerNodes();
2723   for ( int i = 0; i < nbNodes; ++i )
2724   {
2725     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2726     const SMDS_MeshNode*  curN = face->GetNode( i );
2727     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2728          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2729     {
2730       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2731       if ( dist < minSize )
2732         minSize = dist, iN = i;
2733     }
2734   }
2735   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2736   if ( newStep < data._stepSize )
2737   {
2738     data._stepSize = newStep;
2739     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2740     data._stepSizeNodes[0] = face->GetNode( iN );
2741     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2742   }
2743 }
2744
2745 //================================================================================
2746 /*!
2747  * \brief Compute inflation step size by min size of element on a convex surface
2748  */
2749 //================================================================================
2750
2751 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2752 {
2753   if ( minSize < data._stepSize )
2754   {
2755     data._stepSize = minSize;
2756     if ( data._stepSizeNodes[0] )
2757     {
2758       double dist =
2759         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2760       data._stepSizeCoeff = data._stepSize / dist;
2761     }
2762   }
2763 }
2764
2765 //================================================================================
2766 /*!
2767  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2768  */
2769 //================================================================================
2770
2771 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2772 {
2773   SMESH_MesherHelper helper( *_mesh );
2774
2775   const int nbTestPnt = 5; // on a FACE sub-shape
2776
2777   BRepLProp_SLProps surfProp( 2, 1e-6 );
2778   data._convexFaces.clear();
2779
2780   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2781   {
2782     _EdgesOnShape& eof = data._edgesOnShape[iS];
2783     if ( eof.ShapeType() != TopAbs_FACE ||
2784          data._ignoreFaceIds.count( eof._shapeID ))
2785       continue;
2786
2787     TopoDS_Face        F = TopoDS::Face( eof._shape );
2788     SMESH_subMesh *   sm = eof._subMesh;
2789     const TGeomID faceID = eof._shapeID;
2790
2791     BRepAdaptor_Surface surface( F, false );
2792     surfProp.SetSurface( surface );
2793
2794     bool isTooCurved = false;
2795
2796     _ConvexFace cnvFace;
2797     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2798     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2799     while ( smIt->more() )
2800     {
2801       sm = smIt->next();
2802       const TGeomID subID = sm->GetId();
2803       // find _LayerEdge's of a sub-shape
2804       _EdgesOnShape* eos;
2805       if (( eos = data.GetShapeEdges( subID )))
2806         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2807       else
2808         continue;
2809       // check concavity and curvature and limit data._stepSize
2810       const double minCurvature =
2811         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2812       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2813       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2814       {
2815         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2816         surfProp.SetParameters( uv.X(), uv.Y() );
2817         if ( !surfProp.IsCurvatureDefined() )
2818           continue;
2819         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2820         {
2821           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2822           isTooCurved = true;
2823         }
2824         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2825         {
2826           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2827           isTooCurved = true;
2828         }
2829       }
2830     } // loop on sub-shapes of the FACE
2831
2832     if ( !isTooCurved ) continue;
2833
2834     _ConvexFace & convFace =
2835       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2836
2837     convFace._face = F;
2838     convFace._normalsFixed = false;
2839
2840     // skip a closed surface (data._convexFaces is useful anyway)
2841     bool isClosedF = false;
2842     helper.SetSubShape( F );
2843     if ( helper.HasRealSeam() )
2844     {
2845       // in the closed surface there must be a closed EDGE
2846       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2847         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2848     }
2849     if ( isClosedF )
2850     {
2851       // limit _LayerEdge::_maxLen on the FACE
2852       const double minCurvature =
2853         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2854       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2855       if ( id2eos != cnvFace._subIdToEOS.end() )
2856       {
2857         _EdgesOnShape& eos = * id2eos->second;
2858         for ( size_t i = 0; i < eos._edges.size(); ++i )
2859         {
2860           _LayerEdge* ledge = eos._edges[ i ];
2861           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2862           surfProp.SetParameters( uv.X(), uv.Y() );
2863           if ( !surfProp.IsCurvatureDefined() )
2864             continue;
2865
2866           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2867             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2868
2869           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2870             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2871         }
2872       }
2873       continue;
2874     }
2875
2876     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2877     // prism distortion.
2878     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2879     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2880     {
2881       // there are _LayerEdge's on the FACE it-self;
2882       // select _LayerEdge's near EDGEs
2883       _EdgesOnShape& eos = * id2eos->second;
2884       for ( size_t i = 0; i < eos._edges.size(); ++i )
2885       {
2886         _LayerEdge* ledge = eos._edges[ i ];
2887         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2888           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2889           {
2890             convFace._simplexTestEdges.push_back( ledge );
2891             break;
2892           }
2893       }
2894     }
2895     else
2896     {
2897       // where there are no _LayerEdge's on a _ConvexFace,
2898       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2899       // so that collision of viscous internal faces is not detected by check of
2900       // intersection of _LayerEdge's with the viscous internal faces.
2901
2902       set< const SMDS_MeshNode* > usedNodes;
2903
2904       // look for _LayerEdge's with null _sWOL
2905       id2eos = convFace._subIdToEOS.begin();
2906       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2907       {
2908         _EdgesOnShape& eos = * id2eos->second;
2909         if ( !eos._sWOL.IsNull() )
2910           continue;
2911         for ( size_t i = 0; i < eos._edges.size(); ++i )
2912         {
2913           _LayerEdge* ledge = eos._edges[ i ];
2914           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2915           if ( !usedNodes.insert( srcNode ).second ) continue;
2916
2917           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2918           {
2919             usedNodes.insert( ledge->_simplices[i]._nPrev );
2920             usedNodes.insert( ledge->_simplices[i]._nNext );
2921           }
2922           convFace._simplexTestEdges.push_back( ledge );
2923         }
2924       }
2925     }
2926   } // loop on FACEs of data._solid
2927 }
2928
2929 //================================================================================
2930 /*!
2931  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2932  */
2933 //================================================================================
2934
2935 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2936 {
2937   // define allowed thickness
2938   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2939
2940   data._maxThickness = 0;
2941   data._minThickness = 1e100;
2942   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2943   for ( ; hyp != data._hyps.end(); ++hyp )
2944   {
2945     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2946     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2947   }
2948   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2949
2950   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2951   // boundry inclined to the shape at a sharp angle
2952
2953   //list< TGeomID > shapesToSmooth;
2954   TopTools_MapOfShape edgesOfSmooFaces;
2955
2956   SMESH_MesherHelper helper( *_mesh );
2957   bool ok = true;
2958
2959   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2960   data._nbShapesToSmooth = 0;
2961
2962   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2963   {
2964     _EdgesOnShape& eos = edgesByGeom[iS];
2965     eos._toSmooth = false;
2966     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2967       continue;
2968
2969     double tgtThick = eos._hyp.GetTotalThickness();
2970     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2971     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2972     {
2973       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2974       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2975       if ( eE.empty() ) continue;
2976
2977       double faceSize;
2978       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2979         if ( eE[i]->_cosin > theMinSmoothCosin )
2980         {
2981           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2982           while ( fIt->more() && !eos._toSmooth )
2983           {
2984             const SMDS_MeshElement* face = fIt->next();
2985             if ( face->getshapeId() == eos._shapeID &&
2986                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2987             {
2988               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2989             }
2990           }
2991         }
2992     }
2993     if ( eos._toSmooth )
2994     {
2995       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2996         edgesOfSmooFaces.Add( eExp.Current() );
2997
2998       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2999     }
3000     data._nbShapesToSmooth += eos._toSmooth;
3001
3002   }  // check FACEs
3003
3004   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3005   {
3006     _EdgesOnShape& eos = edgesByGeom[iS];
3007     eos._edgeSmoother = NULL;
3008     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3009     if ( !eos._hyp.ToSmooth() ) continue;
3010
3011     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3012     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3013       continue;
3014
3015     double tgtThick = eos._hyp.GetTotalThickness();
3016     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3017     {
3018       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3019       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3020       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3021       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3022       double angle    = eDir.Angle( eV[0]->_normal );
3023       double cosin    = Cos( angle );
3024       double cosinAbs = Abs( cosin );
3025       if ( cosinAbs > theMinSmoothCosin )
3026       {
3027         // always smooth analytic EDGEs
3028         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3029         eos._toSmooth = ! curve.IsNull();
3030
3031         // compare tgtThick with the length of an end segment
3032         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3033         while ( eIt->more() && !eos._toSmooth )
3034         {
3035           const SMDS_MeshElement* endSeg = eIt->next();
3036           if ( endSeg->getshapeId() == (int) iS )
3037           {
3038             double segLen =
3039               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3040             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3041           }
3042         }
3043         if ( eos._toSmooth )
3044         {
3045           eos._edgeSmoother = new _Smoother1D( curve, eos );
3046
3047           for ( size_t i = 0; i < eos._edges.size(); ++i )
3048             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3049         }
3050       }
3051     }
3052     data._nbShapesToSmooth += eos._toSmooth;
3053
3054   } // check EDGEs
3055
3056   // Reset _cosin if no smooth is allowed by the user
3057   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3058   {
3059     _EdgesOnShape& eos = edgesByGeom[iS];
3060     if ( eos._edges.empty() ) continue;
3061
3062     if ( !eos._hyp.ToSmooth() )
3063       for ( size_t i = 0; i < eos._edges.size(); ++i )
3064         eos._edges[i]->SetCosin( 0 );
3065   }
3066
3067
3068   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3069
3070   TopTools_MapOfShape c1VV;
3071
3072   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3073   {
3074     _EdgesOnShape& eos = edgesByGeom[iS];
3075     if ( eos._edges.empty() ||
3076          eos.ShapeType() != TopAbs_FACE ||
3077          !eos._toSmooth )
3078       continue;
3079
3080     // check EDGEs of a FACE
3081     TopTools_MapOfShape checkedEE, allVV;
3082     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3083     while ( !smQueue.empty() )
3084     {
3085       SMESH_subMesh* sm = smQueue.front();
3086       smQueue.pop_front();
3087       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3088       while ( smIt->more() )
3089       {
3090         sm = smIt->next();
3091         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3092           allVV.Add( sm->GetSubShape() );
3093         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3094              !checkedEE.Add( sm->GetSubShape() ))
3095           continue;
3096
3097         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3098         vector<_LayerEdge*>& eE = eoe->_edges;
3099         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3100           continue;
3101
3102         bool isC1 = true; // check continuity along an EDGE
3103         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3104           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3105         if ( !isC1 )
3106           continue;
3107
3108         // check that mesh faces are C1 as well
3109         {
3110           gp_XYZ norm1, norm2;
3111           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3112           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3113           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3114             continue;
3115           while ( fIt->more() && isC1 )
3116             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3117                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3118           if ( !isC1 )
3119             continue;
3120         }
3121
3122         // add the EDGE and an adjacent FACE to _eosC1
3123         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3124         while ( const TopoDS_Shape* face = fIt->next() )
3125         {
3126           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3127           if ( !eof ) continue; // other solid
3128           if ( !eos.HasC1( eoe ))
3129           {
3130             eos._eosC1.push_back( eoe );
3131             eoe->_toSmooth = false;
3132             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3133           }
3134           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3135           {
3136             eos._eosC1.push_back( eof );
3137             eof->_toSmooth = false;
3138             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3139             smQueue.push_back( eof->_subMesh );
3140           }
3141         }
3142       }
3143     }
3144     if ( eos._eosC1.empty() )
3145       continue;
3146
3147     // check VERTEXes of C1 FACEs
3148     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3149     for ( ; vIt.More(); vIt.Next() )
3150     {
3151       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3152       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3153         continue;
3154
3155       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3156       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3157       while ( const TopoDS_Shape* face = fIt->next() )
3158       {
3159         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3160         if ( !eof ) continue; // other solid
3161         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3162         if ( !isC1 )
3163           break;
3164       }
3165       if ( isC1 )
3166       {
3167         eos._eosC1.push_back( eov );
3168         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3169         c1VV.Add( eov->_shape );
3170       }
3171     }
3172
3173   } // fill _eosC1 of FACEs
3174
3175
3176   // Find C1 EDGEs
3177
3178   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3179
3180   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3181   {
3182     _EdgesOnShape& eov = edgesByGeom[iS];
3183     if ( eov._edges.empty() ||
3184          eov.ShapeType() != TopAbs_VERTEX ||
3185          c1VV.Contains( eov._shape ))
3186       continue;
3187     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3188
3189     // get directions of surrounding EDGEs
3190     dirOfEdges.clear();
3191     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3192     while ( const TopoDS_Shape* e = fIt->next() )
3193     {
3194       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3195       if ( !eoe ) continue; // other solid
3196       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3197       if ( !Precision::IsInfinite( eDir.X() ))
3198         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3199     }
3200
3201     // find EDGEs with C1 directions
3202     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3203       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3204         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3205         {
3206           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3207           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3208           if ( isC1 )
3209           {
3210             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3211             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3212             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3213             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3214             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3215             dirOfEdges[i].first = 0;
3216             dirOfEdges[j].first = 0;
3217           }
3218         }
3219   } // fill _eosC1 of VERTEXes
3220
3221
3222
3223   return ok;
3224 }
3225
3226 //================================================================================
3227 /*!
3228  * \brief initialize data of _EdgesOnShape
3229  */
3230 //================================================================================
3231
3232 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3233                                     SMESH_subMesh* sm,
3234                                     _SolidData&    data )
3235 {
3236   if ( !eos._shape.IsNull() ||
3237        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3238     return;
3239
3240   SMESH_MesherHelper helper( *_mesh );
3241
3242   eos._subMesh = sm;
3243   eos._shapeID = sm->GetId();
3244   eos._shape   = sm->GetSubShape();
3245   if ( eos.ShapeType() == TopAbs_FACE )
3246     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3247   eos._toSmooth = false;
3248   eos._data = &data;
3249
3250   // set _SWOL
3251   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3252     data._shrinkShape2Shape.find( eos._shapeID );
3253   if ( s2s != data._shrinkShape2Shape.end() )
3254     eos._sWOL = s2s->second;
3255
3256   eos._isRegularSWOL = true;
3257   if ( eos.SWOLType() == TopAbs_FACE )
3258   {
3259     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3260     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3261     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3262   }
3263
3264   // set _hyp
3265   if ( data._hyps.size() == 1 )
3266   {
3267     eos._hyp = data._hyps.back();
3268   }
3269   else
3270   {
3271     // compute average StdMeshers_ViscousLayers parameters
3272     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3273     if ( eos.ShapeType() == TopAbs_FACE )
3274     {
3275       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3276         eos._hyp = f2hyp->second;
3277     }
3278     else
3279     {
3280       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3281       while ( const TopoDS_Shape* face = fIt->next() )
3282       {
3283         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3284         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3285           eos._hyp.Add( f2hyp->second );
3286       }
3287     }
3288   }
3289
3290   // set _faceNormals
3291   if ( ! eos._hyp.UseSurfaceNormal() )
3292   {
3293     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3294     {
3295       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3296       eos._faceNormals.resize( smDS->NbElements() );
3297
3298       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3299       for ( int iF = 0; eIt->more(); ++iF )
3300       {
3301         const SMDS_MeshElement* face = eIt->next();
3302         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3303           eos._faceNormals[iF].SetCoord( 0,0,0 );
3304       }
3305
3306       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3307         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3308           eos._faceNormals[iF].Reverse();
3309     }
3310     else // find EOS of adjacent FACEs
3311     {
3312       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3313       while ( const TopoDS_Shape* face = fIt->next() )
3314       {
3315         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3316         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3317         if ( eos._faceEOS.back()->_shape.IsNull() )
3318           // avoid using uninitialised _shapeID in GetNormal()
3319           eos._faceEOS.back()->_shapeID = faceID;
3320       }
3321     }
3322   }
3323 }
3324
3325 //================================================================================
3326 /*!
3327  * \brief Returns normal of a face
3328  */
3329 //================================================================================
3330
3331 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3332 {
3333   bool ok = false;
3334   const _EdgesOnShape* eos = 0;
3335
3336   if ( face->getshapeId() == _shapeID )
3337   {
3338     eos = this;
3339   }
3340   else
3341   {
3342     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3343       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3344         eos = _faceEOS[ iF ];
3345   }
3346
3347   if (( eos ) &&
3348       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3349   {
3350     norm = eos->_faceNormals[ face->getIdInShape() ];
3351   }
3352   else if ( !eos )
3353   {
3354     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3355               << " on _shape #" << _shapeID );
3356   }
3357   return ok;
3358 }
3359
3360
3361 //================================================================================
3362 /*!
3363  * \brief Set data of _LayerEdge needed for smoothing
3364  */
3365 //================================================================================
3366
3367 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3368                                   _EdgesOnShape&      eos,
3369                                   SMESH_MesherHelper& helper,
3370                                   _SolidData&         data)
3371 {
3372   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3373
3374   edge._len       = 0;
3375   edge._maxLen    = Precision::Infinite();
3376   edge._minAngle  = 0;
3377   edge._2neibors  = 0;
3378   edge._curvature = 0;
3379   edge._flags     = 0;
3380
3381   // --------------------------
3382   // Compute _normal and _cosin
3383   // --------------------------
3384
3385   edge._cosin     = 0;
3386   edge._lenFactor = 1.;
3387   edge._normal.SetCoord(0,0,0);
3388   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3389
3390   int totalNbFaces = 0;
3391   TopoDS_Face F;
3392   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3393   gp_Vec geomNorm;
3394   bool normOK = true;
3395
3396   const bool onShrinkShape = !eos._sWOL.IsNull();
3397   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3398                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3399
3400   // get geom FACEs the node lies on
3401   //if ( useGeometry )
3402   {
3403     set<TGeomID> faceIds;
3404     if  ( eos.ShapeType() == TopAbs_FACE )
3405     {
3406       faceIds.insert( eos._shapeID );
3407     }
3408     else
3409     {
3410       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3411       while ( fIt->more() )
3412         faceIds.insert( fIt->next()->getshapeId() );
3413     }
3414     set<TGeomID>::iterator id = faceIds.begin();
3415     for ( ; id != faceIds.end(); ++id )
3416     {
3417       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3418       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3419         continue;
3420       F = TopoDS::Face( s );
3421       face2Norm[ totalNbFaces ].first = F;
3422       totalNbFaces++;
3423     }
3424   }
3425
3426   // find _normal
3427   if ( useGeometry )
3428   {
3429     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3430                       eos.SWOLType()  == TopAbs_FACE  &&
3431                       totalNbFaces > 1 );
3432
3433     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3434     {
3435       if ( eos.SWOLType() == TopAbs_EDGE )
3436       {
3437         // inflate from VERTEX along EDGE
3438         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3439       }
3440       else if ( eos.ShapeType() == TopAbs_VERTEX )
3441       {
3442         // inflate from VERTEX along FACE
3443         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3444                                    node, helper, normOK, &edge._cosin);
3445       }
3446       else
3447       {
3448         // inflate from EDGE along FACE
3449         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3450                                    node, helper, normOK);
3451       }
3452     }
3453     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3454     {
3455       if ( fromVonF )
3456         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3457
3458       int nbOkNorms = 0;
3459       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3460       {
3461         F = face2Norm[ iF ].first;
3462         geomNorm = getFaceNormal( node, F, helper, normOK );
3463         if ( !normOK ) continue;
3464         nbOkNorms++;
3465
3466         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3467           geomNorm.Reverse();
3468         face2Norm[ iF ].second = geomNorm.XYZ();
3469         edge._normal += geomNorm.XYZ();
3470       }
3471       if ( nbOkNorms == 0 )
3472         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3473
3474       if ( totalNbFaces >= 3 )
3475       {
3476         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3477       }
3478
3479       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3480       {
3481         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3482         edge._normal.SetCoord( 0,0,0 );
3483         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3484         {
3485           const TopoDS_Face& F = face2Norm[iF].first;
3486           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3487           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3488             geomNorm.Reverse();
3489           if ( normOK )
3490             face2Norm[ iF ].second = geomNorm.XYZ();
3491           edge._normal += face2Norm[ iF ].second;
3492         }
3493       }
3494     }
3495   }
3496   else // !useGeometry - get _normal using surrounding mesh faces
3497   {
3498     edge._normal = getWeigthedNormal( &edge );
3499
3500     // set<TGeomID> faceIds;
3501     //
3502     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3503     // while ( fIt->more() )
3504     // {
3505     //   const SMDS_MeshElement* face = fIt->next();
3506     //   if ( eos.GetNormal( face, geomNorm ))
3507     //   {
3508     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3509     //       continue; // use only one mesh face on FACE
3510     //     edge._normal += geomNorm.XYZ();
3511     //     totalNbFaces++;
3512     //   }
3513     // }
3514   }
3515
3516   // compute _cosin
3517   //if ( eos._hyp.UseSurfaceNormal() )
3518   {
3519     switch ( eos.ShapeType() )
3520     {
3521     case TopAbs_FACE: {
3522       edge._cosin = 0;
3523       break;
3524     }
3525     case TopAbs_EDGE: {
3526       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3527       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3528       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3529       edge._cosin      = Cos( angle );
3530       break;
3531     }
3532     case TopAbs_VERTEX: {
3533       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3534       {
3535         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3536         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3537         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3538         edge._cosin      = Cos( angle );
3539         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3540           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3541           {
3542             F = face2Norm[ iF ].first;
3543             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3544             if ( normOK ) {
3545               double angle = inFaceDir.Angle( edge._normal );
3546               double cosin = Cos( angle );
3547               if ( Abs( cosin ) > Abs( edge._cosin ))
3548                 edge._cosin = cosin;
3549             }
3550           }
3551       }
3552       break;
3553     }
3554     default:
3555       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3556     }
3557   }
3558
3559   double normSize = edge._normal.SquareModulus();
3560   if ( normSize < numeric_limits<double>::min() )
3561     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3562
3563   edge._normal /= sqrt( normSize );
3564
3565   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3566   {
3567     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3568     edge._nodes.resize( 1 );
3569     edge._normal.SetCoord( 0,0,0 );
3570     edge._maxLen = 0;
3571   }
3572
3573   // Set the rest data
3574   // --------------------
3575
3576   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3577
3578   if ( onShrinkShape )
3579   {
3580     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3581     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3582       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3583
3584     // set initial position which is parameters on _sWOL in this case
3585     if ( eos.SWOLType() == TopAbs_EDGE )
3586     {
3587       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3588       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3589       if ( edge._nodes.size() > 1 )
3590         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3591     }
3592     else // eos.SWOLType() == TopAbs_FACE
3593     {
3594       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3595       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3596       if ( edge._nodes.size() > 1 )
3597         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3598     }
3599
3600     if ( edge._nodes.size() > 1 )
3601     {
3602       // check if an angle between a FACE with layers and SWOL is sharp,
3603       // else the edge should not inflate
3604       F.Nullify();
3605       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3606         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3607           F = face2Norm[iF].first;
3608       if ( !F.IsNull())
3609       {
3610         geomNorm = getFaceNormal( node, F, helper, normOK );
3611         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3612           geomNorm.Reverse(); // inside the SOLID
3613         if ( geomNorm * edge._normal < -0.001 )
3614         {
3615           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3616           edge._nodes.resize( 1 );
3617         }
3618         else if ( edge._lenFactor > 3 )
3619         {
3620           edge._lenFactor = 2;
3621           edge.Set( _LayerEdge::RISKY_SWOL );
3622         }
3623       }
3624     }
3625   }
3626   else
3627   {
3628     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3629
3630     if ( eos.ShapeType() == TopAbs_FACE )
3631     {
3632       double angle;
3633       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3634       {
3635         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3636         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3637       }
3638     }
3639   }
3640
3641   // Set neighbor nodes for a _LayerEdge based on EDGE
3642
3643   if ( eos.ShapeType() == TopAbs_EDGE /*||
3644        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3645   {
3646     edge._2neibors = new _2NearEdges;
3647     // target nodes instead of source ones will be set later
3648   }
3649
3650   return true;
3651 }
3652
3653 //================================================================================
3654 /*!
3655  * \brief Return normal to a FACE at a node
3656  *  \param [in] n - node
3657  *  \param [in] face - FACE
3658  *  \param [in] helper - helper
3659  *  \param [out] isOK - true or false
3660  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3661  *  \return gp_XYZ - normal
3662  */
3663 //================================================================================
3664
3665 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3666                                       const TopoDS_Face&   face,
3667                                       SMESH_MesherHelper&  helper,
3668                                       bool&                isOK,
3669                                       bool                 shiftInside)
3670 {
3671   gp_XY uv;
3672   if ( shiftInside )
3673   {
3674     // get a shifted position
3675     gp_Pnt p = SMESH_TNodeXYZ( node );
3676     gp_XYZ shift( 0,0,0 );
3677     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3678     switch ( S.ShapeType() ) {
3679     case TopAbs_VERTEX:
3680     {
3681       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3682       break;
3683     }
3684     case TopAbs_EDGE:
3685     {
3686       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3687       break;
3688     }
3689     default:
3690       isOK = false;
3691     }
3692     if ( isOK )
3693       shift.Normalize();
3694     p.Translate( shift * 1e-5 );
3695
3696     TopLoc_Location loc;
3697     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3698
3699     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3700     
3701     projector.Perform( p );
3702     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3703     {
3704       isOK = false;
3705       return p.XYZ();
3706     }
3707     Quantity_Parameter U,V;
3708     projector.LowerDistanceParameters(U,V);
3709     uv.SetCoord( U,V );
3710   }
3711   else
3712   {
3713     uv = helper.GetNodeUV( face, node, 0, &isOK );
3714   }
3715
3716   gp_Dir normal;
3717   isOK = false;
3718
3719   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3720
3721   if ( !shiftInside &&
3722        helper.IsDegenShape( node->getshapeId() ) &&
3723        getFaceNormalAtSingularity( uv, face, helper, normal ))
3724   {
3725     isOK = true;
3726     return normal.XYZ();
3727   }
3728
3729   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3730   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3731
3732   if ( pointKind == IMPOSSIBLE &&
3733        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3734   {
3735     // probably NormEstim() failed due to a too high tolerance
3736     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3737     isOK = ( pointKind < IMPOSSIBLE );
3738   }
3739   if ( pointKind < IMPOSSIBLE )
3740   {
3741     if ( pointKind != REGULAR &&
3742          !shiftInside &&
3743          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3744     {
3745       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3746       if ( normShift * normal.XYZ() < 0. )
3747         normal = normShift;
3748     }
3749     isOK = true;
3750   }
3751
3752   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3753   {
3754     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3755
3756     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3757     while ( fIt->more() )
3758     {
3759       const SMDS_MeshElement* f = fIt->next();
3760       if ( f->getshapeId() == faceID )
3761       {
3762         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3763         if ( isOK )
3764         {
3765           TopoDS_Face ff = face;
3766           ff.Orientation( TopAbs_FORWARD );
3767           if ( helper.IsReversedSubMesh( ff ))
3768             normal.Reverse();
3769           break;
3770         }
3771       }
3772     }
3773   }
3774   return normal.XYZ();
3775 }
3776
3777 //================================================================================
3778 /*!
3779  * \brief Try to get normal at a singularity of a surface basing on it's nature
3780  */
3781 //================================================================================
3782
3783 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3784                                                   const TopoDS_Face&  face,
3785                                                   SMESH_MesherHelper& helper,
3786                                                   gp_Dir&             normal )
3787 {
3788   BRepAdaptor_Surface surface( face );
3789   gp_Dir axis;
3790   if ( !getRovolutionAxis( surface, axis ))
3791     return false;
3792
3793   double f,l, d, du, dv;
3794   f = surface.FirstUParameter();
3795   l = surface.LastUParameter();
3796   d = ( uv.X() - f ) / ( l - f );
3797   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3798   f = surface.FirstVParameter();
3799   l = surface.LastVParameter();
3800   d = ( uv.Y() - f ) / ( l - f );
3801   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3802
3803   gp_Dir refDir;
3804   gp_Pnt2d testUV = uv;
3805   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3806   double tol = 1e-5;
3807   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3808   for ( int iLoop = 0; true ; ++iLoop )
3809   {
3810     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3811     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3812       break;
3813     if ( iLoop > 20 )
3814       return false;
3815     tol /= 10.;
3816   }
3817
3818   if ( axis * refDir < 0. )
3819     axis.Reverse();
3820
3821   normal = axis;
3822
3823   return true;
3824 }
3825
3826 //================================================================================
3827 /*!
3828  * \brief Return a normal at a node weighted with angles taken by faces
3829  */
3830 //================================================================================
3831
3832 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3833 {
3834   const SMDS_MeshNode* n = edge->_nodes[0];
3835
3836   gp_XYZ resNorm(0,0,0);
3837   SMESH_TNodeXYZ p0( n ), pP, pN;
3838   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3839   {
3840     pP.Set( edge->_simplices[i]._nPrev );
3841     pN.Set( edge->_simplices[i]._nNext );
3842     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3843     double l0P = v0P.SquareMagnitude();
3844     double l0N = v0N.SquareMagnitude();
3845     double lPN = vPN.SquareMagnitude();
3846     if ( l0P < std::numeric_limits<double>::min() ||
3847          l0N < std::numeric_limits<double>::min() ||
3848          lPN < std::numeric_limits<double>::min() )
3849       continue;
3850     double lNorm = norm.SquareMagnitude();
3851     double  sin2 = lNorm / l0P / l0N;
3852     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3853
3854     double weight = sin2 * angle / lPN;
3855     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3856   }
3857
3858   return resNorm;
3859 }
3860
3861 //================================================================================
3862 /*!
3863  * \brief Return a normal at a node by getting a common point of offset planes
3864  *        defined by the FACE normals
3865  */
3866 //================================================================================
3867
3868 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3869                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3870                                            int                              nbFaces,
3871                                            bool                             lastNoOffset)
3872 {
3873   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3874
3875   gp_XYZ resNorm(0,0,0);
3876   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3877   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3878   {
3879     for ( int i = 0; i < nbFaces; ++i )
3880       resNorm += f2Normal[i].second;
3881     return resNorm;
3882   }
3883
3884   // prepare _OffsetPlane's
3885   vector< _OffsetPlane > pln( nbFaces );
3886   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3887   {
3888     pln[i]._faceIndex = i;
3889     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3890   }
3891   if ( lastNoOffset )
3892   {
3893     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3894     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3895   }
3896
3897   // intersect neighboring OffsetPlane's
3898   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3899   while ( const TopoDS_Shape* edge = edgeIt->next() )
3900   {
3901     int f1 = -1, f2 = -1;
3902     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3903       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3904         (( f1 < 0 ) ? f1 : f2 ) = i;
3905
3906     if ( f2 >= 0 )
3907       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3908   }
3909
3910   // get a common point
3911   gp_XYZ commonPnt( 0, 0, 0 );
3912   int nbPoints = 0;
3913   bool isPointFound;
3914   for ( int i = 0; i < nbFaces; ++i )
3915   {
3916     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3917     nbPoints  += isPointFound;
3918   }
3919   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3920   if ( nbPoints == 0 )
3921     return wgtNorm;
3922
3923   commonPnt /= nbPoints;
3924   resNorm = commonPnt - p0;
3925   if ( lastNoOffset )
3926     return resNorm;
3927
3928   // choose the best among resNorm and wgtNorm
3929   resNorm.Normalize();
3930   wgtNorm.Normalize();
3931   double resMinDot = std::numeric_limits<double>::max();
3932   double wgtMinDot = std::numeric_limits<double>::max();
3933   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3934   {
3935     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3936     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3937   }
3938
3939   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3940   {
3941     edge->Set( _LayerEdge::MULTI_NORMAL );
3942   }
3943
3944   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3945 }
3946
3947 //================================================================================
3948 /*!
3949  * \brief Compute line of intersection of 2 planes
3950  */
3951 //================================================================================
3952
3953 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3954                                             const TopoDS_Edge&   E,
3955                                             const TopoDS_Vertex& V )
3956 {
3957   int iNext = bool( _faceIndexNext[0] >= 0 );
3958   _faceIndexNext[ iNext ] = pln._faceIndex;
3959
3960   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3961   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3962
3963   gp_XYZ lineDir = n1 ^ n2;
3964
3965   double x = Abs( lineDir.X() );
3966   double y = Abs( lineDir.Y() );
3967   double z = Abs( lineDir.Z() );
3968
3969   int cooMax; // max coordinate
3970   if (x > y) {
3971     if (x > z) cooMax = 1;
3972     else       cooMax = 3;
3973   }
3974   else {
3975     if (y > z) cooMax = 2;
3976     else       cooMax = 3;
3977   }
3978
3979   gp_Pnt linePos;
3980   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3981   {
3982     // parallel planes - intersection is an offset of the common EDGE
3983     gp_Pnt p = BRep_Tool::Pnt( V );
3984     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3985     lineDir  = getEdgeDir( E, V );
3986   }
3987   else
3988   {
3989     // the constants in the 2 plane equations
3990     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3991     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3992
3993     switch ( cooMax ) {
3994     case 1:
3995       linePos.SetX(  0 );
3996       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3997       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3998       break;
3999     case 2:
4000       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4001       linePos.SetY(  0 );
4002       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4003       break;
4004     case 3:
4005       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4006       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4007       linePos.SetZ(  0 );
4008     }
4009   }
4010   gp_Lin& line = _lines[ iNext ];
4011   line.SetDirection( lineDir );
4012   line.SetLocation ( linePos );
4013
4014   _isLineOK[ iNext ] = true;
4015
4016
4017   iNext = bool( pln._faceIndexNext[0] >= 0 );
4018   pln._lines        [ iNext ] = line;
4019   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4020   pln._isLineOK     [ iNext ] = true;
4021 }
4022
4023 //================================================================================
4024 /*!
4025  * \brief Computes intersection point of two _lines
4026  */
4027 //================================================================================
4028
4029 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4030                                     const TopoDS_Vertex & V) const
4031 {
4032   gp_XYZ p( 0,0,0 );
4033   isFound = false;
4034
4035   if ( NbLines() == 2 )
4036   {
4037     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4038     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4039     if ( Abs( dot01 ) > 0.05 )
4040     {
4041       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4042       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4043       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4044       isFound = true;
4045     }
4046     else
4047     {
4048       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4049       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4050       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4051       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4052       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4053       isFound = true;
4054     }
4055   }
4056
4057   return p;
4058 }
4059
4060 //================================================================================
4061 /*!
4062  * \brief Find 2 neigbor nodes of a node on EDGE
4063  */
4064 //================================================================================
4065
4066 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4067                                         const SMDS_MeshNode*& n1,
4068                                         const SMDS_MeshNode*& n2,
4069                                         _EdgesOnShape&        eos,
4070                                         _SolidData&           data)
4071 {
4072   const SMDS_MeshNode* node = edge->_nodes[0];
4073   const int        shapeInd = eos._shapeID;
4074   SMESHDS_SubMesh*   edgeSM = 0;
4075   if ( eos.ShapeType() == TopAbs_EDGE )
4076   {
4077     edgeSM = eos._subMesh->GetSubMeshDS();
4078     if ( !edgeSM || edgeSM->NbElements() == 0 )
4079       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4080   }
4081   int iN = 0;
4082   n2 = 0;
4083   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4084   while ( eIt->more() && !n2 )
4085   {
4086     const SMDS_MeshElement* e = eIt->next();
4087     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4088     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4089     if ( edgeSM )
4090     {
4091       if (!edgeSM->Contains(e)) continue;
4092     }
4093     else
4094     {
4095       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4096       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4097     }
4098     ( iN++ ? n2 : n1 ) = nNeibor;
4099   }
4100   if ( !n2 )
4101     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4102   return true;
4103 }
4104
4105 //================================================================================
4106 /*!
4107  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4108  */
4109 //================================================================================
4110
4111 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4112                                      const SMDS_MeshNode* n2,
4113                                      const _EdgesOnShape& eos,
4114                                      SMESH_MesherHelper&  helper)
4115 {
4116   if ( eos.ShapeType() != TopAbs_EDGE )
4117     return;
4118
4119   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4120   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4121   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4122
4123   // Set _curvature
4124
4125   double      sumLen = vec1.Modulus() + vec2.Modulus();
4126   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4127   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4128   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4129   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4130   if ( _curvature ) delete _curvature;
4131   _curvature = _Curvature::New( avgNormProj, avgLen );
4132   // if ( _curvature )
4133   //   debugMsg( _nodes[0]->GetID()
4134   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4135   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4136   //             << _curvature->lenDelta(0) );
4137
4138   // Set _plnNorm
4139
4140   if ( eos._sWOL.IsNull() )
4141   {
4142     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4143     // if ( SMESH_Algo::isDegenerated( E ))
4144     //   return;
4145     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4146     gp_XYZ plnNorm = dirE ^ _normal;
4147     double proj0   = plnNorm * vec1;
4148     double proj1   = plnNorm * vec2;
4149     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4150     {
4151       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4152       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4153     }
4154   }
4155 }
4156
4157 //================================================================================
4158 /*!
4159  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4160  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4161  */
4162 //================================================================================
4163
4164 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4165                          _EdgesOnShape&      eos,
4166                          SMESH_MesherHelper& helper )
4167 {
4168   _nodes     = other._nodes;
4169   _normal    = other._normal;
4170   _len       = 0;
4171   _lenFactor = other._lenFactor;
4172   _cosin     = other._cosin;
4173   _2neibors  = other._2neibors;
4174   _curvature = 0; std::swap( _curvature, other._curvature );
4175   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4176
4177   gp_XYZ lastPos( 0,0,0 );
4178   if ( eos.SWOLType() == TopAbs_EDGE )
4179   {
4180     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4181     _pos.push_back( gp_XYZ( u, 0, 0));
4182
4183     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4184     lastPos.SetX( u );
4185   }
4186   else // TopAbs_FACE
4187   {
4188     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4189     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4190
4191     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4192     lastPos.SetX( uv.X() );
4193     lastPos.SetY( uv.Y() );
4194   }
4195   return lastPos;
4196 }
4197
4198 //================================================================================
4199 /*!
4200  * \brief Set _cosin and _lenFactor
4201  */
4202 //================================================================================
4203
4204 void _LayerEdge::SetCosin( double cosin )
4205 {
4206   _cosin = cosin;
4207   cosin = Abs( _cosin );
4208   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4209   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4210 }
4211
4212 //================================================================================
4213 /*!
4214  * \brief Check if another _LayerEdge is a neighbor on EDGE
4215  */
4216 //================================================================================
4217
4218 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4219 {
4220   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4221           ( edge->_2neibors && edge->_2neibors->include( this )));
4222 }
4223
4224 //================================================================================
4225 /*!
4226  * \brief Fills a vector<_Simplex > 
4227  */
4228 //================================================================================
4229
4230 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4231                              vector<_Simplex>&    simplices,
4232                              const set<TGeomID>&  ingnoreShapes,
4233                              const _SolidData*    dataToCheckOri,
4234                              const bool           toSort)
4235 {
4236   simplices.clear();
4237   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4238   while ( fIt->more() )
4239   {
4240     const SMDS_MeshElement* f = fIt->next();
4241     const TGeomID    shapeInd = f->getshapeId();
4242     if ( ingnoreShapes.count( shapeInd )) continue;
4243     const int nbNodes = f->NbCornerNodes();
4244     const int  srcInd = f->GetNodeIndex( node );
4245     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4246     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4247     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4248     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4249       std::swap( nPrev, nNext );
4250     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4251   }
4252
4253   if ( toSort )
4254     SortSimplices( simplices );
4255 }
4256
4257 //================================================================================
4258 /*!
4259  * \brief Set neighbor simplices side by side
4260  */
4261 //================================================================================
4262
4263 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4264 {
4265   vector<_Simplex> sortedSimplices( simplices.size() );
4266   sortedSimplices[0] = simplices[0];
4267   size_t nbFound = 0;
4268   for ( size_t i = 1; i < simplices.size(); ++i )
4269   {
4270     for ( size_t j = 1; j < simplices.size(); ++j )
4271       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4272       {
4273         sortedSimplices[i] = simplices[j];
4274         nbFound++;
4275         break;
4276       }
4277   }
4278   if ( nbFound == simplices.size() - 1 )
4279     simplices.swap( sortedSimplices );
4280 }
4281
4282 //================================================================================
4283 /*!
4284  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4285  */
4286 //================================================================================
4287
4288 void _ViscousBuilder::makeGroupOfLE()
4289 {
4290 #ifdef _DEBUG_
4291   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4292   {
4293     if ( _sdVec[i]._n2eMap.empty() ) continue;
4294
4295     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4296     TNode2Edge::iterator n2e;
4297     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4298     {
4299       _LayerEdge* le = n2e->second;
4300       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4301       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4302       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4303       if ( le ) {
4304         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4305                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4306       }
4307     }
4308     dumpFunctionEnd();
4309
4310     dumpFunction( SMESH_Comment("makeNormals") << i );
4311     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4312     {
4313       _LayerEdge* edge = n2e->second;
4314       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4315       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4316       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4317               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4318     }
4319     dumpFunctionEnd();
4320
4321     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4322     dumpCmd( "faceId1 = mesh.NbElements()" );
4323     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4324     for ( ; fExp.More(); fExp.Next() )
4325     {
4326       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4327       {
4328         if ( sm->NbElements() == 0 ) continue;
4329         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4330         while ( fIt->more())
4331         {
4332           const SMDS_MeshElement* e = fIt->next();
4333           SMESH_Comment cmd("mesh.AddFace([");
4334           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4335             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4336           dumpCmd( cmd );
4337         }
4338       }
4339     }
4340     dumpCmd( "faceId2 = mesh.NbElements()" );
4341     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4342              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4343              << "'%s-%s' % (faceId1+1, faceId2))");
4344     dumpFunctionEnd();
4345   }
4346 #endif
4347 }
4348
4349 //================================================================================
4350 /*!
4351  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4352  */
4353 //================================================================================
4354
4355 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4356 {
4357   data._geomSize = Precision::Infinite();
4358   double intersecDist;
4359   const SMDS_MeshElement* face;
4360   SMESH_MesherHelper helper( *_mesh );
4361
4362   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4363     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4364                                            data._proxyMesh->GetFaces( data._solid )));
4365
4366   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4367   {
4368     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4369     if ( eos._edges.empty() )
4370       continue;
4371     // get neighbor faces intersection with which should not be considered since
4372     // collisions are avoided by means of smoothing
4373     set< TGeomID > neighborFaces;
4374     if ( eos._hyp.ToSmooth() )
4375     {
4376       SMESH_subMeshIteratorPtr subIt =
4377         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4378       while ( subIt->more() )
4379       {
4380         SMESH_subMesh* sm = subIt->next();
4381         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4382         while ( const TopoDS_Shape* face = fIt->next() )
4383           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4384       }
4385     }
4386     // find intersections
4387     double thinkness = eos._hyp.GetTotalThickness();
4388     for ( size_t i = 0; i < eos._edges.size(); ++i )
4389     {
4390       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4391       eos._edges[i]->_maxLen = thinkness;
4392       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4393       if ( intersecDist > 0 && face )
4394       {
4395         data._geomSize = Min( data._geomSize, intersecDist );
4396         if ( !neighborFaces.count( face->getshapeId() ))
4397           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4398       }
4399     }
4400   }
4401 }
4402
4403 //================================================================================
4404 /*!
4405  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4406  */
4407 //================================================================================
4408
4409 bool _ViscousBuilder::inflate(_SolidData& data)
4410 {
4411   SMESH_MesherHelper helper( *_mesh );
4412
4413   // Limit inflation step size by geometry size found by itersecting
4414   // normals of _LayerEdge's with mesh faces
4415   if ( data._stepSize > 0.3 * data._geomSize )
4416     limitStepSize( data, 0.3 * data._geomSize );
4417
4418   const double tgtThick = data._maxThickness;
4419   if ( data._stepSize > data._minThickness )
4420     limitStepSize( data, data._minThickness );
4421
4422   if ( data._stepSize < 1. )
4423     data._epsilon = data._stepSize * 1e-7;
4424
4425   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4426
4427   findCollisionEdges( data, helper );
4428
4429   limitMaxLenByCurvature( data, helper );
4430
4431   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4432   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4433     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4434          data._edgesOnShape[i]._edges.size() > 0 &&
4435          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4436     {
4437       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4438       data._edgesOnShape[i]._edges[0]->Block( data );
4439     }
4440
4441   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4442
4443   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4444   int nbSteps = 0, nbRepeats = 0;
4445   while ( avgThick < 0.99 )
4446   {
4447     // new target length
4448     double prevThick = curThick;
4449     curThick += data._stepSize;
4450     if ( curThick > tgtThick )
4451     {
4452       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4453       nbRepeats++;
4454     }
4455
4456     double stepSize = curThick - prevThick;
4457     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4458
4459     // Elongate _LayerEdge's
4460     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4461     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4462     {
4463       _EdgesOnShape& eos = data._edgesOnShape[iS];
4464       if ( eos._edges.empty() ) continue;
4465
4466       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4467       for ( size_t i = 0; i < eos._edges.size(); ++i )
4468       {
4469         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4470       }
4471     }
4472     dumpFunctionEnd();
4473
4474     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4475       return false;
4476
4477     // Improve and check quality
4478     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4479     {
4480       if ( nbSteps > 0 )
4481       {
4482 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4483         debugMsg("NOT INVALIDATED STEP!");
4484         return error("Smoothing failed", data._index);
4485 #endif
4486         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4487         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4488         {
4489           _EdgesOnShape& eos = data._edgesOnShape[iS];
4490           for ( size_t i = 0; i < eos._edges.size(); ++i )
4491             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4492         }
4493         dumpFunctionEnd();
4494       }
4495       break; // no more inflating possible
4496     }
4497     nbSteps++;
4498
4499     // Evaluate achieved thickness
4500     avgThick = 0;
4501     int nbActiveEdges = 0;
4502     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4503     {
4504       _EdgesOnShape& eos = data._edgesOnShape[iS];
4505       if ( eos._edges.empty() ) continue;
4506
4507       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4508       for ( size_t i = 0; i < eos._edges.size(); ++i )
4509       {
4510         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4511         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4512       }
4513     }
4514     avgThick /= data._n2eMap.size();
4515     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4516
4517 #ifdef BLOCK_INFLATION
4518     if ( nbActiveEdges == 0 )
4519     {
4520       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4521       break;
4522     }
4523 #else
4524     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4525     {
4526       debugMsg( "-- Stop inflation since "
4527                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4528                 << tgtThick * avgThick << " ) * " << safeFactor );
4529       break;
4530     }
4531 #endif
4532     // new step size
4533     limitStepSize( data, 0.25 * distToIntersection );
4534     if ( data._stepSizeNodes[0] )
4535       data._stepSize = data._stepSizeCoeff *
4536         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4537
4538   } // while ( avgThick < 0.99 )
4539
4540   if ( nbSteps == 0 )
4541     return error("failed at the very first inflation step", data._index);
4542
4543   if ( avgThick < 0.99 )
4544   {
4545     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4546     {
4547       data._proxyMesh->_warning.reset
4548         ( new SMESH_ComputeError (COMPERR_WARNING,
4549                                   SMESH_Comment("Thickness ") << tgtThick <<
4550                                   " of viscous layers not reached,"
4551                                   " average reached thickness is " << avgThick*tgtThick));
4552     }
4553   }
4554
4555   // Restore position of src nodes moved by inflation on _noShrinkShapes
4556   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4557   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4558   {
4559     _EdgesOnShape& eos = data._edgesOnShape[iS];
4560     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4561       for ( size_t i = 0; i < eos._edges.size(); ++i )
4562       {
4563         restoreNoShrink( *eos._edges[ i ] );
4564       }
4565   }
4566   dumpFunctionEnd();
4567
4568   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4569 }
4570
4571 //================================================================================
4572 /*!
4573  * \brief Improve quality of layer inner surface and check intersection
4574  */
4575 //================================================================================
4576
4577 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4578                                      const int   infStep,
4579                                      double &    distToIntersection)
4580 {
4581   if ( data._nbShapesToSmooth == 0 )
4582     return true; // no shapes needing smoothing
4583
4584   bool moved, improved;
4585   double vol;
4586   vector< _LayerEdge* >    movedEdges, badEdges;
4587   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4588   vector< bool >           isConcaveFace;
4589
4590   SMESH_MesherHelper helper(*_mesh);
4591   Handle(ShapeAnalysis_Surface) surface;
4592   TopoDS_Face F;
4593
4594   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4595   {
4596     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4597
4598     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4599     {
4600       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4601       if ( !eos._toSmooth ||
4602            eos.ShapeType() != shapeType ||
4603            eos._edges.empty() )
4604         continue;
4605
4606       // already smoothed?
4607       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4608       // if ( !toSmooth ) continue;
4609
4610       if ( !eos._hyp.ToSmooth() )
4611       {
4612         // smooth disabled by the user; check validy only
4613         if ( !isFace ) continue;
4614         badEdges.clear();
4615         for ( size_t i = 0; i < eos._edges.size(); ++i )
4616         {
4617           _LayerEdge* edge = eos._edges[i];
4618           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4619             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4620             {
4621               // debugMsg( "-- Stop inflation. Bad simplex ("
4622               //           << " "<< edge->_nodes[0]->GetID()
4623               //           << " "<< edge->_nodes.back()->GetID()
4624               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4625               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4626               // return false;
4627               badEdges.push_back( edge );
4628             }
4629         }
4630         if ( !badEdges.empty() )
4631         {
4632           eosC1.resize(1);
4633           eosC1[0] = &eos;
4634           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4635           if ( nbBad > 0 )
4636             return false;
4637         }
4638         continue; // goto the next EDGE or FACE
4639       }
4640
4641       // prepare data
4642       if ( eos.SWOLType() == TopAbs_FACE )
4643       {
4644         if ( !F.IsSame( eos._sWOL )) {
4645           F = TopoDS::Face( eos._sWOL );
4646           helper.SetSubShape( F );
4647           surface = helper.GetSurface( F );
4648         }
4649       }
4650       else
4651       {
4652         F.Nullify(); surface.Nullify();
4653       }
4654       const TGeomID sInd = eos._shapeID;
4655
4656       // perform smoothing
4657
4658       if ( eos.ShapeType() == TopAbs_EDGE )
4659       {
4660         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4661
4662         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4663         {
4664           // smooth on EDGE's (normally we should not get here)
4665           int step = 0;
4666           do {
4667             moved = false;
4668             for ( size_t i = 0; i < eos._edges.size(); ++i )
4669             {
4670               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4671             }
4672             dumpCmd( SMESH_Comment("# end step ")<<step);
4673           }
4674           while ( moved && step++ < 5 );
4675         }
4676         dumpFunctionEnd();
4677       }
4678
4679       else // smooth on FACE
4680       {
4681         eosC1.clear();
4682         eosC1.push_back( & eos );
4683         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4684
4685         movedEdges.clear();
4686         isConcaveFace.resize( eosC1.size() );
4687         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4688         {
4689           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4690           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4691           for ( size_t i = 0; i < edges.size(); ++i )
4692             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4693                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4694               movedEdges.push_back( edges[i] );
4695
4696           makeOffsetSurface( *eosC1[ iEOS ], helper );
4697         }
4698
4699         int step = 0, stepLimit = 5, nbBad = 0;
4700         while (( ++step <= stepLimit ) || improved )
4701         {
4702           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4703                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4704           int oldBadNb = nbBad;
4705           badEdges.clear();
4706
4707 #ifdef INCREMENTAL_SMOOTH
4708           bool findBest = false; // ( step == stepLimit );
4709           for ( size_t i = 0; i < movedEdges.size(); ++i )
4710           {
4711             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4712             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4713               badEdges.push_back( movedEdges[i] );
4714           }
4715 #else
4716           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4717           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4718           {
4719             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4720             for ( size_t i = 0; i < edges.size(); ++i )
4721             {
4722               edges[i]->Unset( _LayerEdge::SMOOTHED );
4723               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4724                 badEdges.push_back( eos._edges[i] );
4725             }
4726           }
4727 #endif
4728           nbBad = badEdges.size();
4729
4730           if ( nbBad > 0 )
4731             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4732
4733           if ( !badEdges.empty() && step >= stepLimit / 2 )
4734           {
4735             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4736               stepLimit = 9;
4737
4738             // resolve hard smoothing situation around concave VERTEXes
4739             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4740             {
4741               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4742               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4743                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4744                                                          step, badEdges );
4745             }
4746             // look for the best smooth of _LayerEdge's neighboring badEdges
4747             nbBad = 0;
4748             for ( size_t i = 0; i < badEdges.size(); ++i )
4749             {
4750               _LayerEdge* ledge = badEdges[i];
4751               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4752               {
4753                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4754                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4755               }
4756               ledge->Unset( _LayerEdge::SMOOTHED );
4757               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4758             }
4759             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4760           }
4761
4762           if ( nbBad == oldBadNb  &&
4763                nbBad > 0 &&
4764                step < stepLimit ) // smooth w/o chech of validity
4765           {
4766             dumpFunctionEnd();
4767             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4768                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4769             for ( size_t i = 0; i < movedEdges.size(); ++i )
4770             {
4771               movedEdges[i]->SmoothWoCheck();
4772             }
4773             if ( stepLimit < 9 )
4774               stepLimit++;
4775           }
4776
4777           improved = ( nbBad < oldBadNb );
4778
4779           dumpFunctionEnd();
4780
4781           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4782             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4783             {
4784               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4785             }
4786
4787         } // smoothing steps
4788
4789         // project -- to prevent intersections or fix bad simplices
4790         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4791         {
4792           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4793             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4794         }
4795
4796         //if ( !badEdges.empty() )
4797         {
4798           badEdges.clear();
4799           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4800           {
4801             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4802             {
4803               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4804
4805               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4806               edge->CheckNeiborsOnBoundary( & badEdges );
4807               if (( nbBad > 0 ) ||
4808                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4809               {
4810                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4811                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4812                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4813                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4814                   {
4815                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4816                              << " "<< tgtXYZ._node->GetID()
4817                              << " "<< edge->_simplices[j]._nPrev->GetID()
4818                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4819                     badEdges.push_back( edge );
4820                     break;
4821                   }
4822               }
4823             }
4824           }
4825
4826           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4827           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4828
4829           if ( nbBad > 0 )
4830             return false;
4831         }
4832
4833       } // // smooth on FACE's
4834     } // loop on shapes
4835   } // smooth on [ EDGEs, FACEs ]
4836
4837   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4838   eosC1.resize(1);
4839   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4840   {
4841     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4842     if ( eos.ShapeType() == TopAbs_FACE ||
4843          eos._edges.empty() ||
4844          !eos._sWOL.IsNull() )
4845       continue;
4846
4847     badEdges.clear();
4848     for ( size_t i = 0; i < eos._edges.size(); ++i )
4849     {
4850       _LayerEdge*      edge = eos._edges[i];
4851       if ( edge->_nodes.size() < 2 ) continue;
4852       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4853       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4854       //const gp_XYZ& prevXYZ = edge->PrevPos();
4855       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4856         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4857         {
4858           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4859                    << " "<< tgtXYZ._node->GetID()
4860                    << " "<< edge->_simplices[j]._nPrev->GetID()
4861                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4862           badEdges.push_back( edge );
4863           break;
4864         }
4865     }
4866
4867     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4868     eosC1[0] = &eos;
4869     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4870     if ( nbBad > 0 )
4871       return false;
4872   }
4873
4874
4875   // Check if the last segments of _LayerEdge intersects 2D elements;
4876   // checked elements are either temporary faces or faces on surfaces w/o the layers
4877
4878   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4879     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4880                                            data._proxyMesh->GetFaces( data._solid )) );
4881
4882 #ifdef BLOCK_INFLATION
4883   const bool toBlockInfaltion = true;
4884 #else
4885   const bool toBlockInfaltion = false;
4886 #endif
4887   distToIntersection = Precision::Infinite();
4888   double dist;
4889   const SMDS_MeshElement* intFace = 0;
4890   const SMDS_MeshElement* closestFace = 0;
4891   _LayerEdge* le = 0;
4892   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4893   {
4894     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4895     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4896       continue;
4897     for ( size_t i = 0; i < eos._edges.size(); ++i )
4898     {
4899       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4900            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4901         continue;
4902       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4903       {
4904         return false;
4905         // commented due to "Illegal hash-positionPosition" error in NETGEN
4906         // on Debian60 on viscous_layers_01/B2 case
4907         // Collision; try to deflate _LayerEdge's causing it
4908         // badEdges.clear();
4909         // badEdges.push_back( eos._edges[i] );
4910         // eosC1[0] = & eos;
4911         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4912         // if ( nbBad > 0 )
4913         //   return false;
4914
4915         // badEdges.clear();
4916         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4917         // {
4918         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4919         //   {
4920         //     const SMDS_MeshElement* srcFace =
4921         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4922         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4923         //     while ( nIt->more() )
4924         //     {
4925         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4926         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4927         //       if ( n2e != data._n2eMap.end() )
4928         //         badEdges.push_back( n2e->second );
4929         //     }
4930         //     eosC1[0] = eof;
4931         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4932         //     if ( nbBad > 0 )
4933         //       return false;
4934         //   }
4935         // }
4936         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4937         //   return false;
4938         // else
4939         //   continue;
4940       }
4941       if ( !intFace )
4942       {
4943         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4944         debugMsg( msg );
4945         continue;
4946       }
4947
4948       const bool isShorterDist = ( distToIntersection > dist );
4949       if ( toBlockInfaltion || isShorterDist )
4950       {
4951         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4952         // lying on this _ConvexFace
4953         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4954           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4955             continue;
4956
4957         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4958         // ( avoid limiting the thickness on the case of issue 22576)
4959         if ( intFace->getshapeId() == eos._shapeID  )
4960           continue;
4961
4962         // ignore intersection with intFace of an adjacent FACE
4963         if ( dist > 0 )
4964         {
4965           bool toIgnore = false;
4966           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4967           {
4968             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4969             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4970             {
4971               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4972               for ( ; !toIgnore && edge.More(); edge.Next() )
4973                 // is adjacent - has a common EDGE
4974                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4975
4976               if ( toIgnore ) // check angle between normals
4977               {
4978                 gp_XYZ normal;
4979                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4980                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4981               }
4982             }
4983           }
4984           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4985           {
4986             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4987             {
4988               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4989               toIgnore = ( nInd >= 0 );
4990             }
4991           }
4992           if ( toIgnore )
4993             continue;
4994         }
4995
4996         // intersection not ignored
4997
4998         if ( toBlockInfaltion &&
4999              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5000         {
5001           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5002           eos._edges[i]->Block( data );                  // not to inflate
5003
5004           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5005           {
5006             // block _LayerEdge's, on top of which intFace is
5007             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5008             {
5009               const SMDS_MeshElement* srcFace =
5010                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5011               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5012               while ( nIt->more() )
5013               {
5014                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5015                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5016                 if ( n2e != data._n2eMap.end() )
5017                   n2e->second->Block( data );
5018               }
5019             }
5020           }
5021         }
5022
5023         if ( isShorterDist )
5024         {
5025           distToIntersection = dist;
5026           le = eos._edges[i];
5027           closestFace = intFace;
5028         }
5029
5030       } // if ( toBlockInfaltion || isShorterDist )
5031     } // loop on eos._edges
5032   } // loop on data._edgesOnShape
5033
5034   if ( closestFace && le )
5035   {
5036 #ifdef __myDEBUG
5037     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5038     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5039          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5040          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5041          << ") distance = " << distToIntersection<< endl;
5042 #endif
5043   }
5044
5045   return true;
5046 }
5047
5048 //================================================================================
5049 /*!
5050  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5051  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5052  *  \return int - resulting nb of bad _LayerEdge's
5053  */
5054 //================================================================================
5055
5056 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5057                                           SMESH_MesherHelper&       helper,
5058                                           vector< _LayerEdge* >&    badSmooEdges,
5059                                           vector< _EdgesOnShape* >& eosC1,
5060                                           const int                 infStep )
5061 {
5062   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5063
5064   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5065
5066   enum {
5067     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5068     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5069     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5070   };
5071   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5072
5073   double vol;
5074   bool haveInvalidated = true;
5075   while ( haveInvalidated )
5076   {
5077     haveInvalidated = false;
5078     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5079     {
5080       _LayerEdge*   edge = badSmooEdges[i];
5081       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5082       edge->Set( ADDED );
5083       bool invalidated = false;
5084       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5085       {
5086         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5087         edge->Block( data );
5088         edge->Set( INVALIDATED );
5089         edge->Unset( TO_INVALIDATE );
5090         invalidated = true;
5091         haveInvalidated = true;
5092       }
5093
5094       // look for _LayerEdge's of bad _simplices
5095       int nbBad = 0;
5096       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5097       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5098       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5099       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5100       {
5101         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5102             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5103           continue;
5104
5105         bool isBad = true;
5106         _LayerEdge* ee[2] = { 0,0 };
5107         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5108           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5109             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5110
5111         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5112         while ( maxNbSteps > edge->NbSteps() && isBad )
5113         {
5114           --maxNbSteps;
5115           for ( int iE = 0; iE < 2; ++iE )
5116           {
5117             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5118                  ee[ iE ]->NbSteps() > 1 )
5119             {
5120               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5121               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5122               ee[ iE ]->Block( data );
5123               ee[ iE ]->Set( INVALIDATED );
5124               haveInvalidated = true;
5125             }
5126           }
5127           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5128               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5129             isBad = false;
5130         }
5131         nbBad += isBad;
5132         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5133         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5134         ee[0]->Set( ADDED );
5135         ee[1]->Set( ADDED );
5136         if ( isBad )
5137         {
5138           ee[0]->Set( TO_INVALIDATE );
5139           ee[1]->Set( TO_INVALIDATE );
5140         }
5141       }
5142
5143       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5144       {
5145         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5146         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5147         edge->Block( data );
5148         edge->Set( INVALIDATED );
5149         edge->Unset( TO_INVALIDATE );
5150         haveInvalidated = true;
5151       }
5152     } // loop on badSmooEdges
5153   } // while ( haveInvalidated )
5154
5155   // re-smooth on analytical EDGEs
5156   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5157   {
5158     _LayerEdge* edge = badSmooEdges[i];
5159     if ( !edge->Is( INVALIDATED )) continue;
5160
5161     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5162     if ( eos->ShapeType() == TopAbs_VERTEX )
5163     {
5164       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5165       while ( const TopoDS_Shape* e = eIt->next() )
5166         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5167           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5168           {
5169             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5170             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5171             //   F       = TopoDS::Face( eoe->_sWOL );
5172             //   surface = helper.GetSurface( F );
5173             // }
5174             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5175             eoe->_edgeSmoother->_anaCurve.Nullify();
5176           }
5177     }
5178   }
5179
5180
5181   // check result of invalidation
5182
5183   int nbBad = 0;
5184   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5185   {
5186     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5187     {
5188       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5189       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5190       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5191       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5192       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5193         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5194         {
5195           ++nbBad;
5196           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5197                    << " "<< tgtXYZ._node->GetID()
5198                    << " "<< edge->_simplices[j]._nPrev->GetID()
5199                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5200         }
5201     }
5202   }
5203   dumpFunctionEnd();
5204
5205   return nbBad;
5206 }
5207
5208 //================================================================================
5209 /*!
5210  * \brief Create an offset surface
5211  */
5212 //================================================================================
5213
5214 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5215 {
5216   if ( eos._offsetSurf.IsNull() ||
5217        eos._edgeForOffset == 0 ||
5218        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5219     return;
5220
5221   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5222
5223   // find offset
5224   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5225   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5226   double offset = baseSurface->Gap();
5227
5228   eos._offsetSurf.Nullify();
5229
5230   try
5231   {
5232     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5233     if ( !offsetMaker.IsDone() ) return;
5234
5235     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5236     if ( !fExp.More() ) return;
5237
5238     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5239     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5240     if ( surf.IsNull() ) return;
5241
5242     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5243   }
5244   catch ( Standard_Failure )
5245   {
5246   }
5247 }
5248
5249 //================================================================================
5250 /*!
5251  * \brief Put nodes of a curved FACE to its offset surface
5252  */
5253 //================================================================================
5254
5255 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5256                                           int                       infStep,
5257                                           vector< _EdgesOnShape* >& eosC1,
5258                                           int                       smooStep,
5259                                           bool                      moveAll )
5260 {
5261   _EdgesOnShape * eof = & eos;
5262   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5263   {
5264     eof = 0;
5265     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5266     {
5267       if ( eosC1[i]->_offsetSurf.IsNull() ||
5268            eosC1[i]->ShapeType() != TopAbs_FACE ||
5269            eosC1[i]->_edgeForOffset == 0 ||
5270            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5271         continue;
5272       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5273         eof = eosC1[i];
5274     }
5275   }
5276   if ( !eof ||
5277        eof->_offsetSurf.IsNull() ||
5278        eof->ShapeType() != TopAbs_FACE ||
5279        eof->_edgeForOffset == 0 ||
5280        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5281     return;
5282
5283   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5284   for ( size_t i = 0; i < eos._edges.size(); ++i )
5285   {
5286     _LayerEdge* edge = eos._edges[i];
5287     edge->Unset( _LayerEdge::MARKED );
5288     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5289       continue;
5290     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5291         continue;
5292
5293     int nbBlockedAround = 0;
5294     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5295       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5296     if ( nbBlockedAround > 1 )
5297       continue;
5298
5299     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5300     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5301     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5302     edge->_curvature->_uv = uv;
5303     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5304
5305     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5306     gp_XYZ prevP = edge->PrevCheckPos();
5307     bool      ok = true;
5308     if ( !moveAll )
5309       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5310       {
5311         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5312       }
5313     if ( ok )
5314     {
5315       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5316       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5317       edge->_pos.back() = newP;
5318
5319       edge->Set( _LayerEdge::MARKED );
5320     }
5321   }
5322
5323 #ifdef _DEBUG_
5324   // dumpMove() for debug
5325   size_t i = 0;
5326   for ( ; i < eos._edges.size(); ++i )
5327     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5328       break;
5329   if ( i < eos._edges.size() )
5330   {
5331     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5332                  << "_InfStep" << infStep << "_" << smooStep );
5333     for ( ; i < eos._edges.size(); ++i )
5334     {
5335       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5336         dumpMove( eos._edges[i]->_nodes.back() );
5337     }
5338     dumpFunctionEnd();
5339   }
5340 #endif
5341 }
5342
5343 //================================================================================
5344 /*!
5345  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5346  *        _LayerEdge's to be in a consequent order
5347  */
5348 //================================================================================
5349
5350 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5351                                                 _EdgesOnShape&      eos,
5352                                                 SMESH_MesherHelper& helper)
5353 {
5354   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5355
5356   TopLoc_Location loc; double f,l;
5357
5358   Handle(Geom_Line)   line;
5359   Handle(Geom_Circle) circle;
5360   bool isLine, isCirc;
5361   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5362   {
5363     // check if the EDGE is a line
5364     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5365     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5366       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5367
5368     line   = Handle(Geom_Line)::DownCast( curve );
5369     circle = Handle(Geom_Circle)::DownCast( curve );
5370     isLine = (!line.IsNull());
5371     isCirc = (!circle.IsNull());
5372
5373     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5374     {
5375       isLine = SMESH_Algo::IsStraight( E );
5376
5377       if ( isLine )
5378         line = new Geom_Line( gp::OX() ); // only type does matter
5379     }
5380     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5381     {
5382       // TODO
5383     }
5384   }
5385   else //////////////////////////////////////////////////////////////////////// 2D case
5386   {
5387     if ( !eos._isRegularSWOL ) // 23190
5388       return NULL;
5389
5390     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5391
5392     // check if the EDGE is a line
5393     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5394     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5395       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5396
5397     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5398     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5399     isLine = (!line2d.IsNull());
5400     isCirc = (!circle2d.IsNull());
5401
5402     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5403     {
5404       Bnd_B2d bndBox;
5405       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5406       while ( nIt->more() )
5407         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5408       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5409
5410       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5411       for ( int i = 0; i < 2 && !isLine; ++i )
5412         isLine = ( size.Coord( i+1 ) <= lineTol );
5413     }
5414     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5415     {
5416       // TODO
5417     }
5418     if ( isLine )
5419     {
5420       line = new Geom_Line( gp::OX() ); // only type does matter
5421     }
5422     else if ( isCirc )
5423     {
5424       gp_Pnt2d p = circle2d->Location();
5425       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5426       circle = new Geom_Circle( ax, 1.); // only center position does matter
5427     }
5428   }
5429
5430   if ( isLine )
5431     return line;
5432   if ( isCirc )
5433     return circle;
5434
5435   return Handle(Geom_Curve)();
5436 }
5437
5438 //================================================================================
5439 /*!
5440  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5441  */
5442 //================================================================================
5443
5444 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5445                                       Handle(ShapeAnalysis_Surface)& surface,
5446                                       const TopoDS_Face&             F,
5447                                       SMESH_MesherHelper&            helper)
5448 {
5449   if ( !isAnalytic() ) return false;
5450
5451   const size_t iFrom = 0, iTo = _eos._edges.size();
5452
5453   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5454   {
5455     if ( F.IsNull() ) // 3D
5456     {
5457       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5458       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5459       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5460       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5461       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5462       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5463       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5464       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5465                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5466                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5467                          vLE1->Is( _LayerEdge::BLOCKED ));
5468       for ( size_t i = iFrom; i < iTo; ++i )
5469       {
5470         _LayerEdge*       edge = _eos._edges[i];
5471         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5472         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5473
5474         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5475         {
5476           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5477           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5478                             lineDir * ( curPos - pSrc0 ));
5479           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5480         }
5481         if ( edge->Is( _LayerEdge::BLOCKED ))
5482         {
5483           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5484           double curThick = pSrc.SquareDistance( tgtNode );
5485           double newThink = ( pSrc - newPos ).SquareModulus();
5486           if ( newThink > curThick )
5487             continue;
5488         }
5489         edge->_pos.back() = newPos;
5490         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5491         dumpMove( tgtNode );
5492       }
5493     }
5494     else // 2D
5495     {
5496       _LayerEdge* e0 = getLEdgeOnV( 0 );
5497       _LayerEdge* e1 = getLEdgeOnV( 1 );
5498       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5499       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5500       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5501       {
5502         int iPeriodic = helper.GetPeriodicIndex();
5503         if ( iPeriodic == 1 || iPeriodic == 2 )
5504         {
5505           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5506           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5507             std::swap( uv0, uv1 );
5508         }
5509       }
5510       const gp_XY rangeUV = uv1 - uv0;
5511       for ( size_t i = iFrom; i < iTo; ++i )
5512       {
5513         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5514         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5515         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5516
5517         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5518         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5519         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5520         dumpMove( tgtNode );
5521
5522         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5523         pos->SetUParameter( newUV.X() );
5524         pos->SetVParameter( newUV.Y() );
5525       }
5526     }
5527     return true;
5528   }
5529
5530   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5531   {
5532     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5533     gp_Pnt center3D = circle->Location();
5534
5535     if ( F.IsNull() ) // 3D
5536     {
5537       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5538         return true; // closed EDGE - nothing to do
5539
5540       // circle is a real curve of EDGE
5541       gp_Circ circ = circle->Circ();
5542
5543       // new center is shifted along its axis
5544       const gp_Dir& axis = circ.Axis().Direction();
5545       _LayerEdge*     e0 = getLEdgeOnV(0);
5546       _LayerEdge*     e1 = getLEdgeOnV(1);
5547       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5548       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5549       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5550       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5551       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5552
5553       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5554
5555       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5556       gp_Circ newCirc( newAxis, newRadius );
5557       gp_Vec  vecC1  ( newCenter, p1 );
5558
5559       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5560       if ( uLast < 0 )
5561         uLast += 2 * M_PI;
5562       
5563       for ( size_t i = iFrom; i < iTo; ++i )
5564       {
5565         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5566         double u = uLast * _leParams[i];
5567         gp_Pnt p = ElCLib::Value( u, newCirc );
5568         _eos._edges[i]->_pos.back() = p.XYZ();
5569
5570         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5571         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5572         dumpMove( tgtNode );
5573       }
5574       return true;
5575     }
5576     else // 2D
5577     {
5578       const gp_XY center( center3D.X(), center3D.Y() );
5579
5580       _LayerEdge* e0 = getLEdgeOnV(0);
5581       _LayerEdge* eM = _eos._edges[ 0 ];
5582       _LayerEdge* e1 = getLEdgeOnV(1);
5583       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5584       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5585       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5586       gp_Vec2d vec0( center, uv0 );
5587       gp_Vec2d vecM( center, uvM );
5588       gp_Vec2d vec1( center, uv1 );
5589       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5590       double uMidl = vec0.Angle( vecM );
5591       if ( uLast * uMidl <= 0. )
5592         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5593       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5594
5595       gp_Ax2d   axis( center, vec0 );
5596       gp_Circ2d circ( axis, radius );
5597       for ( size_t i = iFrom; i < iTo; ++i )
5598       {
5599         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5600         double    newU = uLast * _leParams[i];
5601         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5602         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5603
5604         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5605         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5606         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5607         dumpMove( tgtNode );
5608
5609         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5610         pos->SetUParameter( newUV.X() );
5611         pos->SetVParameter( newUV.Y() );
5612       }
5613     }
5614     return true;
5615   }
5616
5617   return false;
5618 }
5619
5620 //================================================================================
5621 /*!
5622  * \brief smooth _LayerEdge's on a an EDGE
5623  */
5624 //================================================================================
5625
5626 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5627                                      Handle(ShapeAnalysis_Surface)& surface,
5628                                      const TopoDS_Face&             F,
5629                                      SMESH_MesherHelper&            helper)
5630 {
5631   if ( _offPoints.empty() )
5632     return false;
5633
5634   // move _offPoints along normals of _LayerEdge's
5635
5636   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5637   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5638     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5639   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5640     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5641   _leOnV[0]._len = e[0]->_len;
5642   _leOnV[1]._len = e[1]->_len;
5643   for ( size_t i = 0; i < _offPoints.size(); i++ )
5644   {
5645     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5646     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5647     const double w0 = _offPoints[i]._2edges._wgt[0];
5648     const double w1 = _offPoints[i]._2edges._wgt[1];
5649     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5650     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5651     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5652     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5653          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5654       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5655
5656     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5657     _offPoints[i]._len  = avgLen;
5658   }
5659
5660   double fTol = 0;
5661   if ( !surface.IsNull() ) // project _offPoints to the FACE
5662   {
5663     fTol = 100 * BRep_Tool::Tolerance( F );
5664     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5665
5666     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5667     //if ( surface->Gap() < 0.5 * segLen )
5668       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5669
5670     for ( size_t i = 1; i < _offPoints.size(); ++i )
5671     {
5672       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5673       //if ( surface->Gap() < 0.5 * segLen )
5674         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5675     }
5676   }
5677
5678   // project tgt nodes of extreme _LayerEdge's to the offset segments
5679
5680   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5681   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5682
5683   gp_Pnt pExtreme[2], pProj[2];
5684   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5685   {
5686     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5687     int  i = _iSeg[ is2nd ];
5688     int di = is2nd ? -1 : +1;
5689     bool projected = false;
5690     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5691     int nbWorse = 0;
5692     do {
5693       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5694       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5695       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5696       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5697       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5698       if ( dist < distMin || projected )
5699       {
5700         _iSeg[ is2nd ] = i;
5701         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5702         distMin = dist;
5703       }
5704       else if ( dist > distPrev )
5705       {
5706         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5707           break;
5708       }
5709       distPrev = dist;
5710       i += di;
5711     }
5712     while ( !projected &&
5713             i >= 0 && i+1 < (int)_offPoints.size() );
5714
5715     if ( !projected )
5716     {
5717       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5718       {
5719         _iSeg[0] = 0;
5720         _iSeg[1] = _offPoints.size()-2;
5721         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5722         return false;
5723       }
5724     }
5725   }
5726   if ( _iSeg[0] > _iSeg[1] )
5727   {
5728     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5729     return false;
5730   }
5731
5732   // adjust length of extreme LE (test viscous_layers_01/B7)
5733   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5734   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5735   double d0 = vDiv0.Magnitude();
5736   double d1 = vDiv1.Magnitude();
5737   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5738   else                                   e[0]->_len -= d0;
5739   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5740   else                                   e[1]->_len -= d1;
5741
5742   // compute normalized length of the offset segments located between the projections
5743
5744   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5745   vector< double > len( nbSeg + 1 );
5746   len[ iSeg++ ] = 0;
5747   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5748   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5749   {
5750     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5751   }
5752   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5753
5754   // d0 *= e[0]->_lenFactor;
5755   // d1 *= e[1]->_lenFactor;
5756   double fullLen = len.back() - d0 - d1;
5757   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5758     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5759
5760   // temporary replace extreme _offPoints by pExtreme
5761   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5762                    _offPoints[ _iSeg[1]+1 ]._xyz };
5763   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5764   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5765
5766   // distribute tgt nodes of _LayerEdge's between the projections
5767
5768   iSeg = 0;
5769   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5770   {
5771     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5772     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5773       iSeg++;
5774     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5775     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5776                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5777
5778     if ( surface.IsNull() )
5779     {
5780       _eos._edges[i]->_pos.back() = p;
5781     }
5782     else // project a new node position to a FACE
5783     {
5784       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5785       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5786
5787       p = surface->Value( uv2 ).XYZ();
5788       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5789     }
5790     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5791     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5792     dumpMove( tgtNode );
5793   }
5794
5795   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5796   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5797
5798   return true;
5799 }
5800
5801 //================================================================================
5802 /*!
5803  * \brief Prepare for smoothing
5804  */
5805 //================================================================================
5806
5807 void _Smoother1D::prepare(_SolidData& data)
5808 {
5809   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5810   _curveLen = SMESH_Algo::EdgeLength( E );
5811
5812   // sort _LayerEdge's by position on the EDGE
5813   data.SortOnEdge( E, _eos._edges );
5814
5815   // compute normalized param of _eos._edges on EDGE
5816   _leParams.resize( _eos._edges.size() + 1 );
5817   {
5818     double curLen;
5819     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5820     _leParams[0] = 0;
5821     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5822     {
5823       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5824       curLen         = p.Distance( pPrev );
5825       _leParams[i+1] = _leParams[i] + curLen;
5826       pPrev          = p;
5827     }
5828     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5829     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5830       _leParams[i] = _leParams[i+1] / fullLen;
5831   }
5832
5833   if ( isAnalytic() )
5834     return;
5835
5836   // divide E to have offset segments with low deflection
5837   BRepAdaptor_Curve c3dAdaptor( E );
5838   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5839   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5840   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5841   if ( discret.NbPoints() <= 2 )
5842   {
5843     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5844     return;
5845   }
5846
5847   const double u0 = c3dAdaptor.FirstParameter();
5848   gp_Pnt p; gp_Vec tangent;
5849   _offPoints.resize( discret.NbPoints() );
5850   for ( size_t i = 0; i < _offPoints.size(); i++ )
5851   {
5852     double u = discret.Parameter( i+1 );
5853     c3dAdaptor.D1( u, p, tangent );
5854     _offPoints[i]._xyz     = p.XYZ();
5855     _offPoints[i]._edgeDir = tangent.XYZ();
5856     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5857   }
5858
5859   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5860
5861   // set _2edges
5862   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5863   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5864   _2NearEdges tmp2edges;
5865   tmp2edges._edges[1] = _eos._edges[0];
5866   _leOnV[0]._2neibors = & tmp2edges;
5867   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5868   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5869   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5870   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5871   {
5872     // find _LayerEdge's located before and after an offset point
5873     // (_eos._edges[ iLE ] is next after ePrev)
5874     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5875       ePrev = _eos._edges[ iLE++ ];
5876     eNext = ePrev->_2neibors->_edges[1];
5877
5878     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5879     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5880     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5881     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5882   }
5883
5884   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5885   for ( size_t i = 0; i < _offPoints.size(); i++ )
5886     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5887       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5888     else break;
5889   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5890     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5891       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5892     else break;
5893
5894   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5895
5896   int iLBO = _offPoints.size() - 2; // last but one
5897
5898   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5899   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5900
5901   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5902   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5903   _leOnV[ 0 ]._len = 0;
5904   _leOnV[ 1 ]._len = 0;
5905   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5906   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5907
5908   _iSeg[0] = 0;
5909   _iSeg[1] = _offPoints.size()-2;
5910
5911   // initialize OffPnt::_len
5912   for ( size_t i = 0; i < _offPoints.size(); ++i )
5913     _offPoints[i]._len = 0;
5914
5915   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5916   {
5917     _leOnV[0]._len = leOnV[0]->_len;
5918     _leOnV[1]._len = leOnV[1]->_len;
5919     for ( size_t i = 0; i < _offPoints.size(); i++ )
5920     {
5921       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5922       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5923       const double w0 = _offPoints[i]._2edges._wgt[0];
5924       const double w1 = _offPoints[i]._2edges._wgt[1];
5925       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5926       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5927                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5928       _offPoints[i]._xyz = avgXYZ;
5929       _offPoints[i]._len = avgLen;
5930     }
5931   }
5932 }
5933
5934 //================================================================================
5935 /*!
5936  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5937  */
5938 //================================================================================
5939
5940 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5941                                      const gp_XYZ&  edgeDir)
5942 {
5943   gp_XYZ cross = normal ^ edgeDir;
5944   gp_XYZ  norm = edgeDir ^ cross;
5945   double  size = norm.Modulus();
5946
5947   return norm / size;
5948 }
5949
5950 //================================================================================
5951 /*!
5952  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5953  */
5954 //================================================================================
5955
5956 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5957                              vector< _LayerEdge* >& edges)
5958 {
5959   map< double, _LayerEdge* > u2edge;
5960   for ( size_t i = 0; i < edges.size(); ++i )
5961     u2edge.insert( u2edge.end(),
5962                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5963
5964   ASSERT( u2edge.size() == edges.size() );
5965   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5966   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5967     edges[i] = u2e->second;
5968
5969   Sort2NeiborsOnEdge( edges );
5970 }
5971
5972 //================================================================================
5973 /*!
5974  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5975  */
5976 //================================================================================
5977
5978 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5979 {
5980   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5981
5982   for ( size_t i = 0; i < edges.size()-1; ++i )
5983     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5984       edges[i]->_2neibors->reverse();
5985
5986   const size_t iLast = edges.size() - 1;
5987   if ( edges.size() > 1 &&
5988        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5989     edges[iLast]->_2neibors->reverse();
5990 }
5991
5992 //================================================================================
5993 /*!
5994  * \brief Return _EdgesOnShape* corresponding to the shape
5995  */
5996 //================================================================================
5997
5998 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5999 {
6000   if ( shapeID < (int)_edgesOnShape.size() &&
6001        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6002     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6003
6004   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6005     if ( _edgesOnShape[i]._shapeID == shapeID )
6006       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6007
6008   return 0;
6009 }
6010
6011 //================================================================================
6012 /*!
6013  * \brief Return _EdgesOnShape* corresponding to the shape
6014  */
6015 //================================================================================
6016
6017 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6018 {
6019   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6020   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6021 }
6022
6023 //================================================================================
6024 /*!
6025  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6026  */
6027 //================================================================================
6028
6029 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6030 {
6031   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6032
6033   set< TGeomID > vertices;
6034   TopoDS_Face F;
6035   if ( eos->ShapeType() == TopAbs_FACE )
6036   {
6037     // check FACE concavity and get concave VERTEXes
6038     F = TopoDS::Face( eos->_shape );
6039     if ( isConcave( F, helper, &vertices ))
6040       _concaveFaces.insert( eos->_shapeID );
6041
6042     // set eos._eosConcaVer
6043     eos->_eosConcaVer.clear();
6044     eos->_eosConcaVer.reserve( vertices.size() );
6045     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6046     {
6047       _EdgesOnShape* eov = GetShapeEdges( *v );
6048       if ( eov && eov->_edges.size() == 1 )
6049       {
6050         eos->_eosConcaVer.push_back( eov );
6051         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6052           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6053       }
6054     }
6055
6056     // SetSmooLen() to _LayerEdge's on FACE
6057     for ( size_t i = 0; i < eos->_edges.size(); ++i )
6058     {
6059       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6060     }
6061     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6062     while ( smIt->more() ) // loop on sub-shapes of the FACE
6063     {
6064       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6065       if ( !eoe ) continue;
6066
6067       vector<_LayerEdge*>& eE = eoe->_edges;
6068       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6069       {
6070         if ( eE[iE]->_cosin <= theMinSmoothCosin )
6071           continue;
6072
6073         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6074         while ( segIt->more() )
6075         {
6076           const SMDS_MeshElement* seg = segIt->next();
6077           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6078             continue;
6079           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6080             continue; // not to check a seg twice
6081           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6082           {
6083             _LayerEdge* eN = eE[iE]->_neibors[iN];
6084             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6085               continue;
6086             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6087             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6088             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6089             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6090           }
6091         }
6092       }
6093     }
6094   } // if ( eos->ShapeType() == TopAbs_FACE )
6095
6096   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6097   {
6098     eos->_edges[i]->_smooFunction = 0;
6099     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6100   }
6101   bool isCurved = false;
6102   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6103   {
6104     _LayerEdge* edge = eos->_edges[i];
6105
6106     // get simplices sorted
6107     _Simplex::SortSimplices( edge->_simplices );
6108
6109     // smoothing function
6110     edge->ChooseSmooFunction( vertices, _n2eMap );
6111
6112     // set _curvature
6113     double avgNormProj = 0, avgLen = 0;
6114     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6115     {
6116       _Simplex& s = edge->_simplices[iS];
6117
6118       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6119       avgNormProj += edge->_normal * vec;
6120       avgLen      += vec.Modulus();
6121       if ( substituteSrcNodes )
6122       {
6123         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6124         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6125       }
6126     }
6127     avgNormProj /= edge->_simplices.size();
6128     avgLen      /= edge->_simplices.size();
6129     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6130     {
6131       isCurved = true;
6132       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6133       if ( !fPos )
6134         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6135           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6136       if ( fPos )
6137         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6138     }
6139   }
6140
6141   // prepare for putOnOffsetSurface()
6142   if (( eos->ShapeType() == TopAbs_FACE ) &&
6143       ( isCurved || !eos->_eosConcaVer.empty() ))
6144   {
6145     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6146     eos->_edgeForOffset = 0;
6147
6148     double maxCosin = -1;
6149     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6150     {
6151       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6152       if ( !eoe || eoe->_edges.empty() ) continue;
6153
6154       vector<_LayerEdge*>& eE = eoe->_edges;
6155       _LayerEdge* e = eE[ eE.size() / 2 ];
6156       if ( e->_cosin > maxCosin )
6157       {
6158         eos->_edgeForOffset = e;
6159         maxCosin = e->_cosin;
6160       }
6161     }
6162   }
6163 }
6164
6165 //================================================================================
6166 /*!
6167  * \brief Add faces for smoothing
6168  */
6169 //================================================================================
6170
6171 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6172                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6173 {
6174   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6175   for ( ; eos != eosToSmooth.end(); ++eos )
6176   {
6177     if ( !*eos || (*eos)->_toSmooth ) continue;
6178
6179     (*eos)->_toSmooth = true;
6180
6181     if ( (*eos)->ShapeType() == TopAbs_FACE )
6182     {
6183       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6184       (*eos)->_toSmooth = true;
6185     }
6186   }
6187
6188   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6189   if ( edgesNoAnaSmooth )
6190     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6191     {
6192       if ( (*eos)->_edgeSmoother )
6193         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6194     }
6195 }
6196
6197 //================================================================================
6198 /*!
6199  * \brief Limit _LayerEdge::_maxLen according to local curvature
6200  */
6201 //================================================================================
6202
6203 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6204 {
6205   // find intersection of neighbor _LayerEdge's to limit _maxLen
6206   // according to local curvature (IPAL52648)
6207
6208   // This method must be called after findCollisionEdges() where _LayerEdge's
6209   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6210
6211   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6212   {
6213     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6214     if ( eosI._edges.empty() ) continue;
6215     if ( !eosI._hyp.ToSmooth() )
6216     {
6217       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6218       {
6219         _LayerEdge* eI = eosI._edges[i];
6220         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6221         {
6222           _LayerEdge* eN = eI->_neibors[iN];
6223           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6224           {
6225             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6226             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6227           }
6228         }
6229       }
6230     }
6231     else if ( eosI.ShapeType() == TopAbs_EDGE )
6232     {
6233       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6234       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6235
6236       _LayerEdge* e0 = eosI._edges[0];
6237       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6238       {
6239         _LayerEdge* eI = eosI._edges[i];
6240         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6241         e0 = eI;
6242       }
6243     }
6244   }
6245 }
6246
6247 //================================================================================
6248 /*!
6249  * \brief Limit _LayerEdge::_maxLen according to local curvature
6250  */
6251 //================================================================================
6252
6253 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6254                                               _LayerEdge*         e2,
6255                                               _EdgesOnShape&      eos1,
6256                                               _EdgesOnShape&      eos2,
6257                                               SMESH_MesherHelper& helper )
6258 {
6259   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6260   double norSize = plnNorm.SquareModulus();
6261   if ( norSize < std::numeric_limits<double>::min() )
6262     return; // parallel normals
6263
6264   // find closest points of skew _LayerEdge's
6265   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6266   gp_XYZ dir12 = src2 - src1;
6267   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6268   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6269   double  dot1 = perp2 * e1->_normal;
6270   double  dot2 = perp1 * e2->_normal;
6271   double    u1 =   ( perp2 * dir12 ) / dot1;
6272   double    u2 = - ( perp1 * dir12 ) / dot2;
6273   if ( u1 > 0 && u2 > 0 )
6274   {
6275     double ovl = ( u1 * e1->_normal * dir12 -
6276                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6277     if ( ovl > theSmoothThickToElemSizeRatio )
6278     {    
6279       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6280       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6281     }
6282   }
6283 }
6284
6285 //================================================================================
6286 /*!
6287  * \brief Fill data._collisionEdges
6288  */
6289 //================================================================================
6290
6291 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6292 {
6293   data._collisionEdges.clear();
6294
6295   // set the full thickness of the layers to LEs
6296   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6297   {
6298     _EdgesOnShape& eos = data._edgesOnShape[iS];
6299     if ( eos._edges.empty() ) continue;
6300     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6301
6302     for ( size_t i = 0; i < eos._edges.size(); ++i )
6303     {
6304       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6305       double maxLen = eos._edges[i]->_maxLen;
6306       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6307       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6308       eos._edges[i]->_maxLen = maxLen;
6309     }
6310   }
6311
6312   // make temporary quadrangles got by extrusion of
6313   // mesh edges along _LayerEdge._normal's
6314
6315   vector< const SMDS_MeshElement* > tmpFaces;
6316
6317   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6318   {
6319     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6320     if ( eos.ShapeType() != TopAbs_EDGE )
6321       continue;
6322     if ( eos._edges.empty() )
6323     {
6324       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6325       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6326       while ( smIt->more() )
6327         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6328           if ( eov->_edges.size() == 1 )
6329             edge[ bool( edge[0]) ] = eov->_edges[0];
6330
6331       if ( edge[1] )
6332       {
6333         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6334         tmpFaces.push_back( f );
6335       }
6336     }
6337     for ( size_t i = 0; i < eos._edges.size(); ++i )
6338     {
6339       _LayerEdge* edge = eos._edges[i];
6340       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6341       {
6342         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6343         if ( src2->GetPosition()->GetDim() > 0 &&
6344              src2->GetID() < edge->_nodes[0]->GetID() )
6345           continue; // avoid using same segment twice
6346
6347         // a _LayerEdge containg tgt2
6348         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6349
6350         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6351         tmpFaces.push_back( f );
6352       }
6353     }
6354   }
6355
6356   // Find _LayerEdge's intersecting tmpFaces.
6357
6358   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6359                                                             tmpFaces.end()));
6360   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6361     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6362
6363   double dist1, dist2, segLen, eps = 0.5;
6364   _CollisionEdges collEdges;
6365   vector< const SMDS_MeshElement* > suspectFaces;
6366   const double angle45 = Cos( 45. * M_PI / 180. );
6367
6368   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6369   {
6370     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6371     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6372       continue;
6373     // find sub-shapes whose VL can influence VL on eos
6374     set< TGeomID > neighborShapes;
6375     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6376     while ( const TopoDS_Shape* face = fIt->next() )
6377     {
6378       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6379       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6380       {
6381         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6382         while ( subIt->more() )
6383           neighborShapes.insert( subIt->next()->GetId() );
6384       }
6385     }
6386     if ( eos.ShapeType() == TopAbs_VERTEX )
6387     {
6388       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6389       while ( const TopoDS_Shape* edge = eIt->next() )
6390         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6391     }
6392     // find intersecting _LayerEdge's
6393     for ( size_t i = 0; i < eos._edges.size(); ++i )
6394     {
6395       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6396       _LayerEdge*   edge = eos._edges[i];
6397       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6398       segLen *= 1.2;
6399
6400       gp_Vec eSegDir0, eSegDir1;
6401       if ( edge->IsOnEdge() )
6402       {
6403         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6404         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6405         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6406       }
6407       suspectFaces.clear();
6408       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6409                                      SMDSAbs_Face, suspectFaces );
6410       collEdges._intEdges.clear();
6411       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6412       {
6413         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6414         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6415         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6416         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6417         if ( edge->IsOnEdge() ) {
6418           if ( edge->_2neibors->include( f->_le1 ) ||
6419                edge->_2neibors->include( f->_le2 )) continue;
6420         }
6421         else {
6422           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6423               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6424         }
6425         dist1 = dist2 = Precision::Infinite();
6426         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6427           dist1 = Precision::Infinite();
6428         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6429           dist2 = Precision::Infinite();
6430         if (( dist1 > segLen ) && ( dist2 > segLen ))
6431           continue;
6432
6433         if ( edge->IsOnEdge() )
6434         {
6435           // skip perpendicular EDGEs
6436           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6437           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6438                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6439                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6440                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6441           if ( !isParallel )
6442             continue;
6443         }
6444
6445         // either limit inflation of edges or remember them for updating _normal
6446         // double dot = edge->_normal * f->GetDir();
6447         // if ( dot > 0.1 )
6448         {
6449           collEdges._intEdges.push_back( f->_le1 );
6450           collEdges._intEdges.push_back( f->_le2 );
6451         }
6452         // else
6453         // {
6454         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6455         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6456         // }
6457       }
6458
6459       if ( !collEdges._intEdges.empty() )
6460       {
6461         collEdges._edge = edge;
6462         data._collisionEdges.push_back( collEdges );
6463       }
6464     }
6465   }
6466
6467   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6468     delete tmpFaces[i];
6469
6470   // restore the zero thickness
6471   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6472   {
6473     _EdgesOnShape& eos = data._edgesOnShape[iS];
6474     if ( eos._edges.empty() ) continue;
6475     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6476
6477     for ( size_t i = 0; i < eos._edges.size(); ++i )
6478     {
6479       eos._edges[i]->InvalidateStep( 1, eos );
6480       eos._edges[i]->_len = 0;
6481     }
6482   }
6483 }
6484
6485 //================================================================================
6486 /*!
6487  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6488  * _LayerEdge's on neighbor EDGE's
6489  */
6490 //================================================================================
6491
6492 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6493                                      SMESH_MesherHelper& helper,
6494                                      int                 stepNb,
6495                                      double              stepSize)
6496 {
6497   updateNormalsOfC1Vertices( data );
6498
6499   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6500     return false;
6501
6502   // map to store new _normal and _cosin for each intersected edge
6503   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6504   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6505   _LayerEdge zeroEdge;
6506   zeroEdge._normal.SetCoord( 0,0,0 );
6507   zeroEdge._maxLen = Precision::Infinite();
6508   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6509
6510   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6511
6512   double segLen, dist1, dist2, dist;
6513   vector< pair< _LayerEdge*, double > > intEdgesDist;
6514   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6515
6516   for ( int iter = 0; iter < 5; ++iter )
6517   {
6518     edge2newEdge.clear();
6519
6520     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6521     {
6522       _CollisionEdges& ce = data._collisionEdges[iE];
6523       _LayerEdge*   edge1 = ce._edge;
6524       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6525       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6526       if ( !eos1 ) continue;
6527
6528       // detect intersections
6529       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6530       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6531       double     eps = 0.5;
6532       intEdgesDist.clear();
6533       double minIntDist = Precision::Infinite();
6534       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6535       {
6536         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6537              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6538              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6539           continue;
6540         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6541         double fact = ( 1.1 + dot * dot );
6542         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6543         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6544         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6545         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6546         dist1 = dist2 = Precision::Infinite();
6547         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6548              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6549           continue;
6550         dist = dist1;
6551         if ( dist > testLen || dist <= 0 )
6552         {
6553           dist = dist2;
6554           if ( dist > testLen || dist <= 0 )
6555             continue;
6556         }
6557         // choose a closest edge
6558         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6559         double d1 = intP.SquareDistance( pSrc0 );
6560         double d2 = intP.SquareDistance( pSrc1 );
6561         int iClose = i + ( d2 < d1 );
6562         _LayerEdge* edge2 = ce._intEdges[iClose];
6563         edge2->Unset( _LayerEdge::MARKED );
6564
6565         // choose a closest edge among neighbors
6566         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6567         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6568         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6569         {
6570           _LayerEdge * edgeJ = intEdgesDist[j].first;
6571           if ( edge2->IsNeiborOnEdge( edgeJ ))
6572           {
6573             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6574             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6575           }
6576         }
6577         intEdgesDist.push_back( make_pair( edge2, dist ));
6578         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6579         // {
6580         //   iClose = i + !( d2 < d1 );
6581         //   intEdges.push_back( ce._intEdges[iClose] );
6582         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6583         // }
6584         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6585       }
6586
6587       //ce._edge = 0;
6588
6589       // compute new _normals
6590       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6591       {
6592         _LayerEdge* edge2    = intEdgesDist[i].first;
6593         double       distWgt = edge1->_len / intEdgesDist[i].second;
6594         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6595         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6596         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6597         edge2->Set( _LayerEdge::MARKED );
6598
6599         // get a new normal
6600         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6601
6602         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6603         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6604         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6605         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6606         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6607         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6608         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6609         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6610         newNormal.Normalize();
6611
6612         // get new cosin
6613         double newCos;
6614         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6615         if ( cos1 < theMinSmoothCosin )
6616         {
6617           newCos = cos2 * sgn1;
6618         }
6619         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6620         {
6621           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6622         }
6623         else
6624         {
6625           newCos = edge1->_cosin;
6626         }
6627
6628         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6629         e2neIt->second._normal += distWgt * newNormal;
6630         e2neIt->second._cosin   = newCos;
6631         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6632         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6633           e2neIt->second._normal += dir2;
6634         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6635         e2neIt->second._normal += distWgt * newNormal;
6636         e2neIt->second._cosin   = edge2->_cosin;
6637         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6638           e2neIt->second._normal += dir1;
6639       }
6640     }
6641
6642     if ( edge2newEdge.empty() )
6643       break; //return true;
6644
6645     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6646
6647     // Update data of edges depending on a new _normal
6648
6649     data.UnmarkEdges();
6650     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6651     {
6652       _LayerEdge*    edge = e2neIt->first;
6653       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6654       _LayerEdge& newEdge = e2neIt->second;
6655       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6656
6657       // Check if a new _normal is OK:
6658       newEdge._normal.Normalize();
6659       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6660       {
6661         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6662         {
6663           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6664           edge->_maxLen = newEdge._maxLen;
6665           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6666         }
6667         continue; // the new _normal is bad
6668       }
6669       // the new _normal is OK
6670
6671       // find shapes that need smoothing due to change of _normal
6672       if ( edge->_cosin   < theMinSmoothCosin &&
6673            newEdge._cosin > theMinSmoothCosin )
6674       {
6675         if ( eos->_sWOL.IsNull() )
6676         {
6677           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6678           while ( fIt->more() )
6679             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6680         }
6681         else // edge inflates along a FACE
6682         {
6683           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6684           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
6685           while ( const TopoDS_Shape* E = eIt->next() )
6686           {
6687             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6688             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6689             if ( angle < M_PI / 2 )
6690               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6691           }
6692         }
6693       }
6694
6695       double len = edge->_len;
6696       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6697       edge->SetNormal( newEdge._normal );
6698       edge->SetCosin( newEdge._cosin );
6699       edge->SetNewLength( len, *eos, helper );
6700       edge->Set( _LayerEdge::MARKED );
6701       edge->Set( _LayerEdge::NORMAL_UPDATED );
6702       edgesNoAnaSmooth.insert( eos );
6703     }
6704
6705     // Update normals and other dependent data of not intersecting _LayerEdge's
6706     // neighboring the intersecting ones
6707
6708     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6709     {
6710       _LayerEdge*   edge1 = e2neIt->first;
6711       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6712       if ( !edge1->Is( _LayerEdge::MARKED ))
6713         continue;
6714
6715       if ( edge1->IsOnEdge() )
6716       {
6717         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6718         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6719         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6720       }
6721
6722       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6723         continue;
6724       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6725       {
6726         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6727         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6728           continue; // j-th neighbor is also intersected
6729         _LayerEdge* prevEdge = edge1;
6730         const int nbSteps = 10;
6731         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6732         {
6733           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6734                neighbor->Is( _LayerEdge::MARKED ))
6735             break;
6736           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6737           if ( !eos ) continue;
6738           _LayerEdge* nextEdge = neighbor;
6739           if ( neighbor->_2neibors )
6740           {
6741             int iNext = 0;
6742             nextEdge = neighbor->_2neibors->_edges[iNext];
6743             if ( nextEdge == prevEdge )
6744               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6745           }
6746           double r = double(step-1)/nbSteps/(iter+1);
6747           if ( !nextEdge->_2neibors )
6748             r = Min( r, 0.5 );
6749
6750           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6751           newNorm.Normalize();
6752           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6753             break;
6754
6755           double len = neighbor->_len;
6756           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6757           neighbor->SetNormal( newNorm );
6758           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6759           if ( neighbor->_2neibors )
6760             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6761           neighbor->SetNewLength( len, *eos, helper );
6762           neighbor->Set( _LayerEdge::MARKED );
6763           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6764           edgesNoAnaSmooth.insert( eos );
6765
6766           if ( !neighbor->_2neibors )
6767             break; // neighbor is on VERTEX
6768
6769           // goto the next neighbor
6770           prevEdge = neighbor;
6771           neighbor = nextEdge;
6772         }
6773       }
6774     }
6775     dumpFunctionEnd();
6776   } // iterations
6777
6778   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6779
6780   return true;
6781 }
6782
6783 //================================================================================
6784 /*!
6785  * \brief Check if a new normal is OK
6786  */
6787 //================================================================================
6788
6789 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6790                                      _LayerEdge&   edge,
6791                                      const gp_XYZ& newNormal)
6792 {
6793   // check a min angle between the newNormal and surrounding faces
6794   vector<_Simplex> simplices;
6795   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6796   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6797   double newMinDot = 1, curMinDot = 1;
6798   for ( size_t i = 0; i < simplices.size(); ++i )
6799   {
6800     n1.Set( simplices[i]._nPrev );
6801     n2.Set( simplices[i]._nNext );
6802     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6803     double normLen2 = normFace.SquareModulus();
6804     if ( normLen2 < std::numeric_limits<double>::min() )
6805       continue;
6806     normFace /= Sqrt( normLen2 );
6807     newMinDot = Min( newNormal    * normFace, newMinDot );
6808     curMinDot = Min( edge._normal * normFace, curMinDot );
6809   }
6810   bool ok = true;
6811   if ( newMinDot < 0.5 )
6812   {
6813     ok = ( newMinDot >= curMinDot * 0.9 );
6814     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6815     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6816     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6817   }
6818
6819   return ok;
6820 }
6821
6822 //================================================================================
6823 /*!
6824  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6825  */
6826 //================================================================================
6827
6828 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6829                                                SMESH_MesherHelper& helper,
6830                                                const int           nbSteps,
6831                                                const double        stepSize )
6832 {
6833   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6834     return true; // no shapes needing smoothing
6835
6836   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6837   {
6838     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6839     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6840          !eos._hyp.ToSmooth() ||
6841          eos.ShapeType() != TopAbs_FACE ||
6842          eos._edges.empty() )
6843       continue;
6844
6845     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6846     if ( !toSmooth ) continue;
6847
6848     for ( size_t i = 0; i < eos._edges.size(); ++i )
6849     {
6850       _LayerEdge* edge = eos._edges[i];
6851       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6852         continue;
6853       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6854         continue;
6855
6856       const gp_XYZ& pPrev = edge->PrevPos();
6857       const gp_XYZ& pLast = edge->_pos.back();
6858       gp_XYZ      stepVec = pLast - pPrev;
6859       double realStepSize = stepVec.Modulus();
6860       if ( realStepSize < numeric_limits<double>::min() )
6861         continue;
6862
6863       edge->_lenFactor = realStepSize / stepSize;
6864       edge->_normal    = stepVec / realStepSize;
6865       edge->Set( _LayerEdge::NORMAL_UPDATED );
6866     }
6867   }
6868
6869   return true;
6870 }
6871
6872 //================================================================================
6873 /*!
6874  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6875  */
6876 //================================================================================
6877
6878 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6879 {
6880   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6881   {
6882     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6883     if ( eov._eosC1.empty() ||
6884          eov.ShapeType() != TopAbs_VERTEX ||
6885          eov._edges.empty() )
6886       continue;
6887
6888     gp_XYZ newNorm   = eov._edges[0]->_normal;
6889     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6890     bool normChanged = false;
6891
6892     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6893     {
6894       _EdgesOnShape*   eoe = eov._eosC1[i];
6895       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6896       const double    eLen = SMESH_Algo::EdgeLength( e );
6897       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6898       if ( oppV.IsSame( eov._shape ))
6899         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6900       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6901       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6902       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6903
6904       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6905       if ( curThickOpp + curThick < eLen )
6906         continue;
6907
6908       double wgt = 2. * curThick / eLen;
6909       newNorm += wgt * eovOpp->_edges[0]->_normal;
6910       normChanged = true;
6911     }
6912     if ( normChanged )
6913     {
6914       eov._edges[0]->SetNormal( newNorm.Normalized() );
6915       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6916     }
6917   }
6918 }
6919
6920 //================================================================================
6921 /*!
6922  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6923  */
6924 //================================================================================
6925
6926 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6927                                                   SMESH_MesherHelper& helper,
6928                                                   int                 stepNb )
6929 {
6930   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6931   bool isOK;
6932
6933   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6934   for ( ; id2face != data._convexFaces.end(); ++id2face )
6935   {
6936     _ConvexFace & convFace = (*id2face).second;
6937     if ( convFace._normalsFixed )
6938       continue; // already fixed
6939     if ( convFace.CheckPrisms() )
6940       continue; // nothing to fix
6941
6942     convFace._normalsFixed = true;
6943
6944     BRepAdaptor_Surface surface ( convFace._face, false );
6945     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6946
6947     // check if the convex FACE is of spherical shape
6948
6949     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6950     Bnd_B3d nodesBox;
6951     gp_Pnt  center;
6952
6953     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6954     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6955     {
6956       _EdgesOnShape& eos = *(id2eos->second);
6957       if ( eos.ShapeType() == TopAbs_VERTEX )
6958       {
6959         _LayerEdge* ledge = eos._edges[ 0 ];
6960         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6961           centersBox.Add( center );
6962       }
6963       for ( size_t i = 0; i < eos._edges.size(); ++i )
6964         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6965     }
6966     if ( centersBox.IsVoid() )
6967     {
6968       debugMsg( "Error: centersBox.IsVoid()" );
6969       return false;
6970     }
6971     const bool isSpherical =
6972       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6973
6974     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6975     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6976
6977     if ( isSpherical )
6978     {
6979       // set _LayerEdge::_normal as average of all normals
6980
6981       // WARNING: different density of nodes on EDGEs is not taken into account that
6982       // can lead to an improper new normal
6983
6984       gp_XYZ avgNormal( 0,0,0 );
6985       nbEdges = 0;
6986       id2eos = convFace._subIdToEOS.begin();
6987       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6988       {
6989         _EdgesOnShape& eos = *(id2eos->second);
6990         // set data of _CentralCurveOnEdge
6991         if ( eos.ShapeType() == TopAbs_EDGE )
6992         {
6993           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6994           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6995           if ( !eos._sWOL.IsNull() )
6996             ceCurve._adjFace.Nullify();
6997           else
6998             ceCurve._ledges.insert( ceCurve._ledges.end(),
6999                                     eos._edges.begin(), eos._edges.end());
7000         }
7001         // summarize normals
7002         for ( size_t i = 0; i < eos._edges.size(); ++i )
7003           avgNormal += eos._edges[ i ]->_normal;
7004       }
7005       double normSize = avgNormal.SquareModulus();
7006       if ( normSize < 1e-200 )
7007       {
7008         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7009         return false;
7010       }
7011       avgNormal /= Sqrt( normSize );
7012
7013       // compute new _LayerEdge::_cosin on EDGEs
7014       double avgCosin = 0;
7015       int     nbCosin = 0;
7016       gp_Vec inFaceDir;
7017       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7018       {
7019         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7020         if ( ceCurve._adjFace.IsNull() )
7021           continue;
7022         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7023         {
7024           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7025           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7026           if ( isOK )
7027           {
7028             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7029             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7030             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7031             nbCosin++;
7032           }
7033         }
7034       }
7035       if ( nbCosin > 0 )
7036         avgCosin /= nbCosin;
7037
7038       // set _LayerEdge::_normal = avgNormal
7039       id2eos = convFace._subIdToEOS.begin();
7040       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7041       {
7042         _EdgesOnShape& eos = *(id2eos->second);
7043         if ( eos.ShapeType() != TopAbs_EDGE )
7044           for ( size_t i = 0; i < eos._edges.size(); ++i )
7045             eos._edges[ i ]->_cosin = avgCosin;
7046
7047         for ( size_t i = 0; i < eos._edges.size(); ++i )
7048         {
7049           eos._edges[ i ]->SetNormal( avgNormal );
7050           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7051         }
7052       }
7053     }
7054     else // if ( isSpherical )
7055     {
7056       // We suppose that centers of curvature at all points of the FACE
7057       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7058       // having a common center of curvature we define the same new normal
7059       // as a sum of normals of _LayerEdge's on EDGEs among them.
7060
7061       // get all centers of curvature for each EDGE
7062
7063       helper.SetSubShape( convFace._face );
7064       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7065
7066       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7067       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7068       {
7069         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7070
7071         // set adjacent FACE
7072         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7073
7074         // get _LayerEdge's of the EDGE
7075         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7076         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7077         if ( !eos || eos->_edges.empty() )
7078         {
7079           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7080           for ( int iV = 0; iV < 2; ++iV )
7081           {
7082             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7083             TGeomID     vID = meshDS->ShapeToIndex( v );
7084             eos = data.GetShapeEdges( vID );
7085             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7086           }
7087           edgeLEdge    = &vertexLEdges[0];
7088           edgeLEdgeEnd = edgeLEdge + 2;
7089
7090           centerCurves[ iE ]._adjFace.Nullify();
7091         }
7092         else
7093         {
7094           if ( ! eos->_toSmooth )
7095             data.SortOnEdge( edge, eos->_edges );
7096           edgeLEdge    = &eos->_edges[ 0 ];
7097           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7098           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7099           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7100
7101           if ( ! eos->_sWOL.IsNull() )
7102             centerCurves[ iE ]._adjFace.Nullify();
7103         }
7104
7105         // Get curvature centers
7106
7107         centersBox.Clear();
7108
7109         if ( edgeLEdge[0]->IsOnEdge() &&
7110              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7111         { // 1st VERTEX
7112           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7113           centersBox.Add( center );
7114         }
7115         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7116           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7117           { // EDGE or VERTEXes
7118             centerCurves[ iE ].Append( center, *edgeLEdge );
7119             centersBox.Add( center );
7120           }
7121         if ( edgeLEdge[-1]->IsOnEdge() &&
7122              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7123         { // 2nd VERTEX
7124           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7125           centersBox.Add( center );
7126         }
7127         centerCurves[ iE ]._isDegenerated =
7128           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7129
7130       } // loop on EDGES of convFace._face to set up data of centerCurves
7131
7132       // Compute new normals for _LayerEdge's on EDGEs
7133
7134       double avgCosin = 0;
7135       int     nbCosin = 0;
7136       gp_Vec inFaceDir;
7137       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7138       {
7139         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7140         if ( ceCurve._isDegenerated )
7141           continue;
7142         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7143         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7144         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7145         {
7146           isOK = false;
7147           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7148           {
7149             if ( iE1 != iE2 )
7150               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7151           }
7152           if ( isOK && !ceCurve._adjFace.IsNull() )
7153           {
7154             // compute new _LayerEdge::_cosin
7155             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7156             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7157             if ( isOK )
7158             {
7159               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7160               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7161               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7162               nbCosin++;
7163             }
7164           }
7165         }
7166       }
7167       // set new normals to _LayerEdge's of NOT degenerated central curves
7168       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7169       {
7170         if ( centerCurves[ iE ]._isDegenerated )
7171           continue;
7172         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7173         {
7174           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7175           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7176         }
7177       }
7178       // set new normals to _LayerEdge's of     degenerated central curves
7179       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7180       {
7181         if ( !centerCurves[ iE ]._isDegenerated ||
7182              centerCurves[ iE ]._ledges.size() < 3 )
7183           continue;
7184         // new normal is an average of new normals at VERTEXes that
7185         // was computed on non-degenerated _CentralCurveOnEdge's
7186         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7187                            centerCurves[ iE ]._ledges.back ()->_normal );
7188         double sz = newNorm.Modulus();
7189         if ( sz < 1e-200 )
7190           continue;
7191         newNorm /= sz;
7192         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7193                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7194         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7195         {
7196           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7197           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7198           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7199         }
7200       }
7201
7202       // Find new normals for _LayerEdge's based on FACE
7203
7204       if ( nbCosin > 0 )
7205         avgCosin /= nbCosin;
7206       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7207       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7208       if ( id2eos != convFace._subIdToEOS.end() )
7209       {
7210         int iE = 0;
7211         gp_XYZ newNorm;
7212         _EdgesOnShape& eos = * ( id2eos->second );
7213         for ( size_t i = 0; i < eos._edges.size(); ++i )
7214         {
7215           _LayerEdge* ledge = eos._edges[ i ];
7216           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7217             continue;
7218           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7219           {
7220             iE = iE % centerCurves.size();
7221             if ( centerCurves[ iE ]._isDegenerated )
7222               continue;
7223             newNorm.SetCoord( 0,0,0 );
7224             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7225             {
7226               ledge->SetNormal( newNorm );
7227               ledge->_cosin  = avgCosin;
7228               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7229               break;
7230             }
7231           }
7232         }
7233       }
7234
7235     } // not a quasi-spherical FACE
7236
7237     // Update _LayerEdge's data according to a new normal
7238
7239     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7240                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7241
7242     id2eos = convFace._subIdToEOS.begin();
7243     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7244     {
7245       _EdgesOnShape& eos = * ( id2eos->second );
7246       for ( size_t i = 0; i < eos._edges.size(); ++i )
7247       {
7248         _LayerEdge* & ledge = eos._edges[ i ];
7249         double len = ledge->_len;
7250         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7251         ledge->SetCosin( ledge->_cosin );
7252         ledge->SetNewLength( len, eos, helper );
7253       }
7254       if ( eos.ShapeType() != TopAbs_FACE )
7255         for ( size_t i = 0; i < eos._edges.size(); ++i )
7256         {
7257           _LayerEdge* ledge = eos._edges[ i ];
7258           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7259           {
7260             _LayerEdge* neibor = ledge->_neibors[iN];
7261             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7262             {
7263               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7264               neibor->Set( _LayerEdge::MOVED );
7265               neibor->SetSmooLen( neibor->_len );
7266             }
7267           }
7268         }
7269     } // loop on sub-shapes of convFace._face
7270
7271     // Find FACEs adjacent to convFace._face that got necessity to smooth
7272     // as a result of normals modification
7273
7274     set< _EdgesOnShape* > adjFacesToSmooth;
7275     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7276     {
7277       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7278            centerCurves[ iE ]._adjFaceToSmooth )
7279         continue;
7280       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7281       {
7282         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7283         {
7284           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7285           break;
7286         }
7287       }
7288     }
7289     data.AddShapesToSmooth( adjFacesToSmooth );
7290
7291     dumpFunctionEnd();
7292
7293
7294   } // loop on data._convexFaces
7295
7296   return true;
7297 }
7298
7299 //================================================================================
7300 /*!
7301  * \brief Finds a center of curvature of a surface at a _LayerEdge
7302  */
7303 //================================================================================
7304
7305 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7306                                         BRepLProp_SLProps&  surfProp,
7307                                         SMESH_MesherHelper& helper,
7308                                         gp_Pnt &            center ) const
7309 {
7310   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7311   surfProp.SetParameters( uv.X(), uv.Y() );
7312   if ( !surfProp.IsCurvatureDefined() )
7313     return false;
7314
7315   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7316   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7317   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7318   if ( surfCurvatureMin > surfCurvatureMax )
7319     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7320   else
7321     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7322
7323   return true;
7324 }
7325
7326 //================================================================================
7327 /*!
7328  * \brief Check that prisms are not distorted
7329  */
7330 //================================================================================
7331
7332 bool _ConvexFace::CheckPrisms() const
7333 {
7334   double vol = 0;
7335   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7336   {
7337     const _LayerEdge* edge = _simplexTestEdges[i];
7338     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7339     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7340       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7341       {
7342         debugMsg( "Bad simplex of _simplexTestEdges ("
7343                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7344                   << " "<< edge->_simplices[j]._nPrev->GetID()
7345                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7346         return false;
7347       }
7348   }
7349   return true;
7350 }
7351
7352 //================================================================================
7353 /*!
7354  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7355  *        stored in this _CentralCurveOnEdge.
7356  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7357  *  \param [in,out] newNormal - current normal at this point, to be redefined
7358  *  \return bool - true if succeeded.
7359  */
7360 //================================================================================
7361
7362 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7363 {
7364   if ( this->_isDegenerated )
7365     return false;
7366
7367   // find two centers the given one lies between
7368
7369   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7370   {
7371     double sl2 = 1.001 * _segLength2[ i ];
7372
7373     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7374     if ( d1 > sl2 )
7375       continue;
7376     
7377     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7378     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7379       continue;
7380
7381     d1 = Sqrt( d1 );
7382     d2 = Sqrt( d2 );
7383     double r = d1 / ( d1 + d2 );
7384     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7385                    (      r ) * _ledges[ i+1 ]->_normal );
7386     norm.Normalize();
7387
7388     newNormal += norm;
7389     double sz = newNormal.Modulus();
7390     if ( sz < 1e-200 )
7391       break;
7392     newNormal /= sz;
7393     return true;
7394   }
7395   return false;
7396 }
7397
7398 //================================================================================
7399 /*!
7400  * \brief Set shape members
7401  */
7402 //================================================================================
7403
7404 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7405                                      const _ConvexFace&  convFace,
7406                                      _SolidData&         data,
7407                                      SMESH_MesherHelper& helper)
7408 {
7409   _edge = edge;
7410
7411   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7412   while ( const TopoDS_Shape* F = fIt->next())
7413     if ( !convFace._face.IsSame( *F ))
7414     {
7415       _adjFace = TopoDS::Face( *F );
7416       _adjFaceToSmooth = false;
7417       // _adjFace already in a smoothing queue ?
7418       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7419         _adjFaceToSmooth = eos->_toSmooth;
7420       break;
7421     }
7422 }
7423
7424 //================================================================================
7425 /*!
7426  * \brief Looks for intersection of it's last segment with faces
7427  *  \param distance - returns shortest distance from the last node to intersection
7428  */
7429 //================================================================================
7430
7431 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7432                                    double &                 distance,
7433                                    const double&            epsilon,
7434                                    _EdgesOnShape&           eos,
7435                                    const SMDS_MeshElement** intFace)
7436 {
7437   vector< const SMDS_MeshElement* > suspectFaces;
7438   double segLen;
7439   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7440   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7441
7442   bool segmentIntersected = false;
7443   distance = Precision::Infinite();
7444   int iFace = -1; // intersected face
7445   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7446   {
7447     const SMDS_MeshElement* face = suspectFaces[j];
7448     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7449          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7450       continue; // face sharing _LayerEdge node
7451     const int nbNodes = face->NbCornerNodes();
7452     bool intFound = false;
7453     double dist;
7454     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7455     if ( nbNodes == 3 )
7456     {
7457       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7458     }
7459     else
7460     {
7461       const SMDS_MeshNode* tria[3];
7462       tria[0] = *nIt++;
7463       tria[1] = *nIt++;
7464       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7465       {
7466         tria[2] = *nIt++;
7467         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7468         tria[1] = tria[2];
7469       }
7470     }
7471     if ( intFound )
7472     {
7473       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7474         segmentIntersected = true;
7475       if ( distance > dist )
7476         distance = dist, iFace = j;
7477     }
7478   }
7479   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7480
7481   distance -= segLen;
7482
7483   if ( segmentIntersected )
7484   {
7485 #ifdef __myDEBUG
7486     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7487     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7488     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7489          << ", intersection with face ("
7490          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7491          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7492          << ") distance = " << distance << endl;
7493 #endif
7494   }
7495
7496   return segmentIntersected;
7497 }
7498
7499 //================================================================================
7500 /*!
7501  * \brief Returns a point used to check orientation of _simplices
7502  */
7503 //================================================================================
7504
7505 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7506 {
7507   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7508
7509   if ( !eos || eos->_sWOL.IsNull() )
7510     return _pos[ i ];
7511
7512   if ( eos->SWOLType() == TopAbs_EDGE )
7513   {
7514     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7515   }
7516   //else //  TopAbs_FACE
7517
7518   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7519 }
7520
7521 //================================================================================
7522 /*!
7523  * \brief Returns size and direction of the last segment
7524  */
7525 //================================================================================
7526
7527 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7528 {
7529   // find two non-coincident positions
7530   gp_XYZ orig = _pos.back();
7531   gp_XYZ vec;
7532   int iPrev = _pos.size() - 2;
7533   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7534   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7535   while ( iPrev >= 0 )
7536   {
7537     vec = orig - _pos[iPrev];
7538     if ( vec.SquareModulus() > tol*tol )
7539       break;
7540     else
7541       iPrev--;
7542   }
7543
7544   // make gp_Ax1
7545   gp_Ax1 segDir;
7546   if ( iPrev < 0 )
7547   {
7548     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7549     segDir.SetDirection( _normal );
7550     segLen = 0;
7551   }
7552   else
7553   {
7554     gp_Pnt pPrev = _pos[ iPrev ];
7555     if ( !eos._sWOL.IsNull() )
7556     {
7557       TopLoc_Location loc;
7558       if ( eos.SWOLType() == TopAbs_EDGE )
7559       {
7560         double f,l;
7561         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7562         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7563       }
7564       else
7565       {
7566         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7567         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7568       }
7569       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7570     }
7571     segDir.SetLocation( pPrev );
7572     segDir.SetDirection( vec );
7573     segLen = vec.Modulus();
7574   }
7575
7576   return segDir;
7577 }
7578
7579 //================================================================================
7580 /*!
7581  * \brief Return the last position of the target node on a FACE. 
7582  *  \param [in] F - the FACE this _LayerEdge is inflated along
7583  *  \return gp_XY - result UV
7584  */
7585 //================================================================================
7586
7587 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7588 {
7589   if ( F.IsSame( eos._sWOL )) // F is my FACE
7590     return gp_XY( _pos.back().X(), _pos.back().Y() );
7591
7592   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7593     return gp_XY( 1e100, 1e100 );
7594
7595   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7596   double f, l, u = _pos.back().X();
7597   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7598   if ( !C2d.IsNull() && f <= u && u <= l )
7599     return C2d->Value( u ).XY();
7600
7601   return gp_XY( 1e100, 1e100 );
7602 }
7603
7604 //================================================================================
7605 /*!
7606  * \brief Test intersection of the last segment with a given triangle
7607  *   using Moller-Trumbore algorithm
7608  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7609  */
7610 //================================================================================
7611
7612 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7613                                const gp_XYZ& vert0,
7614                                const gp_XYZ& vert1,
7615                                const gp_XYZ& vert2,
7616                                double&       t,
7617                                const double& EPSILON) const
7618 {
7619   const gp_Pnt& orig = lastSegment.Location();
7620   const gp_Dir& dir  = lastSegment.Direction();
7621
7622   /* calculate distance from vert0 to ray origin */
7623   //gp_XYZ tvec = orig.XYZ() - vert0;
7624
7625   //if ( tvec * dir > EPSILON )
7626     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7627     //return false;
7628
7629   gp_XYZ edge1 = vert1 - vert0;
7630   gp_XYZ edge2 = vert2 - vert0;
7631
7632   /* begin calculating determinant - also used to calculate U parameter */
7633   gp_XYZ pvec = dir.XYZ() ^ edge2;
7634
7635   /* if determinant is near zero, ray lies in plane of triangle */
7636   double det = edge1 * pvec;
7637
7638   const double ANGL_EPSILON = 1e-12;
7639   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7640     return false;
7641
7642   /* calculate distance from vert0 to ray origin */
7643   gp_XYZ tvec = orig.XYZ() - vert0;
7644
7645   /* calculate U parameter and test bounds */
7646   double u = ( tvec * pvec ) / det;
7647   //if (u < 0.0 || u > 1.0)
7648   if ( u < -EPSILON || u > 1.0 + EPSILON )
7649     return false;
7650
7651   /* prepare to test V parameter */
7652   gp_XYZ qvec = tvec ^ edge1;
7653
7654   /* calculate V parameter and test bounds */
7655   double v = (dir.XYZ() * qvec) / det;
7656   //if ( v < 0.0 || u + v > 1.0 )
7657   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7658     return false;
7659
7660   /* calculate t, ray intersects triangle */
7661   t = (edge2 * qvec) / det;
7662
7663   //return true;
7664   return t > 0.;
7665 }
7666
7667 //================================================================================
7668 /*!
7669  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7670  *        neighbor _LayerEdge's by it's own inflation vector.
7671  *  \param [in] eov - EOS of the VERTEX
7672  *  \param [in] eos - EOS of the FACE
7673  *  \param [in] step - inflation step
7674  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7675  */
7676 //================================================================================
7677
7678 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7679                                    const _EdgesOnShape*    eos,
7680                                    const int               step,
7681                                    vector< _LayerEdge* > & badSmooEdges )
7682 {
7683   // check if any of _neibors is in badSmooEdges
7684   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7685                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7686     return;
7687
7688   // get all edges to move
7689
7690   set< _LayerEdge* > edges;
7691
7692   // find a distance between _LayerEdge on VERTEX and its neighbors
7693   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7694   double dist2 = 0;
7695   for ( size_t i = 0; i < _neibors.size(); ++i )
7696   {
7697     _LayerEdge* nEdge = _neibors[i];
7698     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7699     {
7700       edges.insert( nEdge );
7701       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7702     }
7703   }
7704   // add _LayerEdge's close to curPosV
7705   size_t nbE;
7706   do {
7707     nbE = edges.size();
7708     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7709     {
7710       _LayerEdge* edgeF = *e;
7711       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7712       {
7713         _LayerEdge* nEdge = edgeF->_neibors[i];
7714         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7715              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7716           edges.insert( nEdge );
7717       }
7718     }
7719   }
7720   while ( nbE < edges.size() );
7721
7722   // move the target node of the got edges
7723
7724   gp_XYZ prevPosV = PrevPos();
7725   if ( eov->SWOLType() == TopAbs_EDGE )
7726   {
7727     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7728     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7729   }
7730   else if ( eov->SWOLType() == TopAbs_FACE )
7731   {
7732     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7733     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7734   }
7735
7736   SMDS_FacePosition* fPos;
7737   //double r = 1. - Min( 0.9, step / 10. );
7738   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7739   {
7740     _LayerEdge*       edgeF = *e;
7741     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7742     const gp_XYZ    newPosF = curPosV + prevVF;
7743     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7744     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7745     edgeF->_pos.back() = newPosF;
7746     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7747
7748     // set _curvature to make edgeF updated by putOnOffsetSurface()
7749     if ( !edgeF->_curvature )
7750       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7751       {
7752         edgeF->_curvature = new _Curvature;
7753         edgeF->_curvature->_r = 0;
7754         edgeF->_curvature->_k = 0;
7755         edgeF->_curvature->_h2lenRatio = 0;
7756         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7757       }
7758   }
7759   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7760   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7761   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7762   // {
7763   //   _LayerEdge*      edgeF = *e;
7764   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7765   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7766   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7767   //   edgeF->_pos.back() = newPosF;
7768   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7769   // }
7770
7771   // smooth _LayerEdge's around moved nodes
7772   //size_t nbBadBefore = badSmooEdges.size();
7773   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7774   {
7775     _LayerEdge* edgeF = *e;
7776     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7777       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7778         //&& !edges.count( edgeF->_neibors[j] ))
7779       {
7780         _LayerEdge* edgeFN = edgeF->_neibors[j];
7781         edgeFN->Unset( SMOOTHED );
7782         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7783         // if ( nbBad > 0 )
7784         // {
7785         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7786         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7787         //   int        nbBadAfter = edgeFN->_simplices.size();
7788         //   double vol;
7789         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7790         //   {
7791         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7792         //   }
7793         //   if ( nbBadAfter <= nbBad )
7794         //   {
7795         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7796         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7797         //     edgeF->_pos.back() = newPosF;
7798         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7799         //     nbBad = nbBadAfter;
7800         //   }
7801         // }
7802         if ( nbBad > 0 )
7803           badSmooEdges.push_back( edgeFN );
7804       }
7805   }
7806     // move a bit not smoothed around moved nodes
7807   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7808   //   {
7809   //   _LayerEdge*      edgeF = badSmooEdges[i];
7810   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7811   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7812   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7813   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7814   //   edgeF->_pos.back() = newPosF;
7815   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7816   // }
7817 }
7818
7819 //================================================================================
7820 /*!
7821  * \brief Perform smooth of _LayerEdge's based on EDGE's
7822  *  \retval bool - true if node has been moved
7823  */
7824 //================================================================================
7825
7826 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7827                               const TopoDS_Face&             F,
7828                               SMESH_MesherHelper&            helper)
7829 {
7830   ASSERT( IsOnEdge() );
7831
7832   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7833   SMESH_TNodeXYZ oldPos( tgtNode );
7834   double dist01, distNewOld;
7835   
7836   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7837   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7838   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7839
7840   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7841   double lenDelta = 0;
7842   if ( _curvature )
7843   {
7844     //lenDelta = _curvature->lenDelta( _len );
7845     lenDelta = _curvature->lenDeltaByDist( dist01 );
7846     newPos.ChangeCoord() += _normal * lenDelta;
7847   }
7848
7849   distNewOld = newPos.Distance( oldPos );
7850
7851   if ( F.IsNull() )
7852   {
7853     if ( _2neibors->_plnNorm )
7854     {
7855       // put newPos on the plane defined by source node and _plnNorm
7856       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7857       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7858       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7859     }
7860     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7861     _pos.back() = newPos.XYZ();
7862   }
7863   else
7864   {
7865     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7866     gp_XY uv( Precision::Infinite(), 0 );
7867     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7868     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7869
7870     newPos = surface->Value( uv );
7871     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7872   }
7873
7874   // commented for IPAL0052478
7875   // if ( _curvature && lenDelta < 0 )
7876   // {
7877   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7878   //   _len -= prevPos.Distance( oldPos );
7879   //   _len += prevPos.Distance( newPos );
7880   // }
7881   bool moved = distNewOld > dist01/50;
7882   //if ( moved )
7883   dumpMove( tgtNode ); // debug
7884
7885   return moved;
7886 }
7887
7888 //================================================================================
7889 /*!
7890  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7891  */
7892 //================================================================================
7893
7894 void _LayerEdge::SmoothWoCheck()
7895 {
7896   if ( Is( DIFFICULT ))
7897     return;
7898
7899   bool moved = Is( SMOOTHED );
7900   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7901     moved = _neibors[i]->Is( SMOOTHED );
7902   if ( !moved )
7903     return;
7904
7905   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7906
7907   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7908   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7909   _pos.back() = newPos;
7910
7911   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7912 }
7913
7914 //================================================================================
7915 /*!
7916  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7917  */
7918 //================================================================================
7919
7920 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7921 {
7922   if ( ! Is( NEAR_BOUNDARY ))
7923     return 0;
7924
7925   int nbBad = 0;
7926   double vol;
7927   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7928   {
7929     _LayerEdge* eN = _neibors[iN];
7930     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7931       continue;
7932     if ( needSmooth )
7933       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7934                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7935                        eN->_pos.size() != _pos.size() );
7936
7937     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7938     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7939     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7940       if ( eN->_nodes.size() > 1 &&
7941            eN->_simplices[i].Includes( _nodes.back() ) &&
7942            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7943       {
7944         ++nbBad;
7945         if ( badNeibors )
7946         {
7947           badNeibors->push_back( eN );
7948           debugMsg("Bad boundary simplex ( "
7949                    << " "<< eN->_nodes[0]->GetID()
7950                    << " "<< eN->_nodes.back()->GetID()
7951                    << " "<< eN->_simplices[i]._nPrev->GetID()
7952                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7953         }
7954         else
7955         {
7956           break;
7957         }
7958       }
7959   }
7960   return nbBad;
7961 }
7962
7963 //================================================================================
7964 /*!
7965  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7966  *  \retval int - nb of bad simplices around this _LayerEdge
7967  */
7968 //================================================================================
7969
7970 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7971 {
7972   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7973     return 0; // shape of simplices not changed
7974   if ( _simplices.size() < 2 )
7975     return 0; // _LayerEdge inflated along EDGE or FACE
7976
7977   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7978     findBest = true;
7979
7980   const gp_XYZ& curPos  = _pos.back();
7981   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7982
7983   // quality metrics (orientation) of tetras around _tgtNode
7984   int nbOkBefore = 0;
7985   double vol, minVolBefore = 1e100;
7986   for ( size_t i = 0; i < _simplices.size(); ++i )
7987   {
7988     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7989     minVolBefore = Min( minVolBefore, vol );
7990   }
7991   int nbBad = _simplices.size() - nbOkBefore;
7992
7993   bool bndNeedSmooth = false;
7994   if ( nbBad == 0 )
7995     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7996   if ( nbBad > 0 )
7997     Set( DISTORTED );
7998
7999   // evaluate min angle
8000   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8001   {
8002     size_t nbGoodAngles = _simplices.size();
8003     double angle;
8004     for ( size_t i = 0; i < _simplices.size(); ++i )
8005     {
8006       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8007         --nbGoodAngles;
8008     }
8009     if ( nbGoodAngles == _simplices.size() )
8010     {
8011       Unset( MOVED );
8012       return 0;
8013     }
8014   }
8015   if ( Is( ON_CONCAVE_FACE ))
8016     findBest = true;
8017
8018   if ( step % 2 == 0 )
8019     findBest = false;
8020
8021   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8022   {
8023     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8024       _smooFunction = _funs[ FUN_CENTROIDAL ];
8025     else
8026       _smooFunction = _funs[ FUN_LAPLACIAN ];
8027   }
8028
8029   // compute new position for the last _pos using different _funs
8030   gp_XYZ newPos;
8031   bool moved = false;
8032   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8033   {
8034     if ( iFun < 0 )
8035       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8036     else if ( _funs[ iFun ] == _smooFunction )
8037       continue; // _smooFunction again
8038     else if ( step > 1 )
8039       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8040     else
8041       break; // let "easy" functions improve elements around distorted ones
8042
8043     if ( _curvature )
8044     {
8045       double delta  = _curvature->lenDelta( _len );
8046       if ( delta > 0 )
8047         newPos += _normal * delta;
8048       else
8049       {
8050         double segLen = _normal * ( newPos - prevPos );
8051         if ( segLen + delta > 0 )
8052           newPos += _normal * delta;
8053       }
8054       // double segLenChange = _normal * ( curPos - newPos );
8055       // newPos += 0.5 * _normal * segLenChange;
8056     }
8057
8058     int nbOkAfter = 0;
8059     double minVolAfter = 1e100;
8060     for ( size_t i = 0; i < _simplices.size(); ++i )
8061     {
8062       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8063       minVolAfter = Min( minVolAfter, vol );
8064     }
8065     // get worse?
8066     if ( nbOkAfter < nbOkBefore )
8067       continue;
8068
8069     if (( findBest ) &&
8070         ( nbOkAfter == nbOkBefore ) &&
8071         ( minVolAfter <= minVolBefore ))
8072       continue;
8073
8074     nbBad        = _simplices.size() - nbOkAfter;
8075     minVolBefore = minVolAfter;
8076     nbOkBefore   = nbOkAfter;
8077     moved        = true;
8078
8079     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8080     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8081     _pos.back() = newPos;
8082
8083     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8084                   << (nbBad ? " --BAD" : ""));
8085
8086     if ( iFun > -1 )
8087     {
8088       continue; // look for a better function
8089     }
8090
8091     if ( !findBest )
8092       break;
8093
8094   } // loop on smoothing functions
8095
8096   if ( moved ) // notify _neibors
8097   {
8098     Set( SMOOTHED );
8099     for ( size_t i = 0; i < _neibors.size(); ++i )
8100       if ( !_neibors[i]->Is( MOVED ))
8101       {
8102         _neibors[i]->Set( MOVED );
8103         toSmooth.push_back( _neibors[i] );
8104       }
8105   }
8106
8107   return nbBad;
8108 }
8109
8110 //================================================================================
8111 /*!
8112  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8113  *  \retval int - nb of bad simplices around this _LayerEdge
8114  */
8115 //================================================================================
8116
8117 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8118 {
8119   if ( !_smooFunction )
8120     return 0; // _LayerEdge inflated along EDGE or FACE
8121   if ( Is( BLOCKED ))
8122     return 0; // not inflated
8123
8124   const gp_XYZ& curPos  = _pos.back();
8125   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8126
8127   // quality metrics (orientation) of tetras around _tgtNode
8128   int nbOkBefore = 0;
8129   double vol, minVolBefore = 1e100;
8130   for ( size_t i = 0; i < _simplices.size(); ++i )
8131   {
8132     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8133     minVolBefore = Min( minVolBefore, vol );
8134   }
8135   int nbBad = _simplices.size() - nbOkBefore;
8136
8137   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8138   {
8139     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8140       _smooFunction = _funs[ FUN_LAPLACIAN ];
8141     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8142       _smooFunction = _funs[ FUN_CENTROIDAL ];
8143   }
8144
8145   // compute new position for the last _pos using different _funs
8146   gp_XYZ newPos;
8147   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8148   {
8149     if ( iFun < 0 )
8150       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8151     else if ( _funs[ iFun ] == _smooFunction )
8152       continue; // _smooFunction again
8153     else if ( step > 1 )
8154       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8155     else
8156       break; // let "easy" functions improve elements around distorted ones
8157
8158     if ( _curvature )
8159     {
8160       double delta  = _curvature->lenDelta( _len );
8161       if ( delta > 0 )
8162         newPos += _normal * delta;
8163       else
8164       {
8165         double segLen = _normal * ( newPos - prevPos );
8166         if ( segLen + delta > 0 )
8167           newPos += _normal * delta;
8168       }
8169       // double segLenChange = _normal * ( curPos - newPos );
8170       // newPos += 0.5 * _normal * segLenChange;
8171     }
8172
8173     int nbOkAfter = 0;
8174     double minVolAfter = 1e100;
8175     for ( size_t i = 0; i < _simplices.size(); ++i )
8176     {
8177       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8178       minVolAfter = Min( minVolAfter, vol );
8179     }
8180     // get worse?
8181     if ( nbOkAfter < nbOkBefore )
8182       continue;
8183     if (( isConcaveFace || findBest ) &&
8184         ( nbOkAfter == nbOkBefore ) &&
8185         ( minVolAfter <= minVolBefore )
8186         )
8187       continue;
8188
8189     nbBad        = _simplices.size() - nbOkAfter;
8190     minVolBefore = minVolAfter;
8191     nbOkBefore   = nbOkAfter;
8192
8193     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8194     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8195     _pos.back() = newPos;
8196
8197     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8198                   << ( nbBad ? "--BAD" : ""));
8199
8200     // commented for IPAL0052478
8201     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8202     // _len += prevPos.Distance(newPos);
8203
8204     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8205     {
8206       //_smooFunction = _funs[ iFun ];
8207       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8208       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8209       // << " minVol: " << minVolAfter
8210       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8211       // << endl;
8212       continue; // look for a better function
8213     }
8214
8215     if ( !findBest )
8216       break;
8217
8218   } // loop on smoothing functions
8219
8220   return nbBad;
8221 }
8222
8223 //================================================================================
8224 /*!
8225  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8226  *        For a correct result, _simplices must contain nodes lying on geometry.
8227  */
8228 //================================================================================
8229
8230 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8231                                      const TNode2Edge&     n2eMap)
8232 {
8233   if ( _smooFunction ) return;
8234
8235   // use smoothNefPolygon() near concaveVertices
8236   if ( !concaveVertices.empty() )
8237   {
8238     _smooFunction = _funs[ FUN_CENTROIDAL ];
8239
8240     Set( ON_CONCAVE_FACE );
8241
8242     for ( size_t i = 0; i < _simplices.size(); ++i )
8243     {
8244       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8245       {
8246         _smooFunction = _funs[ FUN_NEFPOLY ];
8247
8248         // set FUN_CENTROIDAL to neighbor edges
8249         for ( i = 0; i < _neibors.size(); ++i )
8250         {
8251           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8252           {
8253             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8254           }
8255         }
8256         return;
8257       }
8258     }
8259
8260     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8261     // // where the nodes are smoothed too far along a sphere thus creating
8262     // // inverted _simplices
8263     // double dist[theNbSmooFuns];
8264     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8265     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8266
8267     // double minDist = Precision::Infinite();
8268     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8269     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8270     // {
8271     //   gp_Pnt newP = (this->*_funs[i])();
8272     //   dist[i] = p.SquareDistance( newP );
8273     //   if ( dist[i]*coef[i] < minDist )
8274     //   {
8275     //     _smooFunction = _funs[i];
8276     //     minDist = dist[i]*coef[i];
8277     //   }
8278     // }
8279   }
8280   else
8281   {
8282     _smooFunction = _funs[ FUN_LAPLACIAN ];
8283   }
8284   // int minDim = 3;
8285   // for ( size_t i = 0; i < _simplices.size(); ++i )
8286   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8287   // if ( minDim == 0 )
8288   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8289   // else if ( minDim == 1 )
8290   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8291
8292
8293   // int iMin;
8294   // for ( int i = 0; i < FUN_NB; ++i )
8295   // {
8296   //   //cout << dist[i] << " ";
8297   //   if ( _smooFunction == _funs[i] ) {
8298   //     iMin = i;
8299   //     //debugMsg( fNames[i] );
8300   //     break;
8301   //   }
8302   // }
8303   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8304 }
8305
8306 //================================================================================
8307 /*!
8308  * \brief Returns a name of _SmooFunction
8309  */
8310 //================================================================================
8311
8312 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8313 {
8314   if ( !fun )
8315     fun = _smooFunction;
8316   for ( int i = 0; i < theNbSmooFuns; ++i )
8317     if ( fun == _funs[i] )
8318       return i;
8319
8320   return theNbSmooFuns;
8321 }
8322
8323 //================================================================================
8324 /*!
8325  * \brief Computes a new node position using Laplacian smoothing
8326  */
8327 //================================================================================
8328
8329 gp_XYZ _LayerEdge::smoothLaplacian()
8330 {
8331   gp_XYZ newPos (0,0,0);
8332   for ( size_t i = 0; i < _simplices.size(); ++i )
8333     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8334   newPos /= _simplices.size();
8335
8336   return newPos;
8337 }
8338
8339 //================================================================================
8340 /*!
8341  * \brief Computes a new node position using angular-based smoothing
8342  */
8343 //================================================================================
8344
8345 gp_XYZ _LayerEdge::smoothAngular()
8346 {
8347   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8348   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8349   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8350
8351   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8352   gp_XYZ pN( 0,0,0 );
8353   for ( size_t i = 0; i < _simplices.size(); ++i )
8354   {
8355     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8356     edgeDir.push_back( p - pPrev );
8357     edgeSize.push_back( edgeDir.back().Magnitude() );
8358     if ( edgeSize.back() < numeric_limits<double>::min() )
8359     {
8360       edgeDir.pop_back();
8361       edgeSize.pop_back();
8362     }
8363     else
8364     {
8365       edgeDir.back() /= edgeSize.back();
8366       points.push_back( p );
8367       pN += p;
8368     }
8369     pPrev = p;
8370   }
8371   edgeDir.push_back ( edgeDir[0] );
8372   edgeSize.push_back( edgeSize[0] );
8373   pN /= points.size();
8374
8375   gp_XYZ newPos(0,0,0);
8376   double sumSize = 0;
8377   for ( size_t i = 0; i < points.size(); ++i )
8378   {
8379     gp_Vec toN    = pN - points[i];
8380     double toNLen = toN.Magnitude();
8381     if ( toNLen < numeric_limits<double>::min() )
8382     {
8383       newPos += pN;
8384       continue;
8385     }
8386     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8387     double bisecLen = bisec.SquareMagnitude();
8388     if ( bisecLen < numeric_limits<double>::min() )
8389     {
8390       gp_Vec norm = edgeDir[i] ^ toN;
8391       bisec = norm ^ edgeDir[i];
8392       bisecLen = bisec.SquareMagnitude();
8393     }
8394     bisecLen = Sqrt( bisecLen );
8395     bisec /= bisecLen;
8396
8397 #if 1
8398     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8399     sumSize += bisecLen;
8400 #else
8401     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8402     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8403 #endif
8404     newPos += pNew;
8405   }
8406   newPos /= sumSize;
8407
8408   // project newPos to an average plane
8409
8410   gp_XYZ norm(0,0,0); // plane normal
8411   points.push_back( points[0] );
8412   for ( size_t i = 1; i < points.size(); ++i )
8413   {
8414     gp_XYZ vec1 = points[ i-1 ] - pN;
8415     gp_XYZ vec2 = points[ i   ] - pN;
8416     gp_XYZ cross = vec1 ^ vec2;
8417     try {
8418       cross.Normalize();
8419       if ( cross * norm < numeric_limits<double>::min() )
8420         norm += cross.Reversed();
8421       else
8422         norm += cross;
8423     }
8424     catch (Standard_Failure) { // if |cross| == 0.
8425     }
8426   }
8427   gp_XYZ vec = newPos - pN;
8428   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8429   newPos     = newPos - r * norm;
8430
8431   return newPos;
8432 }
8433
8434 //================================================================================
8435 /*!
8436  * \brief Computes a new node position using weigthed node positions
8437  */
8438 //================================================================================
8439
8440 gp_XYZ _LayerEdge::smoothLengthWeighted()
8441 {
8442   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8443   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8444
8445   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8446   for ( size_t i = 0; i < _simplices.size(); ++i )
8447   {
8448     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8449     edgeSize.push_back( ( p - pPrev ).Modulus() );
8450     if ( edgeSize.back() < numeric_limits<double>::min() )
8451     {
8452       edgeSize.pop_back();
8453     }
8454     else
8455     {
8456       points.push_back( p );
8457     }
8458     pPrev = p;
8459   }
8460   edgeSize.push_back( edgeSize[0] );
8461
8462   gp_XYZ newPos(0,0,0);
8463   double sumSize = 0;
8464   for ( size_t i = 0; i < points.size(); ++i )
8465   {
8466     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8467     sumSize += edgeSize[i] + edgeSize[i+1];
8468   }
8469   newPos /= sumSize;
8470   return newPos;
8471 }
8472
8473 //================================================================================
8474 /*!
8475  * \brief Computes a new node position using angular-based smoothing
8476  */
8477 //================================================================================
8478
8479 gp_XYZ _LayerEdge::smoothCentroidal()
8480 {
8481   gp_XYZ newPos(0,0,0);
8482   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8483   double sumSize = 0;
8484   for ( size_t i = 0; i < _simplices.size(); ++i )
8485   {
8486     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8487     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8488     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8489     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8490
8491     sumSize += size;
8492     newPos += gc * size;
8493   }
8494   newPos /= sumSize;
8495
8496   return newPos;
8497 }
8498
8499 //================================================================================
8500 /*!
8501  * \brief Computes a new node position located inside a Nef polygon
8502  */
8503 //================================================================================
8504
8505 gp_XYZ _LayerEdge::smoothNefPolygon()
8506 #ifdef OLD_NEF_POLYGON
8507 {
8508   gp_XYZ newPos(0,0,0);
8509
8510   // get a plane to seach a solution on
8511
8512   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8513   size_t i;
8514   const double tol = numeric_limits<double>::min();
8515   gp_XYZ center(0,0,0);
8516   for ( i = 0; i < _simplices.size(); ++i )
8517   {
8518     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8519                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8520     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8521   }
8522   vecs.back() = vecs[0];
8523   center /= _simplices.size();
8524
8525   gp_XYZ zAxis(0,0,0);
8526   for ( i = 0; i < _simplices.size(); ++i )
8527     zAxis += vecs[i] ^ vecs[i+1];
8528
8529   gp_XYZ yAxis;
8530   for ( i = 0; i < _simplices.size(); ++i )
8531   {
8532     yAxis = vecs[i];
8533     if ( yAxis.SquareModulus() > tol )
8534       break;
8535   }
8536   gp_XYZ xAxis = yAxis ^ zAxis;
8537   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8538   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8539   //                             p0.Distance( _simplices[2]._nPrev ));
8540   // gp_XYZ center = smoothLaplacian();
8541   // gp_XYZ xAxis, yAxis, zAxis;
8542   // for ( i = 0; i < _simplices.size(); ++i )
8543   // {
8544   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8545   //   if ( xAxis.SquareModulus() > tol*tol )
8546   //     break;
8547   // }
8548   // for ( i = 1; i < _simplices.size(); ++i )
8549   // {
8550   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8551   //   zAxis = xAxis ^ yAxis;
8552   //   if ( zAxis.SquareModulus() > tol*tol )
8553   //     break;
8554   // }
8555   // if ( i == _simplices.size() ) return newPos;
8556
8557   yAxis = zAxis ^ xAxis;
8558   xAxis /= xAxis.Modulus();
8559   yAxis /= yAxis.Modulus();
8560
8561   // get half-planes of _simplices
8562
8563   vector< _halfPlane > halfPlns( _simplices.size() );
8564   int nbHP = 0;
8565   for ( size_t i = 0; i < _simplices.size(); ++i )
8566   {
8567     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8568     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8569     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8570     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8571     gp_XY  vec12 = p2 - p1;
8572     double dist12 = vec12.Modulus();
8573     if ( dist12 < tol )
8574       continue;
8575     vec12 /= dist12;
8576     halfPlns[ nbHP ]._pos = p1;
8577     halfPlns[ nbHP ]._dir = vec12;
8578     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8579     ++nbHP;
8580   }
8581
8582   // intersect boundaries of half-planes, define state of intersection points
8583   // in relation to all half-planes and calculate internal point of a 2D polygon
8584
8585   double sumLen = 0;
8586   gp_XY newPos2D (0,0);
8587
8588   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8589   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8590   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8591
8592   vector< vector< TIntPntState > > allIntPnts( nbHP );
8593   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8594   {
8595     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8596     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8597
8598     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8599     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8600
8601     int nbNotOut = 0;
8602     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8603
8604     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8605     {
8606       if ( iHP1 == iHP2 ) continue;
8607
8608       TIntPntState & ips1 = intPnts1[ iHP2 ];
8609       if ( ips1.second == UNDEF )
8610       {
8611         // find an intersection point of boundaries of iHP1 and iHP2
8612
8613         if ( iHP2 == iPrev ) // intersection with neighbors is known
8614           ips1.first = halfPlns[ iHP1 ]._pos;
8615         else if ( iHP2 == iNext )
8616           ips1.first = halfPlns[ iHP2 ]._pos;
8617         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8618           ips1.second = NO_INT;
8619
8620         // classify the found intersection point
8621         if ( ips1.second != NO_INT )
8622         {
8623           ips1.second = NOT_OUT;
8624           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8625             if ( i != iHP1 && i != iHP2 &&
8626                  halfPlns[ i ].IsOut( ips1.first, tol ))
8627               ips1.second = IS_OUT;
8628         }
8629         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8630         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8631         TIntPntState & ips2 = intPnts2[ iHP1 ];
8632         ips2 = ips1;
8633       }
8634       if ( ips1.second == NOT_OUT )
8635       {
8636         ++nbNotOut;
8637         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8638       }
8639     }
8640
8641     // find a NOT_OUT segment of boundary which is located between
8642     // two NOT_OUT int points
8643
8644     if ( nbNotOut < 2 )
8645       continue; // no such a segment
8646
8647     if ( nbNotOut > 2 )
8648     {
8649       // sort points along the boundary
8650       map< double, TIntPntState* > ipsByParam;
8651       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8652       {
8653         TIntPntState & ips1 = intPnts1[ iHP2 ];
8654         if ( ips1.second != NO_INT )
8655         {
8656           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8657           double param = op * halfPlns[ iHP1 ]._dir;
8658           ipsByParam.insert( make_pair( param, & ips1 ));
8659         }
8660       }
8661       // look for two neighboring NOT_OUT points
8662       nbNotOut = 0;
8663       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8664       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8665       {
8666         TIntPntState & ips1 = *(u2ips->second);
8667         if ( ips1.second == NOT_OUT )
8668           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8669         else if ( nbNotOut >= 2 )
8670           break;
8671         else
8672           nbNotOut = 0;
8673       }
8674     }
8675
8676     if ( nbNotOut >= 2 )
8677     {
8678       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8679       sumLen += len;
8680
8681       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8682     }
8683   }
8684
8685   if ( sumLen > 0 )
8686   {
8687     newPos2D /= sumLen;
8688     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8689   }
8690   else
8691   {
8692     newPos = center;
8693   }
8694
8695   return newPos;
8696 }
8697 #else // OLD_NEF_POLYGON
8698 { ////////////////////////////////// NEW
8699   gp_XYZ newPos(0,0,0);
8700
8701   // get a plane to seach a solution on
8702
8703   size_t i;
8704   gp_XYZ center(0,0,0);
8705   for ( i = 0; i < _simplices.size(); ++i )
8706     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8707   center /= _simplices.size();
8708
8709   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8710   for ( i = 0; i < _simplices.size(); ++i )
8711     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8712   vecs.back() = vecs[0];
8713
8714   const double tol = numeric_limits<double>::min();
8715   gp_XYZ zAxis(0,0,0);
8716   for ( i = 0; i < _simplices.size(); ++i )
8717   {
8718     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8719     try {
8720       cross.Normalize();
8721       if ( cross * zAxis < tol )
8722         zAxis += cross.Reversed();
8723       else
8724         zAxis += cross;
8725     }
8726     catch (Standard_Failure) { // if |cross| == 0.
8727     }
8728   }
8729
8730   gp_XYZ yAxis;
8731   for ( i = 0; i < _simplices.size(); ++i )
8732   {
8733     yAxis = vecs[i];
8734     if ( yAxis.SquareModulus() > tol )
8735       break;
8736   }
8737   gp_XYZ xAxis = yAxis ^ zAxis;
8738   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8739   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8740   //                             p0.Distance( _simplices[2]._nPrev ));
8741   // gp_XYZ center = smoothLaplacian();
8742   // gp_XYZ xAxis, yAxis, zAxis;
8743   // for ( i = 0; i < _simplices.size(); ++i )
8744   // {
8745   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8746   //   if ( xAxis.SquareModulus() > tol*tol )
8747   //     break;
8748   // }
8749   // for ( i = 1; i < _simplices.size(); ++i )
8750   // {
8751   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8752   //   zAxis = xAxis ^ yAxis;
8753   //   if ( zAxis.SquareModulus() > tol*tol )
8754   //     break;
8755   // }
8756   // if ( i == _simplices.size() ) return newPos;
8757
8758   yAxis = zAxis ^ xAxis;
8759   xAxis /= xAxis.Modulus();
8760   yAxis /= yAxis.Modulus();
8761
8762   // get half-planes of _simplices
8763
8764   vector< _halfPlane > halfPlns( _simplices.size() );
8765   int nbHP = 0;
8766   for ( size_t i = 0; i < _simplices.size(); ++i )
8767   {
8768     const gp_XYZ& OP1 = vecs[ i   ];
8769     const gp_XYZ& OP2 = vecs[ i+1 ];
8770     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8771     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8772     gp_XY  vec12 = p2 - p1;
8773     double dist12 = vec12.Modulus();
8774     if ( dist12 < tol )
8775       continue;
8776     vec12 /= dist12;
8777     halfPlns[ nbHP ]._pos = p1;
8778     halfPlns[ nbHP ]._dir = vec12;
8779     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8780     ++nbHP;
8781   }
8782
8783   // intersect boundaries of half-planes, define state of intersection points
8784   // in relation to all half-planes and calculate internal point of a 2D polygon
8785
8786   double sumLen = 0;
8787   gp_XY newPos2D (0,0);
8788
8789   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8790   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8791   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8792
8793   vector< vector< TIntPntState > > allIntPnts( nbHP );
8794   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8795   {
8796     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8797     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8798
8799     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8800     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8801
8802     int nbNotOut = 0;
8803     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8804
8805     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8806     {
8807       if ( iHP1 == iHP2 ) continue;
8808
8809       TIntPntState & ips1 = intPnts1[ iHP2 ];
8810       if ( ips1.second == UNDEF )
8811       {
8812         // find an intersection point of boundaries of iHP1 and iHP2
8813
8814         if ( iHP2 == iPrev ) // intersection with neighbors is known
8815           ips1.first = halfPlns[ iHP1 ]._pos;
8816         else if ( iHP2 == iNext )
8817           ips1.first = halfPlns[ iHP2 ]._pos;
8818         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8819           ips1.second = NO_INT;
8820
8821         // classify the found intersection point
8822         if ( ips1.second != NO_INT )
8823         {
8824           ips1.second = NOT_OUT;
8825           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8826             if ( i != iHP1 && i != iHP2 &&
8827                  halfPlns[ i ].IsOut( ips1.first, tol ))
8828               ips1.second = IS_OUT;
8829         }
8830         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8831         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8832         TIntPntState & ips2 = intPnts2[ iHP1 ];
8833         ips2 = ips1;
8834       }
8835       if ( ips1.second == NOT_OUT )
8836       {
8837         ++nbNotOut;
8838         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8839       }
8840     }
8841
8842     // find a NOT_OUT segment of boundary which is located between
8843     // two NOT_OUT int points
8844
8845     if ( nbNotOut < 2 )
8846       continue; // no such a segment
8847
8848     if ( nbNotOut > 2 )
8849     {
8850       // sort points along the boundary
8851       map< double, TIntPntState* > ipsByParam;
8852       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8853       {
8854         TIntPntState & ips1 = intPnts1[ iHP2 ];
8855         if ( ips1.second != NO_INT )
8856         {
8857           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8858           double param = op * halfPlns[ iHP1 ]._dir;
8859           ipsByParam.insert( make_pair( param, & ips1 ));
8860         }
8861       }
8862       // look for two neighboring NOT_OUT points
8863       nbNotOut = 0;
8864       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8865       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8866       {
8867         TIntPntState & ips1 = *(u2ips->second);
8868         if ( ips1.second == NOT_OUT )
8869           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8870         else if ( nbNotOut >= 2 )
8871           break;
8872         else
8873           nbNotOut = 0;
8874       }
8875     }
8876
8877     if ( nbNotOut >= 2 )
8878     {
8879       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8880       sumLen += len;
8881
8882       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8883     }
8884   }
8885
8886   if ( sumLen > 0 )
8887   {
8888     newPos2D /= sumLen;
8889     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8890   }
8891   else
8892   {
8893     newPos = center;
8894   }
8895
8896   return newPos;
8897 }
8898 #endif // OLD_NEF_POLYGON
8899
8900 //================================================================================
8901 /*!
8902  * \brief Add a new segment to _LayerEdge during inflation
8903  */
8904 //================================================================================
8905
8906 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8907 {
8908   if ( Is( BLOCKED ))
8909     return;
8910
8911   if ( len > _maxLen )
8912   {
8913     len = _maxLen;
8914     Block( eos.GetData() );
8915   }
8916   const double lenDelta = len - _len;
8917   if ( lenDelta < len * 1e-3  )
8918   {
8919     Block( eos.GetData() );
8920     return;
8921   }
8922
8923   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8924   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8925   gp_XYZ newXYZ;
8926   if ( eos._hyp.IsOffsetMethod() )
8927   {
8928     newXYZ = oldXYZ;
8929     gp_Vec faceNorm;
8930     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8931     while ( faceIt->more() )
8932     {
8933       const SMDS_MeshElement* face = faceIt->next();
8934       if ( !eos.GetNormal( face, faceNorm ))
8935         continue;
8936
8937       // translate plane of a face
8938       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8939
8940       // find point of intersection of the face plane located at baryCenter
8941       // and _normal located at newXYZ
8942       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8943       double dot =  ( faceNorm.XYZ() * _normal );
8944       if ( dot < std::numeric_limits<double>::min() )
8945         dot = lenDelta * 1e-3;
8946       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8947       newXYZ += step * _normal;
8948     }
8949     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8950   }
8951   else
8952   {
8953     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8954   }
8955
8956   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8957   _pos.push_back( newXYZ );
8958
8959   if ( !eos._sWOL.IsNull() )
8960   {
8961     double distXYZ[4];
8962     bool uvOK = false;
8963     if ( eos.SWOLType() == TopAbs_EDGE )
8964     {
8965       double u = Precision::Infinite(); // to force projection w/o distance check
8966       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8967                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8968       _pos.back().SetCoord( u, 0, 0 );
8969       if ( _nodes.size() > 1 && uvOK )
8970       {
8971         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8972         pos->SetUParameter( u );
8973       }
8974     }
8975     else //  TopAbs_FACE
8976     {
8977       gp_XY uv( Precision::Infinite(), 0 );
8978       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8979                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8980       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8981       if ( _nodes.size() > 1 && uvOK )
8982       {
8983         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8984         pos->SetUParameter( uv.X() );
8985         pos->SetVParameter( uv.Y() );
8986       }
8987     }
8988     if ( uvOK )
8989     {
8990       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8991     }
8992     else
8993     {
8994       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8995       _pos.pop_back();
8996       Block( eos.GetData() );
8997       return;
8998     }
8999   }
9000
9001   _len = len;
9002
9003   // notify _neibors
9004   if ( eos.ShapeType() != TopAbs_FACE )
9005   {
9006     for ( size_t i = 0; i < _neibors.size(); ++i )
9007       //if (  _len > _neibors[i]->GetSmooLen() )
9008         _neibors[i]->Set( MOVED );
9009
9010     Set( MOVED );
9011   }
9012   dumpMove( n ); //debug
9013 }
9014
9015 //================================================================================
9016 /*!
9017  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9018  */
9019 //================================================================================
9020
9021 void _LayerEdge::Block( _SolidData& data )
9022 {
9023   //if ( Is( BLOCKED )) return;
9024   Set( BLOCKED );
9025
9026   _maxLen = _len;
9027   std::queue<_LayerEdge*> queue;
9028   queue.push( this );
9029
9030   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9031   while ( !queue.empty() )
9032   {
9033     _LayerEdge* edge = queue.front(); queue.pop();
9034     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9035     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9036     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9037     {
9038       _LayerEdge* neibor = edge->_neibors[iN];
9039       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9040         continue;
9041       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9042       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9043       double minDist = pSrc.SquareDistance( pSrcN );
9044       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9045       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9046       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9047       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9048       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9049       {
9050         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9051       }
9052       if ( neibor->_maxLen > newMaxLen )
9053       {
9054         neibor->_maxLen = newMaxLen;
9055         if ( neibor->_maxLen < neibor->_len )
9056         {
9057           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9058           while ( neibor->_len > neibor->_maxLen &&
9059                   neibor->NbSteps() > 1 )
9060             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9061           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9062           //neibor->Block( data );
9063         }
9064         queue.push( neibor );
9065       }
9066     }
9067   }
9068 }
9069
9070 //================================================================================
9071 /*!
9072  * \brief Remove last inflation step
9073  */
9074 //================================================================================
9075
9076 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9077 {
9078   if ( _pos.size() > curStep && _nodes.size() > 1 )
9079   {
9080     _pos.resize( curStep );
9081
9082     gp_Pnt      nXYZ = _pos.back();
9083     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9084     SMESH_TNodeXYZ curXYZ( n );
9085     if ( !eos._sWOL.IsNull() )
9086     {
9087       TopLoc_Location loc;
9088       if ( eos.SWOLType() == TopAbs_EDGE )
9089       {
9090         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9091         pos->SetUParameter( nXYZ.X() );
9092         double f,l;
9093         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9094         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9095       }
9096       else
9097       {
9098         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9099         pos->SetUParameter( nXYZ.X() );
9100         pos->SetVParameter( nXYZ.Y() );
9101         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9102         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9103       }
9104     }
9105     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9106     dumpMove( n );
9107
9108     if ( restoreLength )
9109     {
9110       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9111     }
9112   }
9113 }
9114
9115 //================================================================================
9116 /*!
9117  * \brief Return index of a _pos distant from _normal
9118  */
9119 //================================================================================
9120
9121 int _LayerEdge::GetSmoothedPos( const double tol )
9122 {
9123   int iSmoothed = 0;
9124   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9125   {
9126     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9127     if ( normDist > tol * tol )
9128       iSmoothed = i;
9129   }
9130   return iSmoothed;
9131 }
9132
9133 //================================================================================
9134 /*!
9135  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9136  */
9137 //================================================================================
9138
9139 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9140 {
9141   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9142     return;
9143
9144   // find the 1st smoothed _pos
9145   int iSmoothed = GetSmoothedPos( tol );
9146   if ( !iSmoothed ) return;
9147
9148   //if ( 1 || Is( DISTORTED ))
9149   {
9150     gp_XYZ normal = _normal;
9151     if ( Is( NORMAL_UPDATED ))
9152       for ( size_t i = 1; i < _pos.size(); ++i )
9153       {
9154         normal = _pos[i] - _pos[0];
9155         double size = normal.Modulus();
9156         if ( size > RealSmall() )
9157         {
9158           normal /= size;
9159           break;
9160         }
9161       }
9162     const double r = 0.2;
9163     for ( int iter = 0; iter < 50; ++iter )
9164     {
9165       double minDot = 1;
9166       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9167       {
9168         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9169         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9170         _pos[i] = newPos;
9171         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9172         double newLen = ( 1-r ) * midLen + r * segLen[i];
9173         const_cast< double& >( segLen[i] ) = newLen;
9174         // check angle between normal and (_pos[i+1], _pos[i] )
9175         gp_XYZ posDir = _pos[i+1] - _pos[i];
9176         double size   = posDir.SquareModulus();
9177         if ( size > RealSmall() )
9178           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9179       }
9180       if ( minDot > 0.5 * 0.5 )
9181         break;
9182     }
9183   }
9184   // else
9185   // {
9186   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9187   //   {
9188   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9189   //       continue;
9190
9191   //     double     wgt = segLen[i] / segLen.back();
9192   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9193   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9194   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9195   //     _pos[i] = newPos;
9196   //   }
9197   // }
9198 }
9199
9200 //================================================================================
9201 /*!
9202  * \brief Create layers of prisms
9203  */
9204 //================================================================================
9205
9206 bool _ViscousBuilder::refine(_SolidData& data)
9207 {
9208   SMESH_MesherHelper& helper = data.GetHelper();
9209   helper.SetElementsOnShape(false);
9210
9211   Handle(Geom_Curve) curve;
9212   Handle(ShapeAnalysis_Surface) surface;
9213   TopoDS_Edge geomEdge;
9214   TopoDS_Face geomFace;
9215   TopLoc_Location loc;
9216   double f,l, u = 0;
9217   gp_XY uv;
9218   vector< gp_XYZ > pos3D;
9219   bool isOnEdge;
9220   TGeomID prevBaseId = -1;
9221   TNode2Edge* n2eMap = 0;
9222   TNode2Edge::iterator n2e;
9223
9224   // Create intermediate nodes on each _LayerEdge
9225
9226   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9227   {
9228     _EdgesOnShape& eos = data._edgesOnShape[iS];
9229     if ( eos._edges.empty() ) continue;
9230
9231     if ( eos._edges[0]->_nodes.size() < 2 )
9232       continue; // on _noShrinkShapes
9233
9234     // get data of a shrink shape
9235     isOnEdge = false;
9236     geomEdge.Nullify(); geomFace.Nullify();
9237     curve.Nullify(); surface.Nullify();
9238     if ( !eos._sWOL.IsNull() )
9239     {
9240       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9241       if ( isOnEdge )
9242       {
9243         geomEdge = TopoDS::Edge( eos._sWOL );
9244         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9245       }
9246       else
9247       {
9248         geomFace = TopoDS::Face( eos._sWOL );
9249         surface  = helper.GetSurface( geomFace );
9250       }
9251     }
9252     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9253     {
9254       geomFace = TopoDS::Face( eos._shape );
9255       surface  = helper.GetSurface( geomFace );
9256       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9257       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9258       {
9259         eos._eosC1[ i ]->_toSmooth = true;
9260         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9261           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9262       }
9263     }
9264
9265     vector< double > segLen;
9266     for ( size_t i = 0; i < eos._edges.size(); ++i )
9267     {
9268       _LayerEdge& edge = *eos._edges[i];
9269       if ( edge._pos.size() < 2 )
9270         continue;
9271
9272       // get accumulated length of segments
9273       segLen.resize( edge._pos.size() );
9274       segLen[0] = 0.0;
9275       if ( eos._sWOL.IsNull() )
9276       {
9277         bool useNormal = true;
9278         bool   usePos  = false;
9279         bool smoothed  = false;
9280         double   preci = 0.1 * edge._len;
9281         if ( eos._toSmooth && edge._pos.size() > 2 )
9282         {
9283           smoothed = edge.GetSmoothedPos( preci );
9284         }
9285         if ( smoothed )
9286         {
9287           if ( !surface.IsNull() &&
9288                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9289           {
9290             useNormal = usePos = false;
9291             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9292             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9293             {
9294               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9295               if ( surface->Gap() < 2. * edge._len )
9296                 segLen[j] = surface->Gap();
9297               else
9298                 useNormal = true;
9299             }
9300           }
9301         }
9302         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9303         {
9304 #ifndef __NODES_AT_POS
9305           useNormal = usePos = false;
9306           edge._pos[1] = edge._pos.back();
9307           edge._pos.resize( 2 );
9308           segLen.resize( 2 );
9309           segLen[ 1 ] = edge._len;
9310 #endif
9311         }
9312         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9313         {
9314           useNormal = usePos = false;
9315           _LayerEdge tmpEdge; // get original _normal
9316           tmpEdge._nodes.push_back( edge._nodes[0] );
9317           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9318             usePos = true;
9319           else
9320             for ( size_t j = 1; j < edge._pos.size(); ++j )
9321               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9322         }
9323         if ( useNormal )
9324         {
9325           for ( size_t j = 1; j < edge._pos.size(); ++j )
9326             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9327         }
9328         if ( usePos )
9329         {
9330           for ( size_t j = 1; j < edge._pos.size(); ++j )
9331             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9332         }
9333         else
9334         {
9335           bool swapped = ( edge._pos.size() > 2 );
9336           while ( swapped )
9337           {
9338             swapped = false;
9339             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9340               if ( segLen[j] > segLen.back() )
9341               {
9342                 segLen.erase( segLen.begin() + j );
9343                 edge._pos.erase( edge._pos.begin() + j );
9344                 --j;
9345               }
9346               else if ( segLen[j] < segLen[j-1] )
9347               {
9348                 std::swap( segLen[j], segLen[j-1] );
9349                 std::swap( edge._pos[j], edge._pos[j-1] );
9350                 swapped = true;
9351               }
9352           }
9353         }
9354         // smooth a path formed by edge._pos
9355 #ifndef __NODES_AT_POS
9356         if (( smoothed ) /*&&
9357             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9358           edge.SmoothPos( segLen, preci );
9359 #endif
9360       }
9361       else if ( eos._isRegularSWOL ) // usual SWOL
9362       {
9363         for ( size_t j = 1; j < edge._pos.size(); ++j )
9364           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9365       }
9366       else if ( !surface.IsNull() ) // SWOL surface with singularities
9367       {
9368         pos3D.resize( edge._pos.size() );
9369         for ( size_t j = 0; j < edge._pos.size(); ++j )
9370           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9371
9372         for ( size_t j = 1; j < edge._pos.size(); ++j )
9373           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9374       }
9375
9376       // allocate memory for new nodes if it is not yet refined
9377       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9378       if ( edge._nodes.size() == 2 )
9379       {
9380 #ifdef __NODES_AT_POS
9381         int nbNodes = edge._pos.size();
9382 #else
9383         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9384 #endif
9385         edge._nodes.resize( nbNodes, 0 );
9386         edge._nodes[1] = 0;
9387         edge._nodes.back() = tgtNode;
9388       }
9389       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9390       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9391       if ( baseShapeId != prevBaseId )
9392       {
9393         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9394         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9395         prevBaseId = baseShapeId;
9396       }
9397       _LayerEdge* edgeOnSameNode = 0;
9398       bool        useExistingPos = false;
9399       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9400       {
9401         edgeOnSameNode = n2e->second;
9402         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9403         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9404         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9405         if ( isOnEdge )
9406         {
9407           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9408           epos->SetUParameter( otherTgtPos.X() );
9409         }
9410         else
9411         {
9412           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9413           fpos->SetUParameter( otherTgtPos.X() );
9414           fpos->SetVParameter( otherTgtPos.Y() );
9415         }
9416       }
9417       // calculate height of the first layer
9418       double h0;
9419       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9420       const double f = eos._hyp.GetStretchFactor();
9421       const int    N = eos._hyp.GetNumberLayers();
9422       const double fPowN = pow( f, N );
9423       if ( fPowN - 1 <= numeric_limits<double>::min() )
9424         h0 = T / N;
9425       else
9426         h0 = T * ( f - 1 )/( fPowN - 1 );
9427
9428       const double zeroLen = std::numeric_limits<double>::min();
9429
9430       // create intermediate nodes
9431       double hSum = 0, hi = h0/f;
9432       size_t iSeg = 1;
9433       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9434       {
9435         // compute an intermediate position
9436         hi *= f;
9437         hSum += hi;
9438         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9439           ++iSeg;
9440         int iPrevSeg = iSeg-1;
9441         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9442           --iPrevSeg;
9443         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9444         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9445 #ifdef __NODES_AT_POS
9446         pos = edge._pos[ iStep ];
9447 #endif
9448         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9449         if ( !eos._sWOL.IsNull() )
9450         {
9451           // compute XYZ by parameters <pos>
9452           if ( isOnEdge )
9453           {
9454             u = pos.X();
9455             if ( !node )
9456               pos = curve->Value( u ).Transformed(loc);
9457           }
9458           else if ( eos._isRegularSWOL )
9459           {
9460             uv.SetCoord( pos.X(), pos.Y() );
9461             if ( !node )
9462               pos = surface->Value( pos.X(), pos.Y() );
9463           }
9464           else
9465           {
9466             uv.SetCoord( pos.X(), pos.Y() );
9467             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9468             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9469             if ( !node )
9470               pos = surface->Value( uv );
9471           }
9472         }
9473         // create or update the node
9474         if ( !node )
9475         {
9476           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9477           if ( !eos._sWOL.IsNull() )
9478           {
9479             if ( isOnEdge )
9480               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9481             else
9482               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9483           }
9484           else
9485           {
9486             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9487           }
9488         }
9489         else
9490         {
9491           if ( !eos._sWOL.IsNull() )
9492           {
9493             // make average pos from new and current parameters
9494             if ( isOnEdge )
9495             {
9496               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9497               if ( useExistingPos )
9498                 u = helper.GetNodeU( geomEdge, node );
9499               pos = curve->Value( u ).Transformed(loc);
9500
9501               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9502               epos->SetUParameter( u );
9503             }
9504             else
9505             {
9506               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9507               if ( useExistingPos )
9508                 uv = helper.GetNodeUV( geomFace, node );
9509               pos = surface->Value( uv );
9510
9511               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9512               fpos->SetUParameter( uv.X() );
9513               fpos->SetVParameter( uv.Y() );
9514             }
9515           }
9516           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9517         }
9518       } // loop on edge._nodes
9519
9520       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9521       {
9522         if ( isOnEdge )
9523           edge._pos.back().SetCoord( u, 0,0);
9524         else
9525           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9526
9527         if ( edgeOnSameNode )
9528           edgeOnSameNode->_pos.back() = edge._pos.back();
9529       }
9530
9531     } // loop on eos._edges to create nodes
9532
9533
9534     if ( !getMeshDS()->IsEmbeddedMode() )
9535       // Log node movement
9536       for ( size_t i = 0; i < eos._edges.size(); ++i )
9537       {
9538         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9539         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9540       }
9541   }
9542
9543
9544   // Create volumes
9545
9546   helper.SetElementsOnShape(true);
9547
9548   vector< vector<const SMDS_MeshNode*>* > nnVec;
9549   set< vector<const SMDS_MeshNode*>* >    nnSet;
9550   set< int >                       degenEdgeInd;
9551   vector<const SMDS_MeshElement*>     degenVols;
9552
9553   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9554   for ( ; exp.More(); exp.Next() )
9555   {
9556     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9557     if ( data._ignoreFaceIds.count( faceID ))
9558       continue;
9559     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9560     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9561     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9562     while ( fIt->more() )
9563     {
9564       const SMDS_MeshElement* face = fIt->next();
9565       const int            nbNodes = face->NbCornerNodes();
9566       nnVec.resize( nbNodes );
9567       nnSet.clear();
9568       degenEdgeInd.clear();
9569       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9570       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9571       for ( int iN = 0; iN < nbNodes; ++iN )
9572       {
9573         const SMDS_MeshNode* n = nIt->next();
9574         _LayerEdge*       edge = data._n2eMap[ n ];
9575         const int i = isReversedFace ? nbNodes-1-iN : iN;
9576         nnVec[ i ] = & edge->_nodes;
9577         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9578         minZ = std::min( minZ, nnVec[ i ]->size() );
9579
9580         if ( helper.HasDegeneratedEdges() )
9581           nnSet.insert( nnVec[ i ]);
9582       }
9583
9584       if ( maxZ == 0 )
9585         continue;
9586       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9587         continue;
9588
9589       switch ( nbNodes )
9590       {
9591       case 3: // TRIA
9592       {
9593         // PENTA
9594         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9595           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9596                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9597
9598         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9599         {
9600           for ( int iN = 0; iN < nbNodes; ++iN )
9601             if ( nnVec[ iN ]->size() < iZ+1 )
9602               degenEdgeInd.insert( iN );
9603
9604           if ( degenEdgeInd.size() == 1 )  // PYRAM
9605           {
9606             int i2 = *degenEdgeInd.begin();
9607             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9608             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9609             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9610                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9611           }
9612           else  // TETRA
9613           {
9614             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9615             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9616                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9617                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9618                               (*nnVec[ i3 ])[ iZ ]);
9619           }
9620         }
9621         break; // TRIA
9622       }
9623       case 4: // QUAD
9624       {
9625         // HEX
9626         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9627           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9628                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9629                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9630                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9631
9632         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9633         {
9634           for ( int iN = 0; iN < nbNodes; ++iN )
9635             if ( nnVec[ iN ]->size() < iZ+1 )
9636               degenEdgeInd.insert( iN );
9637
9638           switch ( degenEdgeInd.size() )
9639           {
9640           case 2: // PENTA
9641           {
9642             int i2 = *degenEdgeInd.begin();
9643             int i3 = *degenEdgeInd.rbegin();
9644             bool ok = ( i3 - i2 == 1 );
9645             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9646             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9647             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9648
9649             const SMDS_MeshElement* vol =
9650               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9651                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9652             if ( !ok && vol )
9653               degenVols.push_back( vol );
9654           }
9655           break;
9656
9657           default: // degen HEX
9658           {
9659             const SMDS_MeshElement* vol =
9660               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9661                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9662                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9663                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9664                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9665                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9666                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9667                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9668             degenVols.push_back( vol );
9669           }
9670           }
9671         }
9672         break; // HEX
9673       }
9674       default:
9675         return error("Not supported type of element", data._index);
9676
9677       } // switch ( nbNodes )
9678     } // while ( fIt->more() )
9679   } // loop on FACEs
9680
9681   if ( !degenVols.empty() )
9682   {
9683     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9684     if ( !err || err->IsOK() )
9685     {
9686       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9687                                          "Bad quality volumes created" ));
9688       err->myBadElements.insert( err->myBadElements.end(),
9689                                  degenVols.begin(),degenVols.end() );
9690     }
9691   }
9692
9693   return true;
9694 }
9695
9696 //================================================================================
9697 /*!
9698  * \brief Shrink 2D mesh on faces to let space for inflated layers
9699  */
9700 //================================================================================
9701
9702 bool _ViscousBuilder::shrink(_SolidData& theData)
9703 {
9704   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9705   // _LayerEdge's inflated along FACE or EDGE)
9706   map< TGeomID, list< _SolidData* > > f2sdMap;
9707   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9708   {
9709     _SolidData& data = _sdVec[i];
9710     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9711     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9712       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9713       {
9714         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9715
9716         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9717         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9718         // by StdMeshers_QuadToTriaAdaptor
9719         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9720         {
9721           SMESH_ProxyMesh::SubMesh* proxySub =
9722             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9723           if ( proxySub->NbElements() == 0 )
9724           {
9725             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9726             while ( fIt->more() )
9727             {
9728               const SMDS_MeshElement* f = fIt->next();
9729               // as a result 3D algo will use elements from proxySub and not from smDS
9730               proxySub->AddElement( f );
9731               f->setIsMarked( true );
9732
9733               // Mark nodes on the FACE to discriminate them from nodes
9734               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
9735               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
9736               {
9737                 const SMDS_MeshNode* n = f->GetNode( iN );
9738                 if ( n->GetPosition()->GetDim() == 2 )
9739                   n->setIsMarked( true );
9740               }
9741             }
9742           }
9743         }
9744       }
9745   }
9746
9747   SMESH_MesherHelper helper( *_mesh );
9748   helper.ToFixNodeParameters( true );
9749
9750   // EDGEs to shrink
9751   map< TGeomID, _Shrinker1D > e2shrMap;
9752   vector< _EdgesOnShape* > subEOS;
9753   vector< _LayerEdge* > lEdges;
9754
9755   // loop on FACEs to srink mesh on
9756   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9757   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9758   {
9759     list< _SolidData* > & dataList = f2sd->second;
9760     if ( dataList.front()->_n2eMap.empty() ||
9761          dataList.back() ->_n2eMap.empty() )
9762       continue; // not yet computed
9763     if ( dataList.front() != &theData &&
9764          dataList.back()  != &theData )
9765       continue;
9766
9767     _SolidData&      data = *dataList.front();
9768     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9769     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9770     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9771
9772     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9773
9774     _shrinkedFaces.Add( F );
9775     helper.SetSubShape( F );
9776
9777     // ===========================
9778     // Prepare data for shrinking
9779     // ===========================
9780
9781     // Collect nodes to smooth, they are marked at the beginning of this method
9782     vector < const SMDS_MeshNode* > smoothNodes;
9783     {
9784       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9785       while ( nIt->more() )
9786       {
9787         const SMDS_MeshNode* n = nIt->next();
9788         if ( n->isMarked() )
9789           smoothNodes.push_back( n );
9790       }
9791     }
9792     // Find out face orientation
9793     double refSign = 1;
9794     const set<TGeomID> ignoreShapes;
9795     bool isOkUV;
9796     if ( !smoothNodes.empty() )
9797     {
9798       vector<_Simplex> simplices;
9799       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9800       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9801       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9802       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9803       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9804         refSign = -1;
9805     }
9806
9807     // Find _LayerEdge's inflated along F
9808     subEOS.clear();
9809     lEdges.clear();
9810     {
9811       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9812                                                                 /*complexFirst=*/true); //!!!
9813       while ( subIt->more() )
9814       {
9815         const TGeomID subID = subIt->next()->GetId();
9816         if ( data._noShrinkShapes.count( subID ))
9817           continue;
9818         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9819         if ( !eos || eos->_sWOL.IsNull() ) continue;
9820
9821         subEOS.push_back( eos );
9822
9823         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9824         {
9825           lEdges.push_back( eos->_edges[ i ] );
9826           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9827         }
9828       }
9829     }
9830
9831     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9832     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9833     while ( fIt->more() )
9834       if ( const SMDS_MeshElement* f = fIt->next() )
9835         dumpChangeNodes( f );
9836     dumpFunctionEnd();
9837
9838     // Replace source nodes by target nodes in mesh faces to shrink
9839     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9840     const SMDS_MeshNode* nodes[20];
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         _LayerEdge& edge = *eos._edges[i];
9847         const SMDS_MeshNode* srcNode = edge._nodes[0];
9848         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9849         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9850         while ( fIt->more() )
9851         {
9852           const SMDS_MeshElement* f = fIt->next();
9853           if ( !smDS->Contains( f ) || !f->isMarked() )
9854             continue;
9855           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9856           for ( int iN = 0; nIt->more(); ++iN )
9857           {
9858             const SMDS_MeshNode* n = nIt->next();
9859             nodes[iN] = ( n == srcNode ? tgtNode : n );
9860           }
9861           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9862           dumpChangeNodes( f );
9863         }
9864       }
9865     }
9866     dumpFunctionEnd();
9867
9868     // find out if a FACE is concave
9869     const bool isConcaveFace = isConcave( F, helper );
9870
9871     // Create _SmoothNode's on face F
9872     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9873     {
9874       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9875       const bool sortSimplices = isConcaveFace;
9876       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9877       {
9878         const SMDS_MeshNode* n = smoothNodes[i];
9879         nodesToSmooth[ i ]._node = n;
9880         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9881         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9882         // fix up incorrect uv of nodes on the FACE
9883         helper.GetNodeUV( F, n, 0, &isOkUV);
9884         dumpMove( n );
9885       }
9886       dumpFunctionEnd();
9887     }
9888     //if ( nodesToSmooth.empty() ) continue;
9889
9890     // Find EDGE's to shrink and set simpices to LayerEdge's
9891     set< _Shrinker1D* > eShri1D;
9892     {
9893       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9894       {
9895         _EdgesOnShape& eos = * subEOS[ iS ];
9896         if ( eos.SWOLType() == TopAbs_EDGE )
9897         {
9898           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9899           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9900           eShri1D.insert( & srinker );
9901           srinker.AddEdge( eos._edges[0], eos, helper );
9902           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9903           // restore params of nodes on EGDE if the EDGE has been already
9904           // srinked while srinking other FACE
9905           srinker.RestoreParams();
9906         }
9907         for ( size_t i = 0; i < eos._edges.size(); ++i )
9908         {
9909           _LayerEdge& edge = * eos._edges[i];
9910           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9911
9912           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
9913           // not-marked nodes are those added by refine()
9914           edge._nodes.back()->setIsMarked( true );
9915         }
9916       }
9917     }
9918
9919     bool toFixTria = false; // to improve quality of trias by diagonal swap
9920     if ( isConcaveFace )
9921     {
9922       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9923       if ( hasTria != hasQuad ) {
9924         toFixTria = hasTria;
9925       }
9926       else {
9927         set<int> nbNodesSet;
9928         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9929         while ( fIt->more() && nbNodesSet.size() < 2 )
9930           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9931         toFixTria = ( *nbNodesSet.begin() == 3 );
9932       }
9933     }
9934
9935     // ==================
9936     // Perform shrinking
9937     // ==================
9938
9939     bool shrinked = true;
9940     int nbBad, shriStep=0, smooStep=0;
9941     _SmoothNode::SmoothType smoothType
9942       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9943     SMESH_Comment errMsg;
9944     while ( shrinked )
9945     {
9946       shriStep++;
9947       // Move boundary nodes (actually just set new UV)
9948       // -----------------------------------------------
9949       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9950       shrinked = false;
9951       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9952       {
9953         _EdgesOnShape& eos = * subEOS[ iS ];
9954         for ( size_t i = 0; i < eos._edges.size(); ++i )
9955         {
9956           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9957         }
9958       }
9959       dumpFunctionEnd();
9960
9961       // Move nodes on EDGE's
9962       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9963       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9964       for ( ; shr != eShri1D.end(); ++shr )
9965         (*shr)->Compute( /*set3D=*/false, helper );
9966
9967       // Smoothing in 2D
9968       // -----------------
9969       int nbNoImpSteps = 0;
9970       bool       moved = true;
9971       nbBad = 1;
9972       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9973       {
9974         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9975
9976         int oldBadNb = nbBad;
9977         nbBad = 0;
9978         moved = false;
9979         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9980         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9981         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9982         {
9983           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9984                                             smooTy, /*set3D=*/isConcaveFace);
9985         }
9986         if ( nbBad < oldBadNb )
9987           nbNoImpSteps = 0;
9988         else
9989           nbNoImpSteps++;
9990
9991         dumpFunctionEnd();
9992       }
9993
9994       errMsg.clear();
9995       if ( nbBad > 0 )
9996         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9997       if ( shriStep > 200 )
9998         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9999       if ( !errMsg.empty() )
10000         break;
10001
10002       // Fix narrow triangles by swapping diagonals
10003       // ---------------------------------------
10004       if ( toFixTria )
10005       {
10006         set<const SMDS_MeshNode*> usedNodes;
10007         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10008
10009         // update working data
10010         set<const SMDS_MeshNode*>::iterator n;
10011         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10012         {
10013           n = usedNodes.find( nodesToSmooth[ i ]._node );
10014           if ( n != usedNodes.end())
10015           {
10016             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10017                                     nodesToSmooth[ i ]._simplices,
10018                                     ignoreShapes, NULL,
10019                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10020             usedNodes.erase( n );
10021           }
10022         }
10023         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10024         {
10025           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10026           if ( n != usedNodes.end())
10027           {
10028             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10029                                     lEdges[i]->_simplices,
10030                                     ignoreShapes );
10031             usedNodes.erase( n );
10032           }
10033         }
10034       }
10035       // TODO: check effect of this additional smooth
10036       // additional laplacian smooth to increase allowed shrink step
10037       // for ( int st = 1; st; --st )
10038       // {
10039       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10040       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10041       //   {
10042       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10043       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10044       //   }
10045       // }
10046
10047     } // while ( shrinked )
10048
10049     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10050     {
10051       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10052
10053       // remove faces
10054       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10055       {
10056         vector< const SMDS_MeshElement* > facesToRm;
10057         if ( psm )
10058         {
10059           facesToRm.reserve( psm->NbElements() );
10060           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10061             facesToRm.push_back( ite->next() );
10062
10063           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10064             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10065               psm->Clear();
10066         }
10067         for ( size_t i = 0; i < facesToRm.size(); ++i )
10068           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10069       }
10070       // remove nodes
10071       {
10072         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10073         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10074           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10075             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10076                                 subEOS[iS]->_edges[i]->_nodes.end() );
10077         }
10078         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10079         while ( itn->more() ) {
10080           const SMDS_MeshNode* n = itn->next();
10081           if ( !nodesToKeep.count( n ))
10082             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10083         }
10084       }
10085       // restore position and UV of target nodes
10086       gp_Pnt p;
10087       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10088         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10089         {
10090           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10091           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10092           if ( edge->_pos.empty() ||
10093                edge->Is( _LayerEdge::SHRUNK )) continue;
10094           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10095           {
10096             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10097             pos->SetUParameter( edge->_pos[0].X() );
10098             pos->SetVParameter( edge->_pos[0].Y() );
10099             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10100           }
10101           else
10102           {
10103             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10104             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10105             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10106           }
10107           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10108           dumpMove( tgtNode );
10109         }
10110       // shrink EDGE sub-meshes and set proxy sub-meshes
10111       UVPtStructVec uvPtVec;
10112       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10113       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10114       {
10115         _Shrinker1D* shr = (*shrIt);
10116         shr->Compute( /*set3D=*/true, helper );
10117
10118         // set proxy mesh of EDGEs w/o layers
10119         map< double, const SMDS_MeshNode* > nodes;
10120         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10121         // remove refinement nodes
10122         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10123         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10124         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10125         if ( u2n->second == sn0 || u2n->second == sn1 )
10126         {
10127           while ( u2n->second != tn0 && u2n->second != tn1 )
10128             ++u2n;
10129           nodes.erase( nodes.begin(), u2n );
10130         }
10131         u2n = --nodes.end();
10132         if ( u2n->second == sn0 || u2n->second == sn1 )
10133         {
10134           while ( u2n->second != tn0 && u2n->second != tn1 )
10135             --u2n;
10136           nodes.erase( ++u2n, nodes.end() );
10137         }
10138         // set proxy sub-mesh
10139         uvPtVec.resize( nodes.size() );
10140         u2n = nodes.begin();
10141         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10142         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10143         {
10144           uvPtVec[ i ].node = u2n->second;
10145           uvPtVec[ i ].param = u2n->first;
10146           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10147         }
10148         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10149         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10150       }
10151
10152       // set proxy mesh of EDGEs with layers
10153       vector< _LayerEdge* > edges;
10154       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10155       {
10156         _EdgesOnShape& eos = * subEOS[ iS ];
10157         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10158
10159         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10160         data.SortOnEdge( E, eos._edges );
10161
10162         edges.clear();
10163         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10164           if ( !eov->_edges.empty() )
10165             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10166
10167         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10168
10169         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10170           if ( !eov->_edges.empty() )
10171             edges.push_back( eov->_edges[0] ); // on last VERTEX
10172
10173         uvPtVec.resize( edges.size() );
10174         for ( size_t i = 0; i < edges.size(); ++i )
10175         {
10176           uvPtVec[ i ].node = edges[i]->_nodes.back();
10177           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10178           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10179         }
10180         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10181         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10182         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10183       }
10184       // temporary clear the FACE sub-mesh from faces made by refine()
10185       vector< const SMDS_MeshElement* > elems;
10186       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10187       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10188         elems.push_back( ite->next() );
10189       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10190         elems.push_back( ite->next() );
10191       smDS->Clear();
10192
10193       // compute the mesh on the FACE
10194       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10195       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10196
10197       // re-fill proxy sub-meshes of the FACE
10198       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10199         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10200           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10201             psm->AddElement( ite->next() );
10202
10203       // re-fill smDS
10204       for ( size_t i = 0; i < elems.size(); ++i )
10205         smDS->AddElement( elems[i] );
10206
10207       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10208         return error( errMsg );
10209
10210     } // end of re-meshing in case of failed smoothing
10211     else
10212     {
10213       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10214       bool isStructuredFixed = false;
10215       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10216         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10217       if ( !isStructuredFixed )
10218       {
10219         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10220           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10221
10222         for ( int st = 3; st; --st )
10223         {
10224           switch( st ) {
10225           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10226           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10227           case 3: smoothType = _SmoothNode::ANGULAR; break;
10228           }
10229           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10230           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10231           {
10232             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10233                                      smoothType,/*set3D=*/st==1 );
10234           }
10235           dumpFunctionEnd();
10236         }
10237       }
10238       if ( !getMeshDS()->IsEmbeddedMode() )
10239         // Log node movement
10240         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10241         {
10242           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10243           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10244         }
10245     }
10246
10247     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10248     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10249
10250   } // loop on FACES to srink mesh on
10251
10252
10253   // Replace source nodes by target nodes in shrinked mesh edges
10254
10255   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10256   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10257     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10258
10259   return true;
10260 }
10261
10262 //================================================================================
10263 /*!
10264  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10265  */
10266 //================================================================================
10267
10268 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10269                                            _EdgesOnShape&         eos,
10270                                            SMESH_MesherHelper&    helper,
10271                                            const SMESHDS_SubMesh* faceSubMesh)
10272 {
10273   const SMDS_MeshNode* srcNode = edge._nodes[0];
10274   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10275
10276   if ( eos.SWOLType() == TopAbs_FACE )
10277   {
10278     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10279     {
10280       edge._pos.clear();
10281       edge.Set( _LayerEdge::SHRUNK );
10282       return srcNode == tgtNode;
10283     }
10284     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10285     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10286     gp_Vec2d uvDir( srcUV, tgtUV );
10287     double uvLen = uvDir.Magnitude();
10288     uvDir /= uvLen;
10289     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10290     edge._len = uvLen;
10291
10292     //edge._pos.resize(1);
10293     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10294
10295     // set UV of source node to target node
10296     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10297     pos->SetUParameter( srcUV.X() );
10298     pos->SetVParameter( srcUV.Y() );
10299   }
10300   else // _sWOL is TopAbs_EDGE
10301   {
10302     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10303     {
10304       edge._pos.clear();
10305       edge.Set( _LayerEdge::SHRUNK );
10306       return srcNode == tgtNode;
10307     }
10308     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10309     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10310     if ( !edgeSM || edgeSM->NbElements() == 0 )
10311       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10312
10313     const SMDS_MeshNode* n2 = 0;
10314     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10315     while ( eIt->more() && !n2 )
10316     {
10317       const SMDS_MeshElement* e = eIt->next();
10318       if ( !edgeSM->Contains(e)) continue;
10319       n2 = e->GetNode( 0 );
10320       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10321     }
10322     if ( !n2 )
10323       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10324
10325     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10326     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10327     double u2   = helper.GetNodeU( E, n2, srcNode );
10328
10329     //edge._pos.clear();
10330
10331     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10332     {
10333       // tgtNode is located so that it does not make faces with wrong orientation
10334       edge.Set( _LayerEdge::SHRUNK );
10335       return true;
10336     }
10337     //edge._pos.resize(1);
10338     edge._pos[0].SetCoord( U_TGT, uTgt );
10339     edge._pos[0].SetCoord( U_SRC, uSrc );
10340     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10341
10342     edge._simplices.resize( 1 );
10343     edge._simplices[0]._nPrev = n2;
10344
10345     // set U of source node to the target node
10346     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10347     pos->SetUParameter( uSrc );
10348   }
10349   return true;
10350 }
10351
10352 //================================================================================
10353 /*!
10354  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10355  */
10356 //================================================================================
10357
10358 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10359 {
10360   if ( edge._nodes.size() == 1 )
10361   {
10362     edge._pos.clear();
10363     edge._len = 0;
10364
10365     const SMDS_MeshNode* srcNode = edge._nodes[0];
10366     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10367     if ( S.IsNull() ) return;
10368
10369     gp_Pnt p;
10370
10371     switch ( S.ShapeType() )
10372     {
10373     case TopAbs_EDGE:
10374     {
10375       double f,l;
10376       TopLoc_Location loc;
10377       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10378       if ( curve.IsNull() ) return;
10379       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10380       p = curve->Value( ePos->GetUParameter() );
10381       break;
10382     }
10383     case TopAbs_VERTEX:
10384     {
10385       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10386       break;
10387     }
10388     default: return;
10389     }
10390     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10391     dumpMove( srcNode );
10392   }
10393 }
10394
10395 //================================================================================
10396 /*!
10397  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10398  */
10399 //================================================================================
10400
10401 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10402                                   SMESH_MesherHelper&         helper,
10403                                   const bool                  is2D,
10404                                   const int                   step,
10405                                   set<const SMDS_MeshNode*> * involvedNodes)
10406 {
10407   SMESH::Controls::AspectRatio qualifier;
10408   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10409   const double maxAspectRatio = is2D ? 4. : 2;
10410   _NodeCoordHelper xyz( F, helper, is2D );
10411
10412   // find bad triangles
10413
10414   vector< const SMDS_MeshElement* > badTrias;
10415   vector< double >                  badAspects;
10416   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10417   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10418   while ( fIt->more() )
10419   {
10420     const SMDS_MeshElement * f = fIt->next();
10421     if ( f->NbCornerNodes() != 3 ) continue;
10422     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10423     double aspect = qualifier.GetValue( points );
10424     if ( aspect > maxAspectRatio )
10425     {
10426       badTrias.push_back( f );
10427       badAspects.push_back( aspect );
10428     }
10429   }
10430   if ( step == 1 )
10431   {
10432     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10433     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10434     while ( fIt->more() )
10435     {
10436       const SMDS_MeshElement * f = fIt->next();
10437       if ( f->NbCornerNodes() == 3 )
10438         dumpChangeNodes( f );
10439     }
10440     dumpFunctionEnd();
10441   }
10442   if ( badTrias.empty() )
10443     return;
10444
10445   // find couples of faces to swap diagonal
10446
10447   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10448   vector< T2Trias > triaCouples; 
10449
10450   TIDSortedElemSet involvedFaces, emptySet;
10451   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10452   {
10453     T2Trias trias    [3];
10454     double  aspRatio [3];
10455     int i1, i2, i3;
10456
10457     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10458       continue;
10459     for ( int iP = 0; iP < 3; ++iP )
10460       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10461
10462     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10463     int bestCouple = -1;
10464     for ( int iSide = 0; iSide < 3; ++iSide )
10465     {
10466       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10467       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10468       trias [iSide].first  = badTrias[iTia];
10469       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10470                                                              & i1, & i2 );
10471       if (( ! trias[iSide].second ) ||
10472           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10473           ( ! sm->Contains( trias[iSide].second )))
10474         continue;
10475
10476       // aspect ratio of an adjacent tria
10477       for ( int iP = 0; iP < 3; ++iP )
10478         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10479       double aspectInit = qualifier.GetValue( points2 );
10480
10481       // arrange nodes as after diag-swaping
10482       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10483         i3 = helper.WrapIndex( i1-1, 3 );
10484       else
10485         i3 = helper.WrapIndex( i1+1, 3 );
10486       points1 = points;
10487       points1( 1+ iSide ) = points2( 1+ i3 );
10488       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10489
10490       // aspect ratio after diag-swaping
10491       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10492       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10493         continue;
10494
10495       // prevent inversion of a triangle
10496       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10497       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10498       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10499         continue;
10500
10501       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10502         bestCouple = iSide;
10503     }
10504
10505     if ( bestCouple >= 0 )
10506     {
10507       triaCouples.push_back( trias[bestCouple] );
10508       involvedFaces.insert ( trias[bestCouple].second );
10509     }
10510     else
10511     {
10512       involvedFaces.erase( badTrias[iTia] );
10513     }
10514   }
10515   if ( triaCouples.empty() )
10516     return;
10517
10518   // swap diagonals
10519
10520   SMESH_MeshEditor editor( helper.GetMesh() );
10521   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10522   for ( size_t i = 0; i < triaCouples.size(); ++i )
10523   {
10524     dumpChangeNodes( triaCouples[i].first );
10525     dumpChangeNodes( triaCouples[i].second );
10526     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10527   }
10528
10529   if ( involvedNodes )
10530     for ( size_t i = 0; i < triaCouples.size(); ++i )
10531     {
10532       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10533                              triaCouples[i].first->end_nodes() );
10534       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10535                              triaCouples[i].second->end_nodes() );
10536     }
10537
10538   // just for debug dump resulting triangles
10539   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10540   for ( size_t i = 0; i < triaCouples.size(); ++i )
10541   {
10542     dumpChangeNodes( triaCouples[i].first );
10543     dumpChangeNodes( triaCouples[i].second );
10544   }
10545 }
10546
10547 //================================================================================
10548 /*!
10549  * \brief Move target node to it's final position on the FACE during shrinking
10550  */
10551 //================================================================================
10552
10553 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10554                                  const TopoDS_Face&    F,
10555                                  _EdgesOnShape&        eos,
10556                                  SMESH_MesherHelper&   helper )
10557 {
10558   if ( Is( SHRUNK ))
10559     return false; // already at the target position
10560
10561   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10562
10563   if ( eos.SWOLType() == TopAbs_FACE )
10564   {
10565     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10566     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10567     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10568     const double uvLen = tgtUV.Distance( curUV );
10569     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10570
10571     // Select shrinking step such that not to make faces with wrong orientation.
10572     double stepSize = 1e100;
10573     for ( size_t i = 0; i < _simplices.size(); ++i )
10574     {
10575       if ( !_simplices[i]._nPrev->isMarked() ||
10576            !_simplices[i]._nNext->isMarked() )
10577         continue; // simplex of quadrangle created by addBoundaryElements()
10578
10579       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10580       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10581       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10582       gp_XY dirN = uvN2 - uvN1;
10583       double det = uvDir.Crossed( dirN );
10584       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10585       gp_XY dirN2Cur = curUV - uvN1;
10586       double step = dirN.Crossed( dirN2Cur ) / det;
10587       if ( step > 0 )
10588         stepSize = Min( step, stepSize );
10589     }
10590     gp_Pnt2d newUV;
10591     if ( uvLen <= stepSize )
10592     {
10593       newUV = tgtUV;
10594       Set( SHRUNK );
10595       //_pos.clear();
10596     }
10597     else if ( stepSize > 0 )
10598     {
10599       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10600     }
10601     else
10602     {
10603       return true;
10604     }
10605     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10606     pos->SetUParameter( newUV.X() );
10607     pos->SetVParameter( newUV.Y() );
10608
10609 #ifdef __myDEBUG
10610     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10611     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10612     dumpMove( tgtNode );
10613 #endif
10614   }
10615   else // _sWOL is TopAbs_EDGE
10616   {
10617     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10618     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10619     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10620
10621     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10622     const double uSrc   = _pos[0].Coord( U_SRC );
10623     const double lenTgt = _pos[0].Coord( LEN_TGT );
10624
10625     double newU = _pos[0].Coord( U_TGT );
10626     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10627     {
10628       Set( _LayerEdge::SHRUNK );
10629       //_pos.clear();
10630     }
10631     else
10632     {
10633       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10634     }
10635     tgtPos->SetUParameter( newU );
10636 #ifdef __myDEBUG
10637     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10638     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10639     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10640     dumpMove( tgtNode );
10641 #endif
10642   }
10643
10644   return true;
10645 }
10646
10647 //================================================================================
10648 /*!
10649  * \brief Perform smooth on the FACE
10650  *  \retval bool - true if the node has been moved
10651  */
10652 //================================================================================
10653
10654 bool _SmoothNode::Smooth(int&                  nbBad,
10655                          Handle(Geom_Surface)& surface,
10656                          SMESH_MesherHelper&   helper,
10657                          const double          refSign,
10658                          SmoothType            how,
10659                          bool                  set3D)
10660 {
10661   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10662
10663   // get uv of surrounding nodes
10664   vector<gp_XY> uv( _simplices.size() );
10665   for ( size_t i = 0; i < _simplices.size(); ++i )
10666     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10667
10668   // compute new UV for the node
10669   gp_XY newPos (0,0);
10670   if ( how == TFI && _simplices.size() == 4 )
10671   {
10672     gp_XY corners[4];
10673     for ( size_t i = 0; i < _simplices.size(); ++i )
10674       if ( _simplices[i]._nOpp )
10675         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10676       else
10677         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10678
10679     newPos = helper.calcTFI ( 0.5, 0.5,
10680                               corners[0], corners[1], corners[2], corners[3],
10681                               uv[1], uv[2], uv[3], uv[0] );
10682   }
10683   else if ( how == ANGULAR )
10684   {
10685     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10686   }
10687   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10688   {
10689     // average centers of diagonals wieghted with their reciprocal lengths
10690     if ( _simplices.size() == 4 )
10691     {
10692       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10693       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10694       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10695     }
10696     else
10697     {
10698       double sumWeight = 0;
10699       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10700       for ( int i = 0; i < nb; ++i )
10701       {
10702         int iFrom = i + 2;
10703         int iTo   = i + _simplices.size() - 1;
10704         for ( int j = iFrom; j < iTo; ++j )
10705         {
10706           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10707           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10708           sumWeight += w;
10709           newPos += w * ( uv[i]+uv[i2] );
10710         }
10711       }
10712       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10713     }
10714   }
10715   else
10716   {
10717     // Laplacian smooth
10718     for ( size_t i = 0; i < _simplices.size(); ++i )
10719       newPos += uv[i];
10720     newPos /= _simplices.size();
10721   }
10722
10723   // count quality metrics (orientation) of triangles around the node
10724   int nbOkBefore = 0;
10725   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10726   for ( size_t i = 0; i < _simplices.size(); ++i )
10727     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10728
10729   int nbOkAfter = 0;
10730   for ( size_t i = 0; i < _simplices.size(); ++i )
10731     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10732
10733   if ( nbOkAfter < nbOkBefore )
10734   {
10735     nbBad += _simplices.size() - nbOkBefore;
10736     return false;
10737   }
10738
10739   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10740   pos->SetUParameter( newPos.X() );
10741   pos->SetVParameter( newPos.Y() );
10742
10743 #ifdef __myDEBUG
10744   set3D = true;
10745 #endif
10746   if ( set3D )
10747   {
10748     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10749     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10750     dumpMove( _node );
10751   }
10752
10753   nbBad += _simplices.size() - nbOkAfter;
10754   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10755 }
10756
10757 //================================================================================
10758 /*!
10759  * \brief Computes new UV using angle based smoothing technic
10760  */
10761 //================================================================================
10762
10763 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10764                                      const gp_XY&   uvToFix,
10765                                      const double   refSign)
10766 {
10767   uv.push_back( uv.front() );
10768
10769   vector< gp_XY >  edgeDir ( uv.size() );
10770   vector< double > edgeSize( uv.size() );
10771   for ( size_t i = 1; i < edgeDir.size(); ++i )
10772   {
10773     edgeDir [i-1] = uv[i] - uv[i-1];
10774     edgeSize[i-1] = edgeDir[i-1].Modulus();
10775     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10776       edgeDir[i-1].SetX( 100 );
10777     else
10778       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10779   }
10780   edgeDir.back()  = edgeDir.front();
10781   edgeSize.back() = edgeSize.front();
10782
10783   gp_XY  newPos(0,0);
10784   //int    nbEdges = 0;
10785   double sumSize = 0;
10786   for ( size_t i = 1; i < edgeDir.size(); ++i )
10787   {
10788     if ( edgeDir[i-1].X() > 1. ) continue;
10789     int i1 = i-1;
10790     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10791     if ( i == edgeDir.size() ) break;
10792     gp_XY p = uv[i];
10793     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10794     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10795     gp_XY bisec = norm1 + norm2;
10796     double bisecSize = bisec.Modulus();
10797     if ( bisecSize < numeric_limits<double>::min() )
10798     {
10799       bisec = -edgeDir[i1] + edgeDir[i];
10800       bisecSize = bisec.Modulus();
10801     }
10802     bisec /= bisecSize;
10803
10804     gp_XY  dirToN  = uvToFix - p;
10805     double distToN = dirToN.Modulus();
10806     if ( bisec * dirToN < 0 )
10807       distToN = -distToN;
10808
10809     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10810     //++nbEdges;
10811     sumSize += edgeSize[i1] + edgeSize[i];
10812   }
10813   newPos /= /*nbEdges * */sumSize;
10814   return newPos;
10815 }
10816
10817 //================================================================================
10818 /*!
10819  * \brief Delete _SolidData
10820  */
10821 //================================================================================
10822
10823 _SolidData::~_SolidData()
10824 {
10825   TNode2Edge::iterator n2e = _n2eMap.begin();
10826   for ( ; n2e != _n2eMap.end(); ++n2e )
10827   {
10828     _LayerEdge* & e = n2e->second;
10829     if ( e )
10830     {
10831       delete e->_curvature;
10832       if ( e->_2neibors )
10833         delete e->_2neibors->_plnNorm;
10834       delete e->_2neibors;
10835     }
10836     delete e;
10837     e = 0;
10838   }
10839   _n2eMap.clear();
10840
10841   delete _helper;
10842   _helper = 0;
10843 }
10844
10845 //================================================================================
10846 /*!
10847  * \brief Keep a _LayerEdge inflated along the EDGE
10848  */
10849 //================================================================================
10850
10851 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10852                            _EdgesOnShape&      eos,
10853                            SMESH_MesherHelper& helper )
10854 {
10855   // init
10856   if ( _nodes.empty() )
10857   {
10858     _edges[0] = _edges[1] = 0;
10859     _done = false;
10860   }
10861   // check _LayerEdge
10862   if ( e == _edges[0] || e == _edges[1] )
10863     return;
10864   if ( eos.SWOLType() != TopAbs_EDGE )
10865     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10866   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10867     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10868
10869   // store _LayerEdge
10870   _geomEdge = TopoDS::Edge( eos._sWOL );
10871   double f,l;
10872   BRep_Tool::Range( _geomEdge, f,l );
10873   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10874   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10875
10876   // Update _nodes
10877
10878   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10879   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10880
10881   if ( _nodes.empty() )
10882   {
10883     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10884     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10885       return;
10886     TopLoc_Location loc;
10887     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10888     GeomAdaptor_Curve aCurve(C, f,l);
10889     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10890
10891     int nbExpectNodes = eSubMesh->NbNodes();
10892     _initU  .reserve( nbExpectNodes );
10893     _normPar.reserve( nbExpectNodes );
10894     _nodes  .reserve( nbExpectNodes );
10895     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10896     while ( nIt->more() )
10897     {
10898       const SMDS_MeshNode* node = nIt->next();
10899
10900       // skip refinement nodes
10901       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10902            node == tgtNode0 || node == tgtNode1 )
10903         continue;
10904       bool hasMarkedFace = false;
10905       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
10906       while ( fIt->more() && !hasMarkedFace )
10907         hasMarkedFace = fIt->next()->isMarked();
10908       if ( !hasMarkedFace )
10909         continue;
10910
10911       _nodes.push_back( node );
10912       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10913       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10914       _normPar.push_back(  len / totLen );
10915     }
10916   }
10917   else
10918   {
10919     // remove target node of the _LayerEdge from _nodes
10920     size_t nbFound = 0;
10921     for ( size_t i = 0; i < _nodes.size(); ++i )
10922       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10923         _nodes[i] = 0, nbFound++;
10924     if ( nbFound == _nodes.size() )
10925       _nodes.clear();
10926   }
10927 }
10928
10929 //================================================================================
10930 /*!
10931  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10932  */
10933 //================================================================================
10934
10935 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10936 {
10937   if ( _done || _nodes.empty())
10938     return;
10939   const _LayerEdge* e = _edges[0];
10940   if ( !e ) e = _edges[1];
10941   if ( !e ) return;
10942
10943   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
10944             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
10945
10946   double f,l;
10947   if ( set3D || _done )
10948   {
10949     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10950     GeomAdaptor_Curve aCurve(C, f,l);
10951
10952     if ( _edges[0] )
10953       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10954     if ( _edges[1] )
10955       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10956     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10957
10958     for ( size_t i = 0; i < _nodes.size(); ++i )
10959     {
10960       if ( !_nodes[i] ) continue;
10961       double len = totLen * _normPar[i];
10962       GCPnts_AbscissaPoint discret( aCurve, len, f );
10963       if ( !discret.IsDone() )
10964         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10965       double u = discret.Parameter();
10966       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10967       pos->SetUParameter( u );
10968       gp_Pnt p = C->Value( u );
10969       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10970     }
10971   }
10972   else
10973   {
10974     BRep_Tool::Range( _geomEdge, f,l );
10975     if ( _edges[0] )
10976       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10977     if ( _edges[1] )
10978       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10979     
10980     for ( size_t i = 0; i < _nodes.size(); ++i )
10981     {
10982       if ( !_nodes[i] ) continue;
10983       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10984       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10985       pos->SetUParameter( u );
10986     }
10987   }
10988 }
10989
10990 //================================================================================
10991 /*!
10992  * \brief Restore initial parameters of nodes on EDGE
10993  */
10994 //================================================================================
10995
10996 void _Shrinker1D::RestoreParams()
10997 {
10998   if ( _done )
10999     for ( size_t i = 0; i < _nodes.size(); ++i )
11000     {
11001       if ( !_nodes[i] ) continue;
11002       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11003       pos->SetUParameter( _initU[i] );
11004     }
11005   _done = false;
11006 }
11007
11008 //================================================================================
11009 /*!
11010  * \brief Replace source nodes by target nodes in shrinked mesh edges
11011  */
11012 //================================================================================
11013
11014 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11015 {
11016   const SMDS_MeshNode* nodes[3];
11017   for ( int i = 0; i < 2; ++i )
11018   {
11019     if ( !_edges[i] ) continue;
11020
11021     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11022     if ( !eSubMesh ) return;
11023     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11024     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11025     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11026     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11027     while ( eIt->more() )
11028     {
11029       const SMDS_MeshElement* e = eIt->next();
11030       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11031           continue;
11032       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11033       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11034       {
11035         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11036         nodes[iN] = ( n == srcNode ? tgtNode : n );
11037       }
11038       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11039     }
11040   }
11041 }
11042
11043 //================================================================================
11044 /*!
11045  * \brief Creates 2D and 1D elements on boundaries of new prisms
11046  */
11047 //================================================================================
11048
11049 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11050 {
11051   SMESH_MesherHelper helper( *_mesh );
11052
11053   vector< const SMDS_MeshNode* > faceNodes;
11054
11055   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11056   {
11057     //_SolidData& data = _sdVec[i];
11058     TopTools_IndexedMapOfShape geomEdges;
11059     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11060     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11061     {
11062       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11063       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
11064         continue;
11065
11066       // Get _LayerEdge's based on E
11067
11068       map< double, const SMDS_MeshNode* > u2nodes;
11069       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11070         continue;
11071
11072       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11073       TNode2Edge & n2eMap = data._n2eMap;
11074       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11075       {
11076         //check if 2D elements are needed on E
11077         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11078         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11079         ledges.push_back( n2e->second );
11080         u2n++;
11081         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11082           continue; // no layers on E
11083         ledges.push_back( n2eMap[ u2n->second ]);
11084
11085         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11086         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11087         int nbSharedPyram = 0;
11088         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11089         while ( vIt->more() )
11090         {
11091           const SMDS_MeshElement* v = vIt->next();
11092           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11093         }
11094         if ( nbSharedPyram > 1 )
11095           continue; // not free border of the pyramid
11096
11097         faceNodes.clear();
11098         faceNodes.push_back( ledges[0]->_nodes[0] );
11099         faceNodes.push_back( ledges[1]->_nodes[0] );
11100         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11101         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11102
11103         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11104           continue; // faces already created
11105       }
11106       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11107         ledges.push_back( n2eMap[ u2n->second ]);
11108
11109       // Find out orientation and type of face to create
11110
11111       bool reverse = false, isOnFace;
11112       
11113       map< TGeomID, TopoDS_Shape >::iterator e2f =
11114         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
11115       TopoDS_Shape F;
11116       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11117       {
11118         F = e2f->second.Oriented( TopAbs_FORWARD );
11119         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11120         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11121           reverse = !reverse, F.Reverse();
11122         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11123           reverse = !reverse;
11124       }
11125       else if ( !data._ignoreFaceIds.count( e2f->first ))
11126       {
11127         // find FACE with layers sharing E
11128         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11129         if ( fIt->more() )
11130           F = *( fIt->next() );
11131       }
11132       // Find the sub-mesh to add new faces
11133       SMESHDS_SubMesh* sm = 0;
11134       if ( isOnFace )
11135         sm = getMeshDS()->MeshElements( F );
11136       else
11137         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11138       if ( !sm )
11139         return error("error in addBoundaryElements()", data._index);
11140
11141       // Make faces
11142       const int dj1 = reverse ? 0 : 1;
11143       const int dj2 = reverse ? 1 : 0;
11144       for ( size_t j = 1; j < ledges.size(); ++j )
11145       {
11146         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11147         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11148         if ( nn1.size() == nn2.size() )
11149         {
11150           if ( isOnFace )
11151             for ( size_t z = 1; z < nn1.size(); ++z )
11152               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11153           else
11154             for ( size_t z = 1; z < nn1.size(); ++z )
11155               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11156         }
11157         else if ( nn1.size() == 1 )
11158         {
11159           if ( isOnFace )
11160             for ( size_t z = 1; z < nn2.size(); ++z )
11161               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11162           else
11163             for ( size_t z = 1; z < nn2.size(); ++z )
11164               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11165         }
11166         else
11167         {
11168           if ( isOnFace )
11169             for ( size_t z = 1; z < nn1.size(); ++z )
11170               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11171           else
11172             for ( size_t z = 1; z < nn1.size(); ++z )
11173               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11174         }
11175       }
11176
11177       // Make edges
11178       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11179       {
11180         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11181         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11182         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11183         {
11184           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11185           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11186             continue;
11187           helper.SetSubShape( eos->_sWOL );
11188           helper.SetElementsOnShape( true );
11189           for ( size_t z = 1; z < nn.size(); ++z )
11190             helper.AddEdge( nn[z-1], nn[z] );
11191         }
11192       }
11193
11194     } // loop on EDGE's
11195   } // loop on _SolidData's
11196
11197   return true;
11198 }