Salome HOME
23281: [CEA 1859] SALOME master : compilation SMESH - error StdMeshers_ViscousLayers2D
[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 "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46 #include "StdMeshers_ViscousLayers2D.hxx"
47
48 #include <Adaptor3d_HSurface.hxx>
49 #include <BRepAdaptor_Curve.hxx>
50 #include <BRepAdaptor_Curve2d.hxx>
51 #include <BRepAdaptor_Surface.hxx>
52 //#include <BRepLProp_CLProps.hxx>
53 #include <BRepLProp_SLProps.hxx>
54 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
55 #include <BRep_Tool.hxx>
56 #include <Bnd_B2d.hxx>
57 #include <Bnd_B3d.hxx>
58 #include <ElCLib.hxx>
59 #include <GCPnts_AbscissaPoint.hxx>
60 #include <GCPnts_TangentialDeflection.hxx>
61 #include <Geom2d_Circle.hxx>
62 #include <Geom2d_Line.hxx>
63 #include <Geom2d_TrimmedCurve.hxx>
64 #include <GeomAdaptor_Curve.hxx>
65 #include <GeomLib.hxx>
66 #include <Geom_Circle.hxx>
67 #include <Geom_Curve.hxx>
68 #include <Geom_Line.hxx>
69 #include <Geom_TrimmedCurve.hxx>
70 #include <Precision.hxx>
71 #include <Standard_ErrorHandler.hxx>
72 #include <Standard_Failure.hxx>
73 #include <TColStd_Array1OfReal.hxx>
74 #include <TopExp.hxx>
75 #include <TopExp_Explorer.hxx>
76 #include <TopTools_IndexedMapOfShape.hxx>
77 #include <TopTools_ListOfShape.hxx>
78 #include <TopTools_MapIteratorOfMapOfShape.hxx>
79 #include <TopTools_MapOfShape.hxx>
80 #include <TopoDS.hxx>
81 #include <TopoDS_Edge.hxx>
82 #include <TopoDS_Face.hxx>
83 #include <TopoDS_Vertex.hxx>
84 #include <gp_Ax1.hxx>
85 #include <gp_Cone.hxx>
86 #include <gp_Sphere.hxx>
87 #include <gp_Vec.hxx>
88 #include <gp_XY.hxx>
89
90 #include <cmath>
91 #include <limits>
92 #include <list>
93 #include <queue>
94 #include <string>
95
96 #ifdef _DEBUG_
97 //#define __myDEBUG
98 //#define __NOT_INVALIDATE_BAD_SMOOTH
99 #endif
100
101 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
102 #define BLOCK_INFLATION // of individual _LayerEdge's
103 #define OLD_NEF_POLYGON
104
105 using namespace std;
106
107 //================================================================================
108 namespace VISCOUS_3D
109 {
110   typedef int TGeomID;
111
112   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
113
114   const double theMinSmoothCosin = 0.1;
115   const double theSmoothThickToElemSizeRatio = 0.3;
116   const double theMinSmoothTriaAngle = 30;
117   const double theMinSmoothQuadAngle = 45;
118
119   // what part of thickness is allowed till intersection
120   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
121   const double theThickToIntersection = 1.5;
122
123   bool needSmoothing( double cosin, double tgtThick, double elemSize )
124   {
125     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
126   }
127   double getSmoothingThickness( double cosin, double elemSize )
128   {
129     return theSmoothThickToElemSizeRatio * elemSize / cosin;
130   }
131
132   /*!
133    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
134    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
135    */
136   struct _MeshOfSolid : public SMESH_ProxyMesh,
137                         public SMESH_subMeshEventListenerData
138   {
139     bool                  _n2nMapComputed;
140     SMESH_ComputeErrorPtr _warning;
141
142     _MeshOfSolid( SMESH_Mesh* mesh)
143       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
144     {
145       SMESH_ProxyMesh::setMesh( *mesh );
146     }
147
148     // returns submesh for a geom face
149     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
150     {
151       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
152       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
153     }
154     void setNode2Node(const SMDS_MeshNode*                 srcNode,
155                       const SMDS_MeshNode*                 proxyNode,
156                       const SMESH_ProxyMesh::SubMesh* subMesh)
157     {
158       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
159     }
160   };
161   //--------------------------------------------------------------------------------
162   /*!
163    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
164    * It is used to clear an inferior dim sub-meshes modified by viscous layers
165    */
166   class _ShrinkShapeListener : SMESH_subMeshEventListener
167   {
168     _ShrinkShapeListener()
169       : SMESH_subMeshEventListener(/*isDeletable=*/false,
170                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
171   public:
172     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
173     virtual void ProcessEvent(const int                       event,
174                               const int                       eventType,
175                               SMESH_subMesh*                  solidSM,
176                               SMESH_subMeshEventListenerData* data,
177                               const SMESH_Hypothesis*         hyp)
178     {
179       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
180       {
181         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
182       }
183     }
184   };
185   //--------------------------------------------------------------------------------
186   /*!
187    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
188    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
189    * delete the data as soon as it has been used
190    */
191   class _ViscousListener : SMESH_subMeshEventListener
192   {
193     _ViscousListener():
194       SMESH_subMeshEventListener(/*isDeletable=*/false,
195                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
196     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
197   public:
198     virtual void ProcessEvent(const int                       event,
199                               const int                       eventType,
200                               SMESH_subMesh*                  subMesh,
201                               SMESH_subMeshEventListenerData* data,
202                               const SMESH_Hypothesis*         hyp)
203     {
204       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
205           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
206             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
207       {
208         // delete SMESH_ProxyMesh containing temporary faces
209         subMesh->DeleteEventListener( this );
210       }
211     }
212     // Finds or creates proxy mesh of the solid
213     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
214                                       const TopoDS_Shape& solid,
215                                       bool                toCreate=false)
216     {
217       if ( !mesh ) return 0;
218       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
219       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
220       if ( !data && toCreate )
221       {
222         data = new _MeshOfSolid(mesh);
223         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
224         sm->SetEventListener( Get(), data, sm );
225       }
226       return data;
227     }
228     // Removes proxy mesh of the solid
229     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
230     {
231       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
232     }
233   };
234   
235   //================================================================================
236   /*!
237    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
238    * the main shape when sub-mesh of the main shape is cleared,
239    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
240    * is cleared
241    */
242   //================================================================================
243
244   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
245   {
246     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
247     SMESH_subMeshEventListenerData* data =
248       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
249     if ( data )
250     {
251       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
252            data->mySubMeshes.end())
253         data->mySubMeshes.push_back( sub );
254     }
255     else
256     {
257       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
258       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
259     }
260   }
261   struct _SolidData;
262   //--------------------------------------------------------------------------------
263   /*!
264    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
265    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
266    * The class is used to check validity of face or volumes around a smoothed node;
267    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
268    */
269   struct _Simplex
270   {
271     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
272     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
273     _Simplex(const SMDS_MeshNode* nPrev=0,
274              const SMDS_MeshNode* nNext=0,
275              const SMDS_MeshNode* nOpp=0)
276       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
277     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
278     {
279       const double M[3][3] =
280         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
281          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
282          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
283       vol = ( + M[0][0] * M[1][1] * M[2][2]
284               + M[0][1] * M[1][2] * M[2][0]
285               + M[0][2] * M[1][0] * M[2][1]
286               - M[0][0] * M[1][2] * M[2][1]
287               - M[0][1] * M[1][0] * M[2][2]
288               - M[0][2] * M[1][1] * M[2][0]);
289       return vol > 1e-100;
290     }
291     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
292     {
293       SMESH_TNodeXYZ pSrc( nSrc );
294       return IsForward( &pSrc, &pTgt, vol );
295     }
296     bool IsForward(const gp_XY&         tgtUV,
297                    const SMDS_MeshNode* smoothedNode,
298                    const TopoDS_Face&   face,
299                    SMESH_MesherHelper&  helper,
300                    const double         refSign) const
301     {
302       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
303       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
304       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
305       double d = v1 ^ v2;
306       return d*refSign > 1e-100;
307     }
308     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
309     {
310       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
311       if ( !_nOpp ) // triangle
312       {
313         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
314         double tp2 = tp.SquareMagnitude();
315         double pn2 = pn.SquareMagnitude();
316         double nt2 = nt.SquareMagnitude();
317
318         if ( tp2 < pn2 && tp2 < nt2 )
319           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
320         else if ( pn2 < nt2 )
321           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
322         else
323           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
324
325         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
326                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
327         return minAngle < theMaxCos2;
328       }
329       else // quadrangle
330       {
331         SMESH_TNodeXYZ pOpp( _nOpp );
332         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
333         double tp2 = tp.SquareMagnitude();
334         double po2 = po.SquareMagnitude();
335         double on2 = on.SquareMagnitude();
336         double nt2 = nt.SquareMagnitude();
337         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
338                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
339                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
340                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
341
342         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
343                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
344         return minAngle < theMaxCos2;
345       }
346     }
347     bool IsNeighbour(const _Simplex& other) const
348     {
349       return _nPrev == other._nNext || _nNext == other._nPrev;
350     }
351     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
352     static void GetSimplices( const SMDS_MeshNode* node,
353                               vector<_Simplex>&   simplices,
354                               const set<TGeomID>& ingnoreShapes,
355                               const _SolidData*   dataToCheckOri = 0,
356                               const bool          toSort = false);
357     static void SortSimplices(vector<_Simplex>& simplices);
358   };
359   //--------------------------------------------------------------------------------
360   /*!
361    * Structure used to take into account surface curvature while smoothing
362    */
363   struct _Curvature
364   {
365     double   _r; // radius
366     double   _k; // factor to correct node smoothed position
367     double   _h2lenRatio; // avgNormProj / (2*avgDist)
368     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
369   public:
370     static _Curvature* New( double avgNormProj, double avgDist )
371     {
372       _Curvature* c = 0;
373       if ( fabs( avgNormProj / avgDist ) > 1./200 )
374       {
375         c = new _Curvature;
376         c->_r = avgDist * avgDist / avgNormProj;
377         c->_k = avgDist * avgDist / c->_r / c->_r;
378         //c->_k = avgNormProj / c->_r;
379         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
380         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
381
382         c->_uv.SetCoord( 0., 0. );
383       }
384       return c;
385     }
386     double lenDelta(double len) const { return _k * ( _r + len ); }
387     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
388   };
389   //--------------------------------------------------------------------------------
390
391   struct _2NearEdges;
392   struct _LayerEdge;
393   struct _EdgesOnShape;
394   struct _Smoother1D;
395   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
396
397   //--------------------------------------------------------------------------------
398   /*!
399    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
400    * and a node of the most internal layer (_nodes.back())
401    */
402   struct _LayerEdge
403   {
404     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
405
406     vector< const SMDS_MeshNode*> _nodes;
407
408     gp_XYZ              _normal;    // to boundary of solid
409     vector<gp_XYZ>      _pos;       // points computed during inflation
410     double              _len;       // length achived with the last inflation step
411     double              _maxLen;    // maximal possible length
412     double              _cosin;     // of angle (_normal ^ surface)
413     double              _minAngle;  // of _simplices
414     double              _lenFactor; // to compute _len taking _cosin into account
415     int                 _flags;
416
417     // simplices connected to the source node (_nodes[0]);
418     // used for smoothing and quality check of _LayerEdge's based on the FACE
419     vector<_Simplex>    _simplices;
420     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
421     PSmooFun            _smooFunction; // smoothing function
422     _Curvature*         _curvature;
423     // data for smoothing of _LayerEdge's based on the EDGE
424     _2NearEdges*        _2neibors;
425
426     enum EFlags { TO_SMOOTH       = 1,
427                   MOVED           = 2,   // set by _neibors[i]->SetNewLength()
428                   SMOOTHED        = 4,   // set by this->Smooth()
429                   DIFFICULT       = 8,   // near concave VERTEX
430                   ON_CONCAVE_FACE = 16,
431                   BLOCKED         = 32,  // not to inflate any more
432                   INTERSECTED     = 64,  // close intersection with a face found
433                   NORMAL_UPDATED  = 128,
434                   MARKED          = 256, // local usage
435                   MULTI_NORMAL    = 512, // a normal is invisible by some of surrounding faces
436                   NEAR_BOUNDARY   = 1024,// is near FACE boundary forcing smooth
437                   SMOOTHED_C1     = 2048,// is on _eosC1
438                   DISTORTED       = 4096,// was bad before smoothing
439                   RISKY_SWOL      = 8192 // SWOL is parallel to a source FACE
440     };
441     bool Is   ( EFlags f ) const { return _flags & f; }
442     void Set  ( EFlags f ) { _flags |= f; }
443     void Unset( EFlags f ) { _flags &= ~f; }
444
445     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
446     bool SetNewLength2d( Handle(Geom_Surface)& surface,
447                          const TopoDS_Face&    F,
448                          _EdgesOnShape&        eos,
449                          SMESH_MesherHelper&   helper );
450     void SetDataByNeighbors( const SMDS_MeshNode* n1,
451                              const SMDS_MeshNode* n2,
452                              const _EdgesOnShape& eos,
453                              SMESH_MesherHelper&  helper);
454     void Block( _SolidData& data );
455     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
456     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
457                             const TNode2Edge&     n2eMap);
458     void SmoothPos( const vector< double >& segLen, const double tol );
459     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
460     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
461     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
462     void SmoothWoCheck();
463     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
464                       const TopoDS_Face&             F,
465                       SMESH_MesherHelper&            helper);
466     void MoveNearConcaVer( const _EdgesOnShape*    eov,
467                            const _EdgesOnShape*    eos,
468                            const int               step,
469                            vector< _LayerEdge* > & badSmooEdges);
470     bool FindIntersection( SMESH_ElementSearcher&   searcher,
471                            double &                 distance,
472                            const double&            epsilon,
473                            _EdgesOnShape&           eos,
474                            const SMDS_MeshElement** face = 0);
475     bool SegTriaInter( const gp_Ax1&        lastSegment,
476                        const gp_XYZ&        p0,
477                        const gp_XYZ&        p1,
478                        const gp_XYZ&        p2,
479                        double&              dist,
480                        const double&        epsilon) const;
481     bool SegTriaInter( const gp_Ax1&        lastSegment,
482                        const SMDS_MeshNode* n0,
483                        const SMDS_MeshNode* n1,
484                        const SMDS_MeshNode* n2,
485                        double&              dist,
486                        const double&        epsilon) const
487     { return SegTriaInter( lastSegment,
488                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
489                            dist, epsilon );
490     }
491     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
492     const gp_XYZ& PrevCheckPos() const { return _pos[ Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0 ]; }
493     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
494     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
495     bool   IsOnEdge() const { return _2neibors; }
496     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
497     void   SetCosin( double cosin );
498     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
499     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
500     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
501     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
502       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
503     }
504     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
505
506     gp_XYZ smoothLaplacian();
507     gp_XYZ smoothAngular();
508     gp_XYZ smoothLengthWeighted();
509     gp_XYZ smoothCentroidal();
510     gp_XYZ smoothNefPolygon();
511
512     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
513     static const int theNbSmooFuns = FUN_NB;
514     static PSmooFun _funs[theNbSmooFuns];
515     static const char* _funNames[theNbSmooFuns+1];
516     int smooFunID( PSmooFun fun=0) const;
517   };
518   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
519                                                             &_LayerEdge::smoothLengthWeighted,
520                                                             &_LayerEdge::smoothCentroidal,
521                                                             &_LayerEdge::smoothNefPolygon,
522                                                             &_LayerEdge::smoothAngular };
523   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
524                                                          "LengthWeighted",
525                                                          "Centroidal",
526                                                          "NefPolygon",
527                                                          "Angular",
528                                                          "None"};
529   struct _LayerEdgeCmp
530   {
531     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
532     {
533       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
534       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
535     }
536   };
537   //--------------------------------------------------------------------------------
538   /*!
539    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
540    */
541   struct _halfPlane
542   {
543     gp_XY _pos, _dir, _inNorm;
544     bool IsOut( const gp_XY p, const double tol ) const
545     {
546       return _inNorm * ( p - _pos ) < -tol;
547     }
548     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
549     {
550       //const double eps = 1e-10;
551       double D = _dir.Crossed( hp._dir );
552       if ( fabs(D) < std::numeric_limits<double>::min())
553         return false;
554       gp_XY vec21 = _pos - hp._pos; 
555       double u = hp._dir.Crossed( vec21 ) / D; 
556       intPnt = _pos + _dir * u;
557       return true;
558     }
559   };
560   //--------------------------------------------------------------------------------
561   /*!
562    * Structure used to smooth a _LayerEdge based on an EDGE.
563    */
564   struct _2NearEdges
565   {
566     double               _wgt  [2]; // weights of _nodes
567     _LayerEdge*          _edges[2];
568
569      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
570     gp_XYZ*              _plnNorm;
571
572     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
573     const SMDS_MeshNode* tgtNode(bool is2nd) {
574       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
575     }
576     const SMDS_MeshNode* srcNode(bool is2nd) {
577       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
578     }
579     void reverse() {
580       std::swap( _wgt  [0], _wgt  [1] );
581       std::swap( _edges[0], _edges[1] );
582     }
583     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
584       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
585     }
586     bool include( const _LayerEdge* e ) {
587       return ( _edges[0] == e || _edges[1] == e );
588     }
589   };
590
591
592   //--------------------------------------------------------------------------------
593   /*!
594    * \brief Layers parameters got by averaging several hypotheses
595    */
596   struct AverageHyp
597   {
598     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
599       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
600     {
601       Add( hyp );
602     }
603     void Add( const StdMeshers_ViscousLayers* hyp )
604     {
605       if ( hyp )
606       {
607         _nbHyps++;
608         _nbLayers       = hyp->GetNumberLayers();
609         //_thickness     += hyp->GetTotalThickness();
610         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
611         _stretchFactor += hyp->GetStretchFactor();
612         _method         = hyp->GetMethod();
613       }
614     }
615     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
616     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
617     int    GetNumberLayers()   const { return _nbLayers; }
618     int    GetMethod()         const { return _method; }
619
620     bool   UseSurfaceNormal()  const
621     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
622     bool   ToSmooth()          const
623     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
624     bool   IsOffsetMethod()    const
625     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
626
627   private:
628     int     _nbLayers, _nbHyps, _method;
629     double  _thickness, _stretchFactor;
630   };
631
632   //--------------------------------------------------------------------------------
633   /*!
634    * \brief _LayerEdge's on a shape and other shape data
635    */
636   struct _EdgesOnShape
637   {
638     vector< _LayerEdge* > _edges;
639
640     TopoDS_Shape          _shape;
641     TGeomID               _shapeID;
642     SMESH_subMesh *       _subMesh;
643     // face or edge w/o layer along or near which _edges are inflated
644     TopoDS_Shape          _sWOL;
645     bool                  _isRegularSWOL; // w/o singularities
646     // averaged StdMeshers_ViscousLayers parameters
647     AverageHyp            _hyp;
648     bool                  _toSmooth;
649     _Smoother1D*          _edgeSmoother;
650     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
651     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
652
653     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
654     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
655
656     Handle(ShapeAnalysis_Surface) _offsetSurf;
657     _LayerEdge*                   _edgeForOffset;
658
659     _SolidData*            _data; // parent SOLID
660
661     TopAbs_ShapeEnum ShapeType() const
662     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
663     TopAbs_ShapeEnum SWOLType() const
664     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
665     bool             HasC1( const _EdgesOnShape* other ) const
666     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
667     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
668     _SolidData&      GetData() const { return *_data; }
669
670     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
671   };
672
673   //--------------------------------------------------------------------------------
674   /*!
675    * \brief Convex FACE whose radius of curvature is less than the thickness of 
676    *        layers. It is used to detect distortion of prisms based on a convex
677    *        FACE and to update normals to enable further increasing the thickness
678    */
679   struct _ConvexFace
680   {
681     TopoDS_Face                     _face;
682
683     // edges whose _simplices are used to detect prism distortion
684     vector< _LayerEdge* >           _simplexTestEdges;
685
686     // map a sub-shape to _SolidData::_edgesOnShape
687     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
688
689     bool                            _normalsFixed;
690
691     bool GetCenterOfCurvature( _LayerEdge*         ledge,
692                                BRepLProp_SLProps&  surfProp,
693                                SMESH_MesherHelper& helper,
694                                gp_Pnt &            center ) const;
695     bool CheckPrisms() const;
696   };
697
698   //--------------------------------------------------------------------------------
699   /*!
700    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
701    *        at inflation up to the full thickness. A detected collision
702    *        is fixed in updateNormals()
703    */
704   struct _CollisionEdges
705   {
706     _LayerEdge*           _edge;
707     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
708     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
709     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
710   };
711
712   //--------------------------------------------------------------------------------
713   /*!
714    * \brief Data of a SOLID
715    */
716   struct _SolidData
717   {
718     typedef const StdMeshers_ViscousLayers* THyp;
719     TopoDS_Shape                    _solid;
720     TGeomID                         _index; // SOLID id
721     _MeshOfSolid*                   _proxyMesh;
722     list< THyp >                    _hyps;
723     list< TopoDS_Shape >            _hypShapes;
724     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
725     set< TGeomID >                  _reversedFaceIds;
726     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
727
728     double                          _stepSize, _stepSizeCoeff, _geomSize;
729     const SMDS_MeshNode*            _stepSizeNodes[2];
730
731     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
732
733     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
734     map< TGeomID, TNode2Edge* >     _s2neMap;
735     // _LayerEdge's with underlying shapes
736     vector< _EdgesOnShape >         _edgesOnShape;
737
738     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
739     //        layers and a FACE w/o layers
740     // value: the shape (FACE or EDGE) to shrink mesh on.
741     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
742     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
743
744     // Convex FACEs whose radius of curvature is less than the thickness of layers
745     map< TGeomID, _ConvexFace >      _convexFaces;
746
747     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
748     // the adjacent SOLID
749     set< TGeomID >                   _noShrinkShapes;
750
751     int                              _nbShapesToSmooth;
752
753     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
754
755     vector< _CollisionEdges >        _collisionEdges;
756     set< TGeomID >                   _concaveFaces;
757
758     double                           _maxThickness; // of all _hyps
759     double                           _minThickness; // of all _hyps
760
761     double                           _epsilon; // precision for SegTriaInter()
762
763     SMESH_MesherHelper*              _helper;
764
765     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
766                _MeshOfSolid*       m=0)
767       :_solid(s), _proxyMesh(m), _helper(0) {}
768     ~_SolidData();
769
770     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
771     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
772
773     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
774       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
775       return id2face == _convexFaces.end() ? 0 : & id2face->second;
776     }
777     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
778     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
779     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
780     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
781
782     SMESH_MesherHelper& GetHelper() const { return *_helper; }
783
784     void UnmarkEdges() {
785       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
786         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
787           _edgesOnShape[i]._edges[j]->Unset( _LayerEdge::MARKED );
788     }
789     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
790                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
791
792     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
793   };
794   //--------------------------------------------------------------------------------
795   /*!
796    * \brief Offset plane used in getNormalByOffset()
797    */
798   struct _OffsetPlane
799   {
800     gp_Pln _plane;
801     int    _faceIndex;
802     int    _faceIndexNext[2];
803     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
804     bool   _isLineOK[2];
805     _OffsetPlane() {
806       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
807     }
808     void   ComputeIntersectionLine( _OffsetPlane& pln );
809     gp_XYZ GetCommonPoint(bool& isFound) const;
810     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
811   };
812   //--------------------------------------------------------------------------------
813   /*!
814    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
815    */
816   struct _CentralCurveOnEdge
817   {
818     bool                  _isDegenerated;
819     vector< gp_Pnt >      _curvaCenters;
820     vector< _LayerEdge* > _ledges;
821     vector< gp_XYZ >      _normals; // new normal for each of _ledges
822     vector< double >      _segLength2;
823
824     TopoDS_Edge           _edge;
825     TopoDS_Face           _adjFace;
826     bool                  _adjFaceToSmooth;
827
828     void Append( const gp_Pnt& center, _LayerEdge* ledge )
829     {
830       if ( _curvaCenters.size() > 0 )
831         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
832       _curvaCenters.push_back( center );
833       _ledges.push_back( ledge );
834       _normals.push_back( ledge->_normal );
835     }
836     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
837     void SetShapes( const TopoDS_Edge&  edge,
838                     const _ConvexFace&  convFace,
839                     _SolidData&         data,
840                     SMESH_MesherHelper& helper);
841   };
842   //--------------------------------------------------------------------------------
843   /*!
844    * \brief Data of node on a shrinked FACE
845    */
846   struct _SmoothNode
847   {
848     const SMDS_MeshNode*         _node;
849     vector<_Simplex>             _simplices; // for quality check
850
851     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
852
853     bool Smooth(int&                  badNb,
854                 Handle(Geom_Surface)& surface,
855                 SMESH_MesherHelper&   helper,
856                 const double          refSign,
857                 SmoothType            how,
858                 bool                  set3D);
859
860     gp_XY computeAngularPos(vector<gp_XY>& uv,
861                             const gp_XY&   uvToFix,
862                             const double   refSign );
863   };
864   //--------------------------------------------------------------------------------
865   /*!
866    * \brief Builder of viscous layers
867    */
868   class _ViscousBuilder
869   {
870   public:
871     _ViscousBuilder();
872     // does it's job
873     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
874                                   const TopoDS_Shape& shape);
875     // check validity of hypotheses
876     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
877                                            const TopoDS_Shape& shape );
878
879     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
880     void RestoreListeners();
881
882     // computes SMESH_ProxyMesh::SubMesh::_n2n;
883     bool MakeN2NMap( _MeshOfSolid* pm );
884
885   private:
886
887     bool findSolidsWithLayers();
888     bool findFacesWithLayers(const bool onlyWith=false);
889     void getIgnoreFaces(const TopoDS_Shape&             solid,
890                         const StdMeshers_ViscousLayers* hyp,
891                         const TopoDS_Shape&             hypShape,
892                         set<TGeomID>&                   ignoreFaces);
893     bool makeLayer(_SolidData& data);
894     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
895     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
896                       SMESH_MesherHelper& helper, _SolidData& data);
897     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
898                          const TopoDS_Face&   face,
899                          SMESH_MesherHelper&  helper,
900                          bool&                isOK,
901                          bool                 shiftInside=false);
902     bool getFaceNormalAtSingularity(const gp_XY&        uv,
903                                     const TopoDS_Face&  face,
904                                     SMESH_MesherHelper& helper,
905                                     gp_Dir&             normal );
906     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
907     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
908                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
909                               int                              nbFaces );
910     bool findNeiborsOnEdge(const _LayerEdge*     edge,
911                            const SMDS_MeshNode*& n1,
912                            const SMDS_MeshNode*& n2,
913                            _EdgesOnShape&        eos,
914                            _SolidData&           data);
915     void findSimplexTestEdges( _SolidData&                    data,
916                                vector< vector<_LayerEdge*> >& edgesByGeom);
917     void computeGeomSize( _SolidData& data );
918     bool findShapesToSmooth( _SolidData& data);
919     void limitStepSizeByCurvature( _SolidData&  data );
920     void limitStepSize( _SolidData&             data,
921                         const SMDS_MeshElement* face,
922                         const _LayerEdge*       maxCosinEdge );
923     void limitStepSize( _SolidData& data, const double minSize);
924     bool inflate(_SolidData& data);
925     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
926     int  invalidateBadSmooth( _SolidData&               data,
927                               SMESH_MesherHelper&       helper,
928                               vector< _LayerEdge* >&    badSmooEdges,
929                               vector< _EdgesOnShape* >& eosC1,
930                               const int                 infStep );
931     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
932     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep, int smooStep=0, bool moveAll=false );
933     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
934     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
935     bool updateNormalsOfConvexFaces( _SolidData&         data,
936                                      SMESH_MesherHelper& helper,
937                                      int                 stepNb );
938     void updateNormalsOfC1Vertices( _SolidData& data );
939     bool updateNormalsOfSmoothed( _SolidData&         data,
940                                   SMESH_MesherHelper& helper,
941                                   const int           nbSteps,
942                                   const double        stepSize );
943     bool isNewNormalOk( _SolidData&   data,
944                         _LayerEdge&   edge,
945                         const gp_XYZ& newNormal);
946     bool refine(_SolidData& data);
947     bool shrink();
948     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
949                               SMESH_MesherHelper& helper,
950                               const SMESHDS_SubMesh* faceSubMesh );
951     void restoreNoShrink( _LayerEdge& edge ) const;
952     void fixBadFaces(const TopoDS_Face&          F,
953                      SMESH_MesherHelper&         helper,
954                      const bool                  is2D,
955                      const int                   step,
956                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
957     bool addBoundaryElements();
958
959     bool error( const string& text, int solidID=-1 );
960     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
961
962     // debug
963     void makeGroupOfLE();
964
965     SMESH_Mesh*           _mesh;
966     SMESH_ComputeErrorPtr _error;
967
968     vector< _SolidData >  _sdVec;
969     int                   _tmpFaceID;
970   };
971   //--------------------------------------------------------------------------------
972   /*!
973    * \brief Shrinker of nodes on the EDGE
974    */
975   class _Shrinker1D
976   {
977     TopoDS_Edge                   _geomEdge;
978     vector<double>                _initU;
979     vector<double>                _normPar;
980     vector<const SMDS_MeshNode*>  _nodes;
981     const _LayerEdge*             _edges[2];
982     bool                          _done;
983   public:
984     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
985     void Compute(bool set3D, SMESH_MesherHelper& helper);
986     void RestoreParams();
987     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
988     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
989     const SMDS_MeshNode* TgtNode( bool is2nd ) const
990     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
991     const SMDS_MeshNode* SrcNode( bool is2nd ) const
992     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
993   };
994   //--------------------------------------------------------------------------------
995   /*!
996    * \brief Smoother of _LayerEdge's on EDGE.
997    */
998   struct _Smoother1D
999   {
1000     struct OffPnt // point of the offsetted EDGE
1001     {
1002       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1003       double      _len;    // length reached at previous inflation step
1004       double      _param;  // on EDGE
1005       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1006       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1007     };
1008     vector< OffPnt >   _offPoints;
1009     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1010     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1011     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1012     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1013     _EdgesOnShape&     _eos;
1014     double             _curveLen; // length of the EDGE
1015
1016     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1017                                               _EdgesOnShape&      eos,
1018                                               SMESH_MesherHelper& helper);
1019
1020     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1021                  _EdgesOnShape&     eos )
1022       : _anaCurve( curveForSmooth ), _eos( eos )
1023     {
1024     }
1025     bool Perform(_SolidData&                    data,
1026                  Handle(ShapeAnalysis_Surface)& surface,
1027                  const TopoDS_Face&             F,
1028                  SMESH_MesherHelper&            helper )
1029     {
1030       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1031         prepare( data );
1032
1033       if ( isAnalytic() )
1034         return smoothAnalyticEdge( data, surface, F, helper );
1035       else
1036         return smoothComplexEdge ( data, surface, F, helper );
1037     }
1038     void prepare(_SolidData& data );
1039
1040     bool smoothAnalyticEdge( _SolidData&                    data,
1041                              Handle(ShapeAnalysis_Surface)& surface,
1042                              const TopoDS_Face&             F,
1043                              SMESH_MesherHelper&            helper);
1044
1045     bool smoothComplexEdge( _SolidData&                    data,
1046                             Handle(ShapeAnalysis_Surface)& surface,
1047                             const TopoDS_Face&             F,
1048                             SMESH_MesherHelper&            helper);
1049
1050     void setNormalOnV( const bool          is2nd,
1051                        SMESH_MesherHelper& helper);
1052
1053     _LayerEdge* getLEdgeOnV( bool is2nd )
1054     {
1055       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1056     }
1057     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1058   };
1059   //--------------------------------------------------------------------------------
1060   /*!
1061    * \brief Class of temporary mesh face.
1062    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1063    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1064    */
1065   struct _TmpMeshFace : public SMDS_MeshElement
1066   {
1067     vector<const SMDS_MeshNode* > _nn;
1068     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1069                   int id, int faceID=-1, int idInFace=-1):
1070       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1071     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1072     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1073     virtual vtkIdType GetVtkType() const                      { return -1; }
1074     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1075     virtual SMDSAbs_GeometryType GetGeomType() const
1076     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1077     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1078     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1079   };
1080   //--------------------------------------------------------------------------------
1081   /*!
1082    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1083    */
1084   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1085   {
1086     _LayerEdge *_le1, *_le2;
1087     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1088       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1089     {
1090       _nn[0]=_le1->_nodes[0];
1091       _nn[1]=_le1->_nodes.back();
1092       _nn[2]=_le2->_nodes.back();
1093       _nn[3]=_le2->_nodes[0];
1094     }
1095     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1096     {
1097       SMESH_TNodeXYZ p0s( _nn[0] );
1098       SMESH_TNodeXYZ p0t( _nn[1] );
1099       SMESH_TNodeXYZ p1t( _nn[2] );
1100       SMESH_TNodeXYZ p1s( _nn[3] );
1101       gp_XYZ  v0 = p0t - p0s;
1102       gp_XYZ  v1 = p1t - p1s;
1103       gp_XYZ v01 = p1s - p0s;
1104       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1105       gp_XYZ   d = v01 ^ n;
1106       d.Normalize();
1107       return d;
1108     }
1109     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
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       return GetDir();
1116     }
1117   };
1118   //--------------------------------------------------------------------------------
1119   /*!
1120    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1121    * \warning Location of a surface is ignored
1122    */
1123   struct _NodeCoordHelper
1124   {
1125     SMESH_MesherHelper&        _helper;
1126     const TopoDS_Face&         _face;
1127     Handle(Geom_Surface)       _surface;
1128     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1129
1130     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1131       : _helper( helper ), _face( F )
1132     {
1133       if ( is2D )
1134       {
1135         TopLoc_Location loc;
1136         _surface = BRep_Tool::Surface( _face, loc );
1137       }
1138       if ( _surface.IsNull() )
1139         _fun = & _NodeCoordHelper::direct;
1140       else
1141         _fun = & _NodeCoordHelper::byUV;
1142     }
1143     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1144
1145   private:
1146     gp_XYZ direct(const SMDS_MeshNode* n) const
1147     {
1148       return SMESH_TNodeXYZ( n );
1149     }
1150     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1151     {
1152       gp_XY uv = _helper.GetNodeUV( _face, n );
1153       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1154     }
1155   };
1156
1157   //================================================================================
1158   /*!
1159    * \brief Check angle between vectors 
1160    */
1161   //================================================================================
1162
1163   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1164   {
1165     double dot = v1 * v2; // cos * |v1| * |v2|
1166     double l1  = v1.SquareMagnitude();
1167     double l2  = v2.SquareMagnitude();
1168     return (( dot * cos >= 0 ) && 
1169             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1170   }
1171
1172 } // namespace VISCOUS_3D
1173
1174
1175
1176 //================================================================================
1177 // StdMeshers_ViscousLayers hypothesis
1178 //
1179 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1180   :SMESH_Hypothesis(hypId, studyId, gen),
1181    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1182    _method( SURF_OFFSET_SMOOTH )
1183 {
1184   _name = StdMeshers_ViscousLayers::GetHypType();
1185   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1186 } // --------------------------------------------------------------------------------
1187 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1188 {
1189   if ( faceIds != _shapeIds )
1190     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1191   if ( _isToIgnoreShapes != toIgnore )
1192     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1193 } // --------------------------------------------------------------------------------
1194 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1195 {
1196   if ( thickness != _thickness )
1197     _thickness = thickness, NotifySubMeshesHypothesisModification();
1198 } // --------------------------------------------------------------------------------
1199 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1200 {
1201   if ( _nbLayers != nb )
1202     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1203 } // --------------------------------------------------------------------------------
1204 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1205 {
1206   if ( _stretchFactor != factor )
1207     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1210 {
1211   if ( _method != method )
1212     _method = method, NotifySubMeshesHypothesisModification();
1213 } // --------------------------------------------------------------------------------
1214 SMESH_ProxyMesh::Ptr
1215 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1216                                   const TopoDS_Shape& theShape,
1217                                   const bool          toMakeN2NMap) const
1218 {
1219   using namespace VISCOUS_3D;
1220   _ViscousBuilder bulder;
1221   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1222   if ( err && !err->IsOK() )
1223     return SMESH_ProxyMesh::Ptr();
1224
1225   vector<SMESH_ProxyMesh::Ptr> components;
1226   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1227   for ( ; exp.More(); exp.Next() )
1228   {
1229     if ( _MeshOfSolid* pm =
1230          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1231     {
1232       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1233         if ( !bulder.MakeN2NMap( pm ))
1234           return SMESH_ProxyMesh::Ptr();
1235       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1236       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1237
1238       if ( pm->_warning && !pm->_warning->IsOK() )
1239       {
1240         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1241         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1242         if ( !smError || smError->IsOK() )
1243           smError = pm->_warning;
1244       }
1245     }
1246     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1247   }
1248   switch ( components.size() )
1249   {
1250   case 0: break;
1251
1252   case 1: return components[0];
1253
1254   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1255   }
1256   return SMESH_ProxyMesh::Ptr();
1257 } // --------------------------------------------------------------------------------
1258 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1259 {
1260   save << " " << _nbLayers
1261        << " " << _thickness
1262        << " " << _stretchFactor
1263        << " " << _shapeIds.size();
1264   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1265     save << " " << _shapeIds[i];
1266   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1267   save << " " << _method;
1268   return save;
1269 } // --------------------------------------------------------------------------------
1270 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1271 {
1272   int nbFaces, faceID, shapeToTreat, method;
1273   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1274   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1275     _shapeIds.push_back( faceID );
1276   if ( load >> shapeToTreat ) {
1277     _isToIgnoreShapes = !shapeToTreat;
1278     if ( load >> method )
1279       _method = (ExtrusionMethod) method;
1280   }
1281   else {
1282     _isToIgnoreShapes = true; // old behavior
1283   }
1284   return load;
1285 } // --------------------------------------------------------------------------------
1286 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1287                                                    const TopoDS_Shape& theShape)
1288 {
1289   // TODO
1290   return false;
1291 } // --------------------------------------------------------------------------------
1292 SMESH_ComputeErrorPtr
1293 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1294                                           const TopoDS_Shape&                  theShape,
1295                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1296 {
1297   VISCOUS_3D::_ViscousBuilder bulder;
1298   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1299   if ( err && !err->IsOK() )
1300     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1301   else
1302     theStatus = SMESH_Hypothesis::HYP_OK;
1303
1304   return err;
1305 }
1306 // --------------------------------------------------------------------------------
1307 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1308 {
1309   bool isIn =
1310     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1311   return IsToIgnoreShapes() ? !isIn : isIn;
1312 }
1313 // END StdMeshers_ViscousLayers hypothesis
1314 //================================================================================
1315
1316 namespace VISCOUS_3D
1317 {
1318   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1319   {
1320     gp_Vec dir;
1321     double f,l;
1322     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1323     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1324     gp_Pnt p = BRep_Tool::Pnt( fromV );
1325     double distF = p.SquareDistance( c->Value( f ));
1326     double distL = p.SquareDistance( c->Value( l ));
1327     c->D1(( distF < distL ? f : l), p, dir );
1328     if ( distL < distF ) dir.Reverse();
1329     return dir.XYZ();
1330   }
1331   //--------------------------------------------------------------------------------
1332   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1333                      SMESH_MesherHelper& helper)
1334   {
1335     gp_Vec dir;
1336     double f,l; gp_Pnt p;
1337     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1338     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1339     double u = helper.GetNodeU( E, atNode );
1340     c->D1( u, p, dir );
1341     return dir.XYZ();
1342   }
1343   //--------------------------------------------------------------------------------
1344   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1345                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1346                      double* cosin=0);
1347   //--------------------------------------------------------------------------------
1348   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1349                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1350   {
1351     double f,l;
1352     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1353     if ( c.IsNull() )
1354     {
1355       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1356       return getFaceDir( F, v, node, helper, ok );
1357     }
1358     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1359     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1360     gp_Pnt p; gp_Vec du, dv, norm;
1361     surface->D1( uv.X(),uv.Y(), p, du,dv );
1362     norm = du ^ dv;
1363
1364     double u = helper.GetNodeU( fromE, node, 0, &ok );
1365     c->D1( u, p, du );
1366     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1367     if ( o == TopAbs_REVERSED )
1368       du.Reverse();
1369
1370     gp_Vec dir = norm ^ du;
1371
1372     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1373          helper.IsClosedEdge( fromE ))
1374     {
1375       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1376       else                        c->D1( f, p, dv );
1377       if ( o == TopAbs_REVERSED )
1378         dv.Reverse();
1379       gp_Vec dir2 = norm ^ dv;
1380       dir = dir.Normalized() + dir2.Normalized();
1381     }
1382     return dir.XYZ();
1383   }
1384   //--------------------------------------------------------------------------------
1385   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1386                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1387                      bool& ok, double* cosin)
1388   {
1389     TopoDS_Face faceFrw = F;
1390     faceFrw.Orientation( TopAbs_FORWARD );
1391     //double f,l; TopLoc_Location loc;
1392     TopoDS_Edge edges[2]; // sharing a vertex
1393     size_t nbEdges = 0;
1394     {
1395       TopoDS_Vertex VV[2];
1396       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1397       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1398       {
1399         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1400         if ( SMESH_Algo::isDegenerated( e )) continue;
1401         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1402         if ( VV[1].IsSame( fromV )) {
1403           nbEdges += edges[ 0 ].IsNull();
1404           edges[ 0 ] = e;
1405         }
1406         else if ( VV[0].IsSame( fromV )) {
1407           nbEdges += edges[ 1 ].IsNull();
1408           edges[ 1 ] = e;
1409         }
1410       }
1411     }
1412     gp_XYZ dir(0,0,0), edgeDir[2];
1413     if ( nbEdges == 2 )
1414     {
1415       // get dirs of edges going fromV
1416       ok = true;
1417       for ( size_t i = 0; i < nbEdges && ok; ++i )
1418       {
1419         edgeDir[i] = getEdgeDir( edges[i], fromV );
1420         double size2 = edgeDir[i].SquareModulus();
1421         if (( ok = size2 > numeric_limits<double>::min() ))
1422           edgeDir[i] /= sqrt( size2 );
1423       }
1424       if ( !ok ) return dir;
1425
1426       // get angle between the 2 edges
1427       gp_Vec faceNormal;
1428       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1429       if ( Abs( angle ) < 5 * M_PI/180 )
1430       {
1431         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1432       }
1433       else
1434       {
1435         dir = edgeDir[0] + edgeDir[1];
1436         if ( angle < 0 )
1437           dir.Reverse();
1438       }
1439       if ( cosin ) {
1440         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1441         *cosin = Cos( angle );
1442       }
1443     }
1444     else if ( nbEdges == 1 )
1445     {
1446       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1447       if ( cosin ) *cosin = 1.;
1448     }
1449     else
1450     {
1451       ok = false;
1452     }
1453
1454     return dir;
1455   }
1456
1457   //================================================================================
1458   /*!
1459    * \brief Finds concave VERTEXes of a FACE
1460    */
1461   //================================================================================
1462
1463   bool getConcaveVertices( const TopoDS_Face&  F,
1464                            SMESH_MesherHelper& helper,
1465                            set< TGeomID >*     vertices = 0)
1466   {
1467     // check angles at VERTEXes
1468     TError error;
1469     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1470     for ( size_t iW = 0; iW < wires.size(); ++iW )
1471     {
1472       const int nbEdges = wires[iW]->NbEdges();
1473       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1474         continue;
1475       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1476       {
1477         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1478         int iE2 = ( iE1 + 1 ) % nbEdges;
1479         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1480           iE2 = ( iE2 + 1 ) % nbEdges;
1481         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1482         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1483                                         wires[iW]->Edge( iE2 ), F, V );
1484         if ( angle < -5. * M_PI / 180. )
1485         {
1486           if ( !vertices )
1487             return true;
1488           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1489         }
1490       }
1491     }
1492     return vertices ? !vertices->empty() : false;
1493   }
1494
1495   //================================================================================
1496   /*!
1497    * \brief Returns true if a FACE is bound by a concave EDGE
1498    */
1499   //================================================================================
1500
1501   bool isConcave( const TopoDS_Face&  F,
1502                   SMESH_MesherHelper& helper,
1503                   set< TGeomID >*     vertices = 0 )
1504   {
1505     bool isConcv = false;
1506     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1507     //   return true;
1508     gp_Vec2d drv1, drv2;
1509     gp_Pnt2d p;
1510     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1511     for ( ; eExp.More(); eExp.Next() )
1512     {
1513       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1514       if ( SMESH_Algo::isDegenerated( E )) continue;
1515       // check if 2D curve is concave
1516       BRepAdaptor_Curve2d curve( E, F );
1517       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1518       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1519       curve.Intervals( intervals, GeomAbs_C2 );
1520       bool isConvex = true;
1521       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1522       {
1523         double u1 = intervals( i );
1524         double u2 = intervals( i+1 );
1525         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1526         double cross = drv1 ^ drv2;
1527         if ( E.Orientation() == TopAbs_REVERSED )
1528           cross = -cross;
1529         isConvex = ( cross > -1e-9 ); // 0.1 );
1530       }
1531       if ( !isConvex )
1532       {
1533         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1534         isConcv = true;
1535         if ( vertices )
1536           break;
1537         else
1538           return true;
1539       }
1540     }
1541
1542     // check angles at VERTEXes
1543     if ( getConcaveVertices( F, helper, vertices ))
1544       isConcv = true;
1545
1546     return isConcv;
1547   }
1548
1549   //================================================================================
1550   /*!
1551    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1552    *  \param [in] face - the mesh face to treat
1553    *  \param [in] nodeOnEdge - a node on the EDGE
1554    *  \param [out] faceSize - the computed distance
1555    *  \return bool - true if faceSize computed
1556    */
1557   //================================================================================
1558
1559   bool getDistFromEdge( const SMDS_MeshElement* face,
1560                         const SMDS_MeshNode*    nodeOnEdge,
1561                         double &                faceSize )
1562   {
1563     faceSize = Precision::Infinite();
1564     bool done = false;
1565
1566     int nbN  = face->NbCornerNodes();
1567     int iOnE = face->GetNodeIndex( nodeOnEdge );
1568     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1569                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1570     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1571                                       face->GetNode( iNext[1] ) };
1572     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1573     double segLen = -1.;
1574     // look for two neighbor not in-FACE nodes of face
1575     for ( int i = 0; i < 2; ++i )
1576     {
1577       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1578            nNext[i]->GetID() < nodeOnEdge->GetID() )
1579       {
1580         // look for an in-FACE node
1581         for ( int iN = 0; iN < nbN; ++iN )
1582         {
1583           if ( iN == iOnE || iN == iNext[i] )
1584             continue;
1585           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1586           gp_XYZ v = pInFace - segEnd;
1587           if ( segLen < 0 )
1588           {
1589             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1590             segLen = segVec.Modulus();
1591           }
1592           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1593           faceSize = Min( faceSize, distToSeg );
1594           done = true;
1595         }
1596         segLen = -1;
1597       }
1598     }
1599     return done;
1600   }
1601   //================================================================================
1602   /*!
1603    * \brief Return direction of axis or revolution of a surface
1604    */
1605   //================================================================================
1606
1607   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1608                           gp_Dir &                 axis )
1609   {
1610     switch ( surface.GetType() ) {
1611     case GeomAbs_Cone:
1612     {
1613       gp_Cone cone = surface.Cone();
1614       axis = cone.Axis().Direction();
1615       break;
1616     }
1617     case GeomAbs_Sphere:
1618     {
1619       gp_Sphere sphere = surface.Sphere();
1620       axis = sphere.Position().Direction();
1621       break;
1622     }
1623     case GeomAbs_SurfaceOfRevolution:
1624     {
1625       axis = surface.AxeOfRevolution().Direction();
1626       break;
1627     }
1628     //case GeomAbs_SurfaceOfExtrusion:
1629     case GeomAbs_OffsetSurface:
1630     {
1631       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1632       return getRovolutionAxis( base->Surface(), axis );
1633     }
1634     default: return false;
1635     }
1636     return true;
1637   }
1638
1639   //--------------------------------------------------------------------------------
1640   // DEBUG. Dump intermediate node positions into a python script
1641   // HOWTO use: run python commands written in a console to see
1642   //  construction steps of viscous layers
1643 #ifdef __myDEBUG
1644   ofstream* py;
1645   int       theNbPyFunc;
1646   struct PyDump {
1647     PyDump(SMESH_Mesh& m) {
1648       int tag = 3 + m.GetId();
1649       const char* fname = "/tmp/viscous.py";
1650       cout << "execfile('"<<fname<<"')"<<endl;
1651       py = new ofstream(fname);
1652       *py << "import SMESH" << endl
1653           << "from salome.smesh import smeshBuilder" << endl
1654           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1655           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1656           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1657       theNbPyFunc = 0;
1658     }
1659     void Finish() {
1660       if (py) {
1661         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1662           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1663         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1664           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1665       }
1666       delete py; py=0;
1667     }
1668     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1669   };
1670 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1671 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1672 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1673 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1674   void _dumpFunction(const string& fun, int ln)
1675   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1676   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1677   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1678                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1679   void _dumpCmd(const string& txt, int ln)
1680   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1681   void dumpFunctionEnd()
1682   { if (py) *py<< "  return"<< endl; }
1683   void dumpChangeNodes( const SMDS_MeshElement* f )
1684   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1685       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1686       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1687 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1688
1689 #else
1690
1691   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1692 #define dumpFunction(f) f
1693 #define dumpMove(n)
1694 #define dumpMoveComm(n,txt)
1695 #define dumpCmd(txt)
1696 #define dumpFunctionEnd()
1697 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1698 #define debugMsg( txt ) {}
1699
1700 #endif
1701 }
1702
1703 using namespace VISCOUS_3D;
1704
1705 //================================================================================
1706 /*!
1707  * \brief Constructor of _ViscousBuilder
1708  */
1709 //================================================================================
1710
1711 _ViscousBuilder::_ViscousBuilder()
1712 {
1713   _error = SMESH_ComputeError::New(COMPERR_OK);
1714   _tmpFaceID = 0;
1715 }
1716
1717 //================================================================================
1718 /*!
1719  * \brief Stores error description and returns false
1720  */
1721 //================================================================================
1722
1723 bool _ViscousBuilder::error(const string& text, int solidId )
1724 {
1725   const string prefix = string("Viscous layers builder: ");
1726   _error->myName    = COMPERR_ALGO_FAILED;
1727   _error->myComment = prefix + text;
1728   if ( _mesh )
1729   {
1730     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1731     if ( !sm && !_sdVec.empty() )
1732       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1733     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1734     {
1735       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1736       if ( smError && smError->myAlgo )
1737         _error->myAlgo = smError->myAlgo;
1738       smError = _error;
1739       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1740     }
1741     // set KO to all solids
1742     for ( size_t i = 0; i < _sdVec.size(); ++i )
1743     {
1744       if ( _sdVec[i]._index == solidId )
1745         continue;
1746       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1747       if ( !sm->IsEmpty() )
1748         continue;
1749       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1750       if ( !smError || smError->IsOK() )
1751       {
1752         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1753         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1754       }
1755     }
1756   }
1757   makeGroupOfLE(); // debug
1758
1759   return false;
1760 }
1761
1762 //================================================================================
1763 /*!
1764  * \brief At study restoration, restore event listeners used to clear an inferior
1765  *  dim sub-mesh modified by viscous layers
1766  */
1767 //================================================================================
1768
1769 void _ViscousBuilder::RestoreListeners()
1770 {
1771   // TODO
1772 }
1773
1774 //================================================================================
1775 /*!
1776  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1777  */
1778 //================================================================================
1779
1780 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1781 {
1782   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1783   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1784   for ( ; fExp.More(); fExp.Next() )
1785   {
1786     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1787     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1788
1789     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1790       continue;
1791     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1792       continue;
1793
1794     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1795       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1796
1797     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1798     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1799     while( prxIt->more() )
1800     {
1801       const SMDS_MeshElement* fSrc = srcIt->next();
1802       const SMDS_MeshElement* fPrx = prxIt->next();
1803       if ( fSrc->NbNodes() != fPrx->NbNodes())
1804         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1805       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1806         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1807     }
1808   }
1809   pm->_n2nMapComputed = true;
1810   return true;
1811 }
1812
1813 //================================================================================
1814 /*!
1815  * \brief Does its job
1816  */
1817 //================================================================================
1818
1819 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1820                                                const TopoDS_Shape& theShape)
1821 {
1822   // TODO: set priority of solids during Gen::Compute()
1823
1824   _mesh = & theMesh;
1825
1826   // check if proxy mesh already computed
1827   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1828   if ( !exp.More() )
1829     return error("No SOLID's in theShape"), _error;
1830
1831   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1832     return SMESH_ComputeErrorPtr(); // everything already computed
1833
1834   PyDump debugDump( theMesh );
1835
1836   // TODO: ignore already computed SOLIDs 
1837   if ( !findSolidsWithLayers())
1838     return _error;
1839
1840   if ( !findFacesWithLayers() )
1841     return _error;
1842
1843   for ( size_t i = 0; i < _sdVec.size(); ++i )
1844   {
1845     if ( ! makeLayer(_sdVec[i]) )
1846       return _error;
1847
1848     if ( _sdVec[i]._n2eMap.size() == 0 )
1849       continue;
1850     
1851     if ( ! inflate(_sdVec[i]) )
1852       return _error;
1853
1854     if ( ! refine(_sdVec[i]) )
1855       return _error;
1856   }
1857   if ( !shrink() )
1858     return _error;
1859
1860   addBoundaryElements();
1861
1862   makeGroupOfLE(); // debug
1863   debugDump.Finish();
1864
1865   return _error;
1866 }
1867
1868 //================================================================================
1869 /*!
1870  * \brief Check validity of hypotheses
1871  */
1872 //================================================================================
1873
1874 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1875                                                         const TopoDS_Shape& shape )
1876 {
1877   _mesh = & mesh;
1878
1879   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1880     return SMESH_ComputeErrorPtr(); // everything already computed
1881
1882
1883   findSolidsWithLayers();
1884   bool ok = findFacesWithLayers( true );
1885
1886   // remove _MeshOfSolid's of _SolidData's
1887   for ( size_t i = 0; i < _sdVec.size(); ++i )
1888     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1889
1890   if ( !ok )
1891     return _error;
1892
1893   return SMESH_ComputeErrorPtr();
1894 }
1895
1896 //================================================================================
1897 /*!
1898  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1899  */
1900 //================================================================================
1901
1902 bool _ViscousBuilder::findSolidsWithLayers()
1903 {
1904   // get all solids
1905   TopTools_IndexedMapOfShape allSolids;
1906   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1907   _sdVec.reserve( allSolids.Extent());
1908
1909   SMESH_Gen* gen = _mesh->GetGen();
1910   SMESH_HypoFilter filter;
1911   for ( int i = 1; i <= allSolids.Extent(); ++i )
1912   {
1913     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1914     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1915     if ( !algo ) continue;
1916     // TODO: check if algo is hidden
1917     const list <const SMESHDS_Hypothesis *> & allHyps =
1918       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1919     _SolidData* soData = 0;
1920     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1921     const StdMeshers_ViscousLayers* viscHyp = 0;
1922     for ( ; hyp != allHyps.end(); ++hyp )
1923       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1924       {
1925         TopoDS_Shape hypShape;
1926         filter.Init( filter.Is( viscHyp ));
1927         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1928
1929         if ( !soData )
1930         {
1931           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1932                                                                     allSolids(i),
1933                                                                     /*toCreate=*/true);
1934           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1935           soData = & _sdVec.back();
1936           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1937           soData->_helper = new SMESH_MesherHelper( *_mesh );
1938           soData->_helper->SetSubShape( allSolids(i) );
1939         }
1940         soData->_hyps.push_back( viscHyp );
1941         soData->_hypShapes.push_back( hypShape );
1942       }
1943   }
1944   if ( _sdVec.empty() )
1945     return error
1946       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1947
1948   return true;
1949 }
1950
1951 //================================================================================
1952 /*!
1953  * \brief 
1954  */
1955 //================================================================================
1956
1957 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1958 {
1959   SMESH_MesherHelper helper( *_mesh );
1960   TopExp_Explorer exp;
1961   TopTools_IndexedMapOfShape solids;
1962
1963   // collect all faces-to-ignore defined by hyp
1964   for ( size_t i = 0; i < _sdVec.size(); ++i )
1965   {
1966     solids.Add( _sdVec[i]._solid );
1967
1968     // get faces-to-ignore defined by each hyp
1969     typedef const StdMeshers_ViscousLayers* THyp;
1970     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1971     list< TFacesOfHyp > ignoreFacesOfHyps;
1972     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1973     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1974     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1975     {
1976       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1977       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1978     }
1979
1980     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1981     const int nbHyps = _sdVec[i]._hyps.size();
1982     if ( nbHyps > 1 )
1983     {
1984       // check if two hypotheses define different parameters for the same FACE
1985       list< TFacesOfHyp >::iterator igFacesOfHyp;
1986       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1987       {
1988         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1989         THyp hyp = 0;
1990         igFacesOfHyp = ignoreFacesOfHyps.begin();
1991         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1992           if ( ! igFacesOfHyp->first.count( faceID ))
1993           {
1994             if ( hyp )
1995               return error(SMESH_Comment("Several hypotheses define "
1996                                          "Viscous Layers on the face #") << faceID );
1997             hyp = igFacesOfHyp->second;
1998           }
1999         if ( hyp )
2000           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2001         else
2002           _sdVec[i]._ignoreFaceIds.insert( faceID );
2003       }
2004
2005       // check if two hypotheses define different number of viscous layers for
2006       // adjacent faces of a solid
2007       set< int > nbLayersSet;
2008       igFacesOfHyp = ignoreFacesOfHyps.begin();
2009       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2010       {
2011         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2012       }
2013       if ( nbLayersSet.size() > 1 )
2014       {
2015         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2016         {
2017           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2018           THyp hyp1 = 0, hyp2 = 0;
2019           while( const TopoDS_Shape* face = fIt->next() )
2020           {
2021             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2022             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2023             if ( f2h != _sdVec[i]._face2hyp.end() )
2024             {
2025               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2026             }
2027           }
2028           if ( hyp1 && hyp2 &&
2029                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2030           {
2031             return error("Two hypotheses define different number of "
2032                          "viscous layers on adjacent faces");
2033           }
2034         }
2035       }
2036     } // if ( nbHyps > 1 )
2037     else
2038     {
2039       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2040     }
2041   } // loop on _sdVec
2042
2043   if ( onlyWith ) // is called to check hypotheses compatibility only
2044     return true;
2045
2046   // fill _SolidData::_reversedFaceIds
2047   for ( size_t i = 0; i < _sdVec.size(); ++i )
2048   {
2049     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2050     for ( ; exp.More(); exp.Next() )
2051     {
2052       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2053       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2054       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2055           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2056           helper.IsReversedSubMesh( face ))
2057       {
2058         _sdVec[i]._reversedFaceIds.insert( faceID );
2059       }
2060     }
2061   }
2062
2063   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2064   TopTools_IndexedMapOfShape shapes;
2065   for ( size_t i = 0; i < _sdVec.size(); ++i )
2066   {
2067     shapes.Clear();
2068     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2069     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2070     {
2071       const TopoDS_Shape& edge = shapes(iE);
2072       // find 2 faces sharing an edge
2073       TopoDS_Shape FF[2];
2074       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2075       while ( fIt->more())
2076       {
2077         const TopoDS_Shape* f = fIt->next();
2078         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2079           FF[ int( !FF[0].IsNull()) ] = *f;
2080       }
2081       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2082       // check presence of layers on them
2083       int ignore[2];
2084       for ( int j = 0; j < 2; ++j )
2085         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2086       if ( ignore[0] == ignore[1] )
2087         continue; // nothing interesting
2088       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2089       // check presence of layers on fWOL within an adjacent SOLID
2090       bool collision = false;
2091       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2092       while ( const TopoDS_Shape* solid = sIt->next() )
2093         if ( !solid->IsSame( _sdVec[i]._solid ))
2094         {
2095           int iSolid = solids.FindIndex( *solid );
2096           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2097           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2098           {
2099             //_sdVec[i]._noShrinkShapes.insert( iFace );
2100             //fWOL.Nullify();
2101             collision = true;
2102           }
2103         }
2104       // add edge to maps
2105       if ( !fWOL.IsNull())
2106       {
2107         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2108         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2109         if ( collision )
2110         {
2111           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2112           // on the edge but shrink won't be performed
2113           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2114         }
2115       }
2116     }
2117   }
2118   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2119   // the algo of the SOLID sharing the FACE does not support it
2120   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2121   for ( size_t i = 0; i < _sdVec.size(); ++i )
2122   {
2123     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2124     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2125     {
2126       const TopoDS_Shape& fWOL = e2f->second;
2127       const TGeomID     edgeID = e2f->first;
2128       bool notShrinkFace = false;
2129       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2130       while ( soIt->more() )
2131       {
2132         const TopoDS_Shape* solid = soIt->next();
2133         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2134         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2135         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2136         notShrinkFace = true;
2137         size_t iSolid = 0;
2138         for ( ; iSolid < _sdVec.size(); ++iSolid )
2139         {
2140           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2141             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2142               notShrinkFace = false;
2143             break;
2144           }
2145         }
2146         if ( notShrinkFace )
2147         {
2148           _sdVec[i]._noShrinkShapes.insert( edgeID );
2149
2150           // add VERTEXes of the edge in _noShrinkShapes
2151           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2152           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2153             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2154
2155           // check if there is a collision with to-shrink-from EDGEs in iSolid
2156           if ( iSolid == _sdVec.size() )
2157             continue; // no VL in the solid
2158           shapes.Clear();
2159           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2160           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2161           {
2162             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2163             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2164             if ( eID == edgeID ||
2165                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2166                  _sdVec[i]._noShrinkShapes.count( eID ))
2167               continue;
2168             for ( int is1st = 0; is1st < 2; ++is1st )
2169             {
2170               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2171               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2172               {
2173                 // _sdVec[i]._noShrinkShapes.insert( eID );
2174                 // V = helper.IthVertex( !is1st, E );
2175                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2176                 //iE = 0; // re-start the loop on EDGEs of fWOL
2177                 return error("No way to make a conformal mesh with "
2178                              "the given set of faces with layers", _sdVec[i]._index);
2179               }
2180             }
2181           }
2182         }
2183
2184       } // while ( soIt->more() )
2185     } // loop on _sdVec[i]._shrinkShape2Shape
2186   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2187
2188   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2189
2190   for ( size_t i = 0; i < _sdVec.size(); ++i )
2191   {
2192     shapes.Clear();
2193     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2194     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2195     {
2196       const TopoDS_Shape& vertex = shapes(iV);
2197       // find faces WOL sharing the vertex
2198       vector< TopoDS_Shape > facesWOL;
2199       size_t totalNbFaces = 0;
2200       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2201       while ( fIt->more())
2202       {
2203         const TopoDS_Shape* f = fIt->next();
2204         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2205         {
2206           totalNbFaces++;
2207           const int fID = getMeshDS()->ShapeToIndex( *f );
2208           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2209                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2210             facesWOL.push_back( *f );
2211         }
2212       }
2213       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2214         continue; // no layers at this vertex or no WOL
2215       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2216       switch ( facesWOL.size() )
2217       {
2218       case 1:
2219       {
2220         helper.SetSubShape( facesWOL[0] );
2221         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2222         {
2223           TopoDS_Shape seamEdge;
2224           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2225           while ( eIt->more() && seamEdge.IsNull() )
2226           {
2227             const TopoDS_Shape* e = eIt->next();
2228             if ( helper.IsRealSeam( *e ) )
2229               seamEdge = *e;
2230           }
2231           if ( !seamEdge.IsNull() )
2232           {
2233             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2234             break;
2235           }
2236         }
2237         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2238         break;
2239       }
2240       case 2:
2241       {
2242         // find an edge shared by 2 faces
2243         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2244         while ( eIt->more())
2245         {
2246           const TopoDS_Shape* e = eIt->next();
2247           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2248                helper.IsSubShape( *e, facesWOL[1]))
2249           {
2250             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2251           }
2252         }
2253         break;
2254       }
2255       default:
2256         return error("Not yet supported case", _sdVec[i]._index);
2257       }
2258     }
2259   }
2260
2261   // add FACEs of other SOLIDs to _ignoreFaceIds
2262   for ( size_t i = 0; i < _sdVec.size(); ++i )
2263   {
2264     shapes.Clear();
2265     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2266
2267     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2268     {
2269       if ( !shapes.Contains( exp.Current() ))
2270         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2271     }
2272   }
2273
2274   return true;
2275 }
2276
2277 //================================================================================
2278 /*!
2279  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2280  */
2281 //================================================================================
2282
2283 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2284                                      const StdMeshers_ViscousLayers* hyp,
2285                                      const TopoDS_Shape&             hypShape,
2286                                      set<TGeomID>&                   ignoreFaceIds)
2287 {
2288   TopExp_Explorer exp;
2289
2290   vector<TGeomID> ids = hyp->GetBndShapes();
2291   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2292   {
2293     for ( size_t ii = 0; ii < ids.size(); ++ii )
2294     {
2295       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2296       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2297         ignoreFaceIds.insert( ids[ii] );
2298     }
2299   }
2300   else // FACEs with layers are given
2301   {
2302     exp.Init( solid, TopAbs_FACE );
2303     for ( ; exp.More(); exp.Next() )
2304     {
2305       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2306       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2307         ignoreFaceIds.insert( faceInd );
2308     }
2309   }
2310
2311   // ignore internal FACEs if inlets and outlets are specified
2312   if ( hyp->IsToIgnoreShapes() )
2313   {
2314     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2315     TopExp::MapShapesAndAncestors( hypShape,
2316                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2317
2318     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2319     {
2320       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2321       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2322         continue;
2323
2324       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2325       if ( nbSolids > 1 )
2326         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2327     }
2328   }
2329 }
2330
2331 //================================================================================
2332 /*!
2333  * \brief Create the inner surface of the viscous layer and prepare data for infation
2334  */
2335 //================================================================================
2336
2337 bool _ViscousBuilder::makeLayer(_SolidData& data)
2338 {
2339   // get all sub-shapes to make layers on
2340   set<TGeomID> subIds, faceIds;
2341   subIds = data._noShrinkShapes;
2342   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2343   for ( ; exp.More(); exp.Next() )
2344   {
2345     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2346     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2347       faceIds.insert( fSubM->GetId() );
2348   }
2349
2350   // make a map to find new nodes on sub-shapes shared with other SOLID
2351   map< TGeomID, TNode2Edge* >::iterator s2ne;
2352   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2353   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2354   {
2355     TGeomID shapeInd = s2s->first;
2356     for ( size_t i = 0; i < _sdVec.size(); ++i )
2357     {
2358       if ( _sdVec[i]._index == data._index ) continue;
2359       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2360       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2361            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2362       {
2363         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2364         break;
2365       }
2366     }
2367   }
2368
2369   // Create temporary faces and _LayerEdge's
2370
2371   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2372
2373   data._stepSize = Precision::Infinite();
2374   data._stepSizeNodes[0] = 0;
2375
2376   SMESH_MesherHelper helper( *_mesh );
2377   helper.SetSubShape( data._solid );
2378   helper.SetElementsOnShape( true );
2379
2380   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2381   TNode2Edge::iterator n2e2;
2382
2383   // collect _LayerEdge's of shapes they are based on
2384   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2385   const int nbShapes = getMeshDS()->MaxShapeIndex();
2386   edgesByGeom.resize( nbShapes+1 );
2387
2388   // set data of _EdgesOnShape's
2389   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2390   {
2391     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2392     while ( smIt->more() )
2393     {
2394       sm = smIt->next();
2395       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2396            !faceIds.count( sm->GetId() ))
2397         continue;
2398       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2399     }
2400   }
2401   // make _LayerEdge's
2402   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2403   {
2404     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2405     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2406     SMESH_ProxyMesh::SubMesh* proxySub =
2407       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2408
2409     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2410     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2411
2412     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2413     while ( eIt->more() )
2414     {
2415       const SMDS_MeshElement* face = eIt->next();
2416       double          faceMaxCosin = -1;
2417       _LayerEdge*     maxCosinEdge = 0;
2418       int             nbDegenNodes = 0;
2419
2420       newNodes.resize( face->NbCornerNodes() );
2421       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2422       {
2423         const SMDS_MeshNode* n = face->GetNode( i );
2424         const int      shapeID = n->getshapeId();
2425         const bool onDegenShap = helper.IsDegenShape( shapeID );
2426         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2427         if ( onDegenShap )
2428         {
2429           if ( onDegenEdge )
2430           {
2431             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2432             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2433             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2434             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2435               n = vN;
2436               nbDegenNodes++;
2437             }
2438           }
2439           else
2440           {
2441             nbDegenNodes++;
2442           }
2443         }
2444         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2445         if ( !(*n2e).second )
2446         {
2447           // add a _LayerEdge
2448           _LayerEdge* edge = new _LayerEdge();
2449           edge->_nodes.push_back( n );
2450           n2e->second = edge;
2451           edgesByGeom[ shapeID ]._edges.push_back( edge );
2452           const bool noShrink = data._noShrinkShapes.count( shapeID );
2453
2454           SMESH_TNodeXYZ xyz( n );
2455
2456           // set edge data or find already refined _LayerEdge and get data from it
2457           if (( !noShrink                                                     ) &&
2458               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2459               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2460               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2461           {
2462             _LayerEdge* foundEdge = (*n2e2).second;
2463             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2464             foundEdge->_pos.push_back( lastPos );
2465             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2466             const_cast< SMDS_MeshNode* >
2467               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2468           }
2469           else
2470           {
2471             if ( !noShrink )
2472             {
2473               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2474             }
2475             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2476               return false;
2477
2478             if ( edge->_nodes.size() < 2 )
2479               edge->Block( data );
2480               //data._noShrinkShapes.insert( shapeID );
2481           }
2482           dumpMove(edge->_nodes.back());
2483
2484           if ( edge->_cosin > faceMaxCosin )
2485           {
2486             faceMaxCosin = edge->_cosin;
2487             maxCosinEdge = edge;
2488           }
2489         }
2490         newNodes[ i ] = n2e->second->_nodes.back();
2491
2492         if ( onDegenEdge )
2493           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2494       }
2495       if ( newNodes.size() - nbDegenNodes < 2 )
2496         continue;
2497
2498       // create a temporary face
2499       const SMDS_MeshElement* newFace =
2500         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2501       proxySub->AddElement( newFace );
2502
2503       // compute inflation step size by min size of element on a convex surface
2504       if ( faceMaxCosin > theMinSmoothCosin )
2505         limitStepSize( data, face, maxCosinEdge );
2506
2507     } // loop on 2D elements on a FACE
2508   } // loop on FACEs of a SOLID to create _LayerEdge's
2509
2510
2511   // Set _LayerEdge::_neibors
2512   TNode2Edge::iterator n2e;
2513   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2514   {
2515     _EdgesOnShape& eos = data._edgesOnShape[iS];
2516     for ( size_t i = 0; i < eos._edges.size(); ++i )
2517     {
2518       _LayerEdge* edge = eos._edges[i];
2519       TIDSortedNodeSet nearNodes;
2520       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2521       while ( fIt->more() )
2522       {
2523         const SMDS_MeshElement* f = fIt->next();
2524         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2525           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2526       }
2527       nearNodes.erase( edge->_nodes[0] );
2528       edge->_neibors.reserve( nearNodes.size() );
2529       TIDSortedNodeSet::iterator node = nearNodes.begin();
2530       for ( ; node != nearNodes.end(); ++node )
2531         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2532           edge->_neibors.push_back( n2e->second );
2533     }
2534   }
2535
2536   data._epsilon = 1e-7;
2537   if ( data._stepSize < 1. )
2538     data._epsilon *= data._stepSize;
2539
2540   if ( !findShapesToSmooth( data ))
2541     return false;
2542
2543   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2544   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2545
2546   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2547   const SMDS_MeshNode* nn[2];
2548   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2549   {
2550     _EdgesOnShape& eos = data._edgesOnShape[iS];
2551     for ( size_t i = 0; i < eos._edges.size(); ++i )
2552     {
2553       _LayerEdge* edge = eos._edges[i];
2554       if ( edge->IsOnEdge() )
2555       {
2556         // get neighbor nodes
2557         bool hasData = ( edge->_2neibors->_edges[0] );
2558         if ( hasData ) // _LayerEdge is a copy of another one
2559         {
2560           nn[0] = edge->_2neibors->srcNode(0);
2561           nn[1] = edge->_2neibors->srcNode(1);
2562         }
2563         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2564         {
2565           return false;
2566         }
2567         // set neighbor _LayerEdge's
2568         for ( int j = 0; j < 2; ++j )
2569         {
2570           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2571             return error("_LayerEdge not found by src node", data._index);
2572           edge->_2neibors->_edges[j] = n2e->second;
2573         }
2574         if ( !hasData )
2575           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2576       }
2577
2578       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2579       {
2580         _Simplex& s = edge->_simplices[j];
2581         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2582         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2583       }
2584
2585       // For an _LayerEdge on a degenerated EDGE, copy some data from
2586       // a corresponding _LayerEdge on a VERTEX
2587       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2588       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2589       {
2590         // Generally we should not get here
2591         if ( eos.ShapeType() != TopAbs_EDGE )
2592           continue;
2593         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2594         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2595         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2596           continue;
2597         const _LayerEdge* vEdge = n2e->second;
2598         edge->_normal    = vEdge->_normal;
2599         edge->_lenFactor = vEdge->_lenFactor;
2600         edge->_cosin     = vEdge->_cosin;
2601       }
2602
2603     } // loop on data._edgesOnShape._edges
2604   } // loop on data._edgesOnShape
2605
2606   // fix _LayerEdge::_2neibors on EDGEs to smooth
2607   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2608   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2609   //   if ( !e2c->second.IsNull() )
2610   //   {
2611   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2612   //       data.Sort2NeiborsOnEdge( eos->_edges );
2613   //   }
2614
2615   dumpFunctionEnd();
2616   return true;
2617 }
2618
2619 //================================================================================
2620 /*!
2621  * \brief Compute inflation step size by min size of element on a convex surface
2622  */
2623 //================================================================================
2624
2625 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2626                                      const SMDS_MeshElement* face,
2627                                      const _LayerEdge*       maxCosinEdge )
2628 {
2629   int iN = 0;
2630   double minSize = 10 * data._stepSize;
2631   const int nbNodes = face->NbCornerNodes();
2632   for ( int i = 0; i < nbNodes; ++i )
2633   {
2634     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2635     const SMDS_MeshNode*  curN = face->GetNode( i );
2636     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2637          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2638     {
2639       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2640       if ( dist < minSize )
2641         minSize = dist, iN = i;
2642     }
2643   }
2644   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2645   if ( newStep < data._stepSize )
2646   {
2647     data._stepSize = newStep;
2648     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2649     data._stepSizeNodes[0] = face->GetNode( iN );
2650     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2651   }
2652 }
2653
2654 //================================================================================
2655 /*!
2656  * \brief Compute inflation step size by min size of element on a convex surface
2657  */
2658 //================================================================================
2659
2660 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2661 {
2662   if ( minSize < data._stepSize )
2663   {
2664     data._stepSize = minSize;
2665     if ( data._stepSizeNodes[0] )
2666     {
2667       double dist =
2668         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2669       data._stepSizeCoeff = data._stepSize / dist;
2670     }
2671   }
2672 }
2673
2674 //================================================================================
2675 /*!
2676  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2677  */
2678 //================================================================================
2679
2680 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2681 {
2682   const int nbTestPnt = 5; // on a FACE sub-shape
2683
2684   BRepLProp_SLProps surfProp( 2, 1e-6 );
2685   SMESH_MesherHelper helper( *_mesh );
2686
2687   data._convexFaces.clear();
2688
2689   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2690   {
2691     _EdgesOnShape& eof = data._edgesOnShape[iS];
2692     if ( eof.ShapeType() != TopAbs_FACE ||
2693          data._ignoreFaceIds.count( eof._shapeID ))
2694       continue;
2695
2696     TopoDS_Face        F = TopoDS::Face( eof._shape );
2697     SMESH_subMesh *   sm = eof._subMesh;
2698     const TGeomID faceID = eof._shapeID;
2699
2700     BRepAdaptor_Surface surface( F, false );
2701     surfProp.SetSurface( surface );
2702
2703     bool isTooCurved = false;
2704
2705     _ConvexFace cnvFace;
2706     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2707     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2708     while ( smIt->more() )
2709     {
2710       sm = smIt->next();
2711       const TGeomID subID = sm->GetId();
2712       // find _LayerEdge's of a sub-shape
2713       _EdgesOnShape* eos;
2714       if (( eos = data.GetShapeEdges( subID )))
2715         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2716       else
2717         continue;
2718       // check concavity and curvature and limit data._stepSize
2719       const double minCurvature =
2720         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2721       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2722       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2723       {
2724         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2725         surfProp.SetParameters( uv.X(), uv.Y() );
2726         if ( !surfProp.IsCurvatureDefined() )
2727           continue;
2728         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2729         {
2730           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2731           isTooCurved = true;
2732         }
2733         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2734         {
2735           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2736           isTooCurved = true;
2737         }
2738       }
2739     } // loop on sub-shapes of the FACE
2740
2741     if ( !isTooCurved ) continue;
2742
2743     _ConvexFace & convFace =
2744       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2745
2746     convFace._face = F;
2747     convFace._normalsFixed = false;
2748
2749     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2750     // prism distortion.
2751     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2752     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2753     {
2754       // there are _LayerEdge's on the FACE it-self;
2755       // select _LayerEdge's near EDGEs
2756       _EdgesOnShape& eos = * id2eos->second;
2757       for ( size_t i = 0; i < eos._edges.size(); ++i )
2758       {
2759         _LayerEdge* ledge = eos._edges[ i ];
2760         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2761           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2762           {
2763             convFace._simplexTestEdges.push_back( ledge );
2764             break;
2765           }
2766       }
2767     }
2768     else
2769     {
2770       // where there are no _LayerEdge's on a _ConvexFace,
2771       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2772       // so that collision of viscous internal faces is not detected by check of
2773       // intersection of _LayerEdge's with the viscous internal faces.
2774
2775       set< const SMDS_MeshNode* > usedNodes;
2776
2777       // look for _LayerEdge's with null _sWOL
2778       id2eos = convFace._subIdToEOS.begin();
2779       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2780       {
2781         _EdgesOnShape& eos = * id2eos->second;
2782         if ( !eos._sWOL.IsNull() )
2783           continue;
2784         for ( size_t i = 0; i < eos._edges.size(); ++i )
2785         {
2786           _LayerEdge* ledge = eos._edges[ i ];
2787           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2788           if ( !usedNodes.insert( srcNode ).second ) continue;
2789
2790           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2791           {
2792             usedNodes.insert( ledge->_simplices[i]._nPrev );
2793             usedNodes.insert( ledge->_simplices[i]._nNext );
2794           }
2795           convFace._simplexTestEdges.push_back( ledge );
2796         }
2797       }
2798     }
2799   } // loop on FACEs of data._solid
2800 }
2801
2802 //================================================================================
2803 /*!
2804  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2805  */
2806 //================================================================================
2807
2808 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2809 {
2810   // define allowed thickness
2811   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2812
2813   data._maxThickness = 0;
2814   data._minThickness = 1e100;
2815   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2816   for ( ; hyp != data._hyps.end(); ++hyp )
2817   {
2818     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2819     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2820   }
2821   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2822
2823   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2824   // boundry inclined to the shape at a sharp angle
2825
2826   //list< TGeomID > shapesToSmooth;
2827   TopTools_MapOfShape edgesOfSmooFaces;
2828
2829   SMESH_MesherHelper helper( *_mesh );
2830   bool ok = true;
2831
2832   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2833   data._nbShapesToSmooth = 0;
2834
2835   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2836   {
2837     _EdgesOnShape& eos = edgesByGeom[iS];
2838     eos._toSmooth = false;
2839     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2840       continue;
2841
2842     double tgtThick = eos._hyp.GetTotalThickness();
2843     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2844     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2845     {
2846       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2847       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2848       if ( eE.empty() ) continue;
2849
2850       double faceSize;
2851       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2852         if ( eE[i]->_cosin > theMinSmoothCosin )
2853         {
2854           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2855           while ( fIt->more() && !eos._toSmooth )
2856           {
2857             const SMDS_MeshElement* face = fIt->next();
2858             if ( face->getshapeId() == eos._shapeID &&
2859                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2860             {
2861               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2862             }
2863           }
2864         }
2865     }
2866     if ( eos._toSmooth )
2867     {
2868       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2869         edgesOfSmooFaces.Add( eExp.Current() );
2870
2871       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2872     }
2873     data._nbShapesToSmooth += eos._toSmooth;
2874
2875   }  // check FACEs
2876
2877   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2878   {
2879     _EdgesOnShape& eos = edgesByGeom[iS];
2880     eos._edgeSmoother = NULL;
2881     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2882     if ( !eos._hyp.ToSmooth() ) continue;
2883
2884     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2885     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2886       continue;
2887
2888     double tgtThick = eos._hyp.GetTotalThickness();
2889     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2890     {
2891       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2892       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2893       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2894       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2895       double angle    = eDir.Angle( eV[0]->_normal );
2896       double cosin    = Cos( angle );
2897       double cosinAbs = Abs( cosin );
2898       if ( cosinAbs > theMinSmoothCosin )
2899       {
2900         // always smooth analytic EDGEs
2901         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2902         eos._toSmooth = ! curve.IsNull();
2903
2904         // compare tgtThick with the length of an end segment
2905         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2906         while ( eIt->more() && !eos._toSmooth )
2907         {
2908           const SMDS_MeshElement* endSeg = eIt->next();
2909           if ( endSeg->getshapeId() == (int) iS )
2910           {
2911             double segLen =
2912               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2913             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2914           }
2915         }
2916         if ( eos._toSmooth )
2917         {
2918           eos._edgeSmoother = new _Smoother1D( curve, eos );
2919
2920           for ( size_t i = 0; i < eos._edges.size(); ++i )
2921             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2922         }
2923       }
2924     }
2925     data._nbShapesToSmooth += eos._toSmooth;
2926
2927   } // check EDGEs
2928
2929   // Reset _cosin if no smooth is allowed by the user
2930   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2931   {
2932     _EdgesOnShape& eos = edgesByGeom[iS];
2933     if ( eos._edges.empty() ) continue;
2934
2935     if ( !eos._hyp.ToSmooth() )
2936       for ( size_t i = 0; i < eos._edges.size(); ++i )
2937         eos._edges[i]->SetCosin( 0 );
2938   }
2939
2940
2941   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2942
2943   TopTools_MapOfShape c1VV;
2944
2945   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2946   {
2947     _EdgesOnShape& eos = edgesByGeom[iS];
2948     if ( eos._edges.empty() ||
2949          eos.ShapeType() != TopAbs_FACE ||
2950          !eos._toSmooth )
2951       continue;
2952
2953     // check EDGEs of a FACE
2954     TopTools_MapOfShape checkedEE, allVV;
2955     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
2956     while ( !smQueue.empty() )
2957     {
2958       SMESH_subMesh* sm = smQueue.front();
2959       smQueue.pop_front();
2960       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2961       while ( smIt->more() )
2962       {
2963         sm = smIt->next();
2964         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
2965           allVV.Add( sm->GetSubShape() );
2966         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
2967              !checkedEE.Add( sm->GetSubShape() ))
2968           continue;
2969
2970         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
2971         vector<_LayerEdge*>& eE = eoe->_edges;
2972         if ( eE.empty() || !eoe->_sWOL.IsNull() )
2973           continue;
2974
2975         bool isC1 = true; // check continuity along an EDGE
2976         for ( size_t i = 0; i < eE.size() && isC1; ++i )
2977           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
2978         if ( !isC1 )
2979           continue;
2980
2981         // check that mesh faces are C1 as well
2982         {
2983           gp_XYZ norm1, norm2;
2984           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
2985           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
2986           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
2987             continue;
2988           while ( fIt->more() && isC1 )
2989             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
2990                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
2991           if ( !isC1 )
2992             continue;
2993         }
2994
2995         // add the EDGE and an adjacent FACE to _eosC1
2996         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
2997         while ( const TopoDS_Shape* face = fIt->next() )
2998         {
2999           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3000           if ( !eof ) continue; // other solid
3001           if ( !eos.HasC1( eoe ))
3002           {
3003             eos._eosC1.push_back( eoe );
3004             eoe->_toSmooth = false;
3005             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3006           }
3007           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3008           {
3009             eos._eosC1.push_back( eof );
3010             eof->_toSmooth = false;
3011             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3012             smQueue.push_back( eof->_subMesh );
3013           }
3014         }
3015       }
3016     }
3017     if ( eos._eosC1.empty() )
3018       continue;
3019
3020     // check VERTEXes of C1 FACEs
3021     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3022     for ( ; vIt.More(); vIt.Next() )
3023     {
3024       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3025       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3026         continue;
3027
3028       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3029       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3030       while ( const TopoDS_Shape* face = fIt->next() )
3031       {
3032         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3033         if ( !eof ) continue; // other solid
3034         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3035         if ( !isC1 )
3036           break;
3037       }
3038       if ( isC1 )
3039       {
3040         eos._eosC1.push_back( eov );
3041         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3042         c1VV.Add( eov->_shape );
3043       }
3044     }
3045
3046   } // fill _eosC1 of FACEs
3047
3048
3049   // Find C1 EDGEs
3050
3051   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3052
3053   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3054   {
3055     _EdgesOnShape& eov = edgesByGeom[iS];
3056     if ( eov._edges.empty() ||
3057          eov.ShapeType() != TopAbs_VERTEX ||
3058          c1VV.Contains( eov._shape ))
3059       continue;
3060     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3061
3062     // get directions of surrounding EDGEs
3063     dirOfEdges.clear();
3064     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3065     while ( const TopoDS_Shape* e = fIt->next() )
3066     {
3067       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3068       if ( !eoe ) continue; // other solid
3069       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3070       if ( !Precision::IsInfinite( eDir.X() ))
3071         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3072     }
3073
3074     // find EDGEs with C1 directions
3075     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3076       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3077         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3078         {
3079           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3080           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3081           if ( isC1 )
3082           {
3083             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3084             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3085             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3086             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3087             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3088             dirOfEdges[i].first = 0;
3089             dirOfEdges[j].first = 0;
3090           }
3091         }
3092   } // fill _eosC1 of VERTEXes
3093
3094
3095
3096   return ok;
3097 }
3098
3099 //================================================================================
3100 /*!
3101  * \brief initialize data of _EdgesOnShape
3102  */
3103 //================================================================================
3104
3105 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3106                                     SMESH_subMesh* sm,
3107                                     _SolidData&    data )
3108 {
3109   if ( !eos._shape.IsNull() ||
3110        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3111     return;
3112
3113   SMESH_MesherHelper helper( *_mesh );
3114
3115   eos._subMesh = sm;
3116   eos._shapeID = sm->GetId();
3117   eos._shape   = sm->GetSubShape();
3118   if ( eos.ShapeType() == TopAbs_FACE )
3119     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3120   eos._toSmooth = false;
3121   eos._data = &data;
3122
3123   // set _SWOL
3124   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3125     data._shrinkShape2Shape.find( eos._shapeID );
3126   if ( s2s != data._shrinkShape2Shape.end() )
3127     eos._sWOL = s2s->second;
3128
3129   eos._isRegularSWOL = true;
3130   if ( eos.SWOLType() == TopAbs_FACE )
3131   {
3132     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3133     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3134     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3135   }
3136
3137   // set _hyp
3138   if ( data._hyps.size() == 1 )
3139   {
3140     eos._hyp = data._hyps.back();
3141   }
3142   else
3143   {
3144     // compute average StdMeshers_ViscousLayers parameters
3145     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3146     if ( eos.ShapeType() == TopAbs_FACE )
3147     {
3148       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3149         eos._hyp = f2hyp->second;
3150     }
3151     else
3152     {
3153       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3154       while ( const TopoDS_Shape* face = fIt->next() )
3155       {
3156         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3157         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3158           eos._hyp.Add( f2hyp->second );
3159       }
3160     }
3161   }
3162
3163   // set _faceNormals
3164   if ( ! eos._hyp.UseSurfaceNormal() )
3165   {
3166     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3167     {
3168       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3169       eos._faceNormals.resize( smDS->NbElements() );
3170
3171       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3172       for ( int iF = 0; eIt->more(); ++iF )
3173       {
3174         const SMDS_MeshElement* face = eIt->next();
3175         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3176           eos._faceNormals[iF].SetCoord( 0,0,0 );
3177       }
3178
3179       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3180         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3181           eos._faceNormals[iF].Reverse();
3182     }
3183     else // find EOS of adjacent FACEs
3184     {
3185       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3186       while ( const TopoDS_Shape* face = fIt->next() )
3187       {
3188         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3189         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3190         if ( eos._faceEOS.back()->_shape.IsNull() )
3191           // avoid using uninitialised _shapeID in GetNormal()
3192           eos._faceEOS.back()->_shapeID = faceID;
3193       }
3194     }
3195   }
3196 }
3197
3198 //================================================================================
3199 /*!
3200  * \brief Returns normal of a face
3201  */
3202 //================================================================================
3203
3204 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3205 {
3206   bool ok = false;
3207   const _EdgesOnShape* eos = 0;
3208
3209   if ( face->getshapeId() == _shapeID )
3210   {
3211     eos = this;
3212   }
3213   else
3214   {
3215     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3216       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3217         eos = _faceEOS[ iF ];
3218   }
3219
3220   if (( eos ) &&
3221       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3222   {
3223     norm = eos->_faceNormals[ face->getIdInShape() ];
3224   }
3225   else if ( !eos )
3226   {
3227     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3228               << " on _shape #" << _shapeID );
3229   }
3230   return ok;
3231 }
3232
3233
3234 //================================================================================
3235 /*!
3236  * \brief Set data of _LayerEdge needed for smoothing
3237  */
3238 //================================================================================
3239
3240 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3241                                   _EdgesOnShape&      eos,
3242                                   SMESH_MesherHelper& helper,
3243                                   _SolidData&         data)
3244 {
3245   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3246
3247   edge._len       = 0;
3248   edge._maxLen    = Precision::Infinite();
3249   edge._minAngle  = 0;
3250   edge._2neibors  = 0;
3251   edge._curvature = 0;
3252   edge._flags     = 0;
3253
3254   // --------------------------
3255   // Compute _normal and _cosin
3256   // --------------------------
3257
3258   edge._cosin     = 0;
3259   edge._lenFactor = 1.;
3260   edge._normal.SetCoord(0,0,0);
3261   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3262
3263   int totalNbFaces = 0;
3264   TopoDS_Face F;
3265   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3266   gp_Vec geomNorm;
3267   bool normOK = true;
3268
3269   const bool onShrinkShape = !eos._sWOL.IsNull();
3270   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3271                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3272
3273   // get geom FACEs the node lies on
3274   //if ( useGeometry )
3275   {
3276     set<TGeomID> faceIds;
3277     if  ( eos.ShapeType() == TopAbs_FACE )
3278     {
3279       faceIds.insert( eos._shapeID );
3280     }
3281     else
3282     {
3283       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3284       while ( fIt->more() )
3285         faceIds.insert( fIt->next()->getshapeId() );
3286     }
3287     set<TGeomID>::iterator id = faceIds.begin();
3288     for ( ; id != faceIds.end(); ++id )
3289     {
3290       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3291       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3292         continue;
3293       F = TopoDS::Face( s );
3294       face2Norm[ totalNbFaces ].first = F;
3295       totalNbFaces++;
3296     }
3297   }
3298
3299   // find _normal
3300   if ( useGeometry )
3301   {
3302     if ( onShrinkShape ) // one of faces the node is on has no layers
3303     {
3304       if ( eos.SWOLType() == TopAbs_EDGE )
3305       {
3306         // inflate from VERTEX along EDGE
3307         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3308       }
3309       else if ( eos.ShapeType() == TopAbs_VERTEX )
3310       {
3311         // inflate from VERTEX along FACE
3312         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3313                                    node, helper, normOK, &edge._cosin);
3314       }
3315       else
3316       {
3317         // inflate from EDGE along FACE
3318         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3319                                    node, helper, normOK);
3320       }
3321     }
3322     else // layers are on all FACEs of SOLID the node is on
3323     {
3324       int nbOkNorms = 0;
3325       for ( int iF = 0; iF < totalNbFaces; ++iF )
3326       {
3327         F = TopoDS::Face( face2Norm[ iF ].first );
3328         geomNorm = getFaceNormal( node, F, helper, normOK );
3329         if ( !normOK ) continue;
3330         nbOkNorms++;
3331
3332         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3333           geomNorm.Reverse();
3334         face2Norm[ iF ].second = geomNorm.XYZ();
3335         edge._normal += geomNorm.XYZ();
3336       }
3337       if ( nbOkNorms == 0 )
3338         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3339
3340       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3341       {
3342         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3343         edge._normal.SetCoord( 0,0,0 );
3344         for ( int iF = 0; iF < totalNbFaces; ++iF )
3345         {
3346           const TopoDS_Face& F = face2Norm[iF].first;
3347           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3348           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3349             geomNorm.Reverse();
3350           if ( normOK )
3351             face2Norm[ iF ].second = geomNorm.XYZ();
3352           edge._normal += face2Norm[ iF ].second;
3353         }
3354       }
3355
3356       if ( totalNbFaces >= 3 )
3357       {
3358         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces );
3359       }
3360     }
3361   }
3362   else // !useGeometry - get _normal using surrounding mesh faces
3363   {
3364     edge._normal = getWeigthedNormal( &edge );
3365
3366     // set<TGeomID> faceIds;
3367     //
3368     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3369     // while ( fIt->more() )
3370     // {
3371     //   const SMDS_MeshElement* face = fIt->next();
3372     //   if ( eos.GetNormal( face, geomNorm ))
3373     //   {
3374     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3375     //       continue; // use only one mesh face on FACE
3376     //     edge._normal += geomNorm.XYZ();
3377     //     totalNbFaces++;
3378     //   }
3379     // }
3380   }
3381
3382   // compute _cosin
3383   //if ( eos._hyp.UseSurfaceNormal() )
3384   {
3385     switch ( eos.ShapeType() )
3386     {
3387     case TopAbs_FACE: {
3388       edge._cosin = 0;
3389       break;
3390     }
3391     case TopAbs_EDGE: {
3392       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3393       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3394       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3395       edge._cosin      = Cos( angle );
3396       break;
3397     }
3398     case TopAbs_VERTEX: {
3399       if ( eos.SWOLType() != TopAbs_FACE ) { // else _cosin is set by getFaceDir()
3400         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3401         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3402         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3403         edge._cosin      = Cos( angle );
3404         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3405           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3406           {
3407             F = face2Norm[ iF ].first;
3408             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3409             if ( normOK ) {
3410               double angle = inFaceDir.Angle( edge._normal );
3411               double cosin = Cos( angle );
3412               if ( Abs( cosin ) > edge._cosin )
3413                 edge._cosin = cosin;
3414             }
3415           }
3416       }
3417       break;
3418     }
3419     default:
3420       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3421     }
3422   }
3423
3424   double normSize = edge._normal.SquareModulus();
3425   if ( normSize < numeric_limits<double>::min() )
3426     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3427
3428   edge._normal /= sqrt( normSize );
3429
3430   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3431   {
3432     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3433     edge._nodes.resize( 1 );
3434     edge._normal.SetCoord( 0,0,0 );
3435     edge._maxLen = 0;
3436   }
3437
3438   // Set the rest data
3439   // --------------------
3440
3441   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3442
3443   if ( onShrinkShape )
3444   {
3445     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3446     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3447       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3448
3449     // set initial position which is parameters on _sWOL in this case
3450     if ( eos.SWOLType() == TopAbs_EDGE )
3451     {
3452       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3453       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3454       if ( edge._nodes.size() > 1 )
3455         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3456     }
3457     else // eos.SWOLType() == TopAbs_FACE
3458     {
3459       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3460       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3461       if ( edge._nodes.size() > 1 )
3462         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3463     }
3464
3465     if ( edge._nodes.size() > 1 )
3466     {
3467       // check if an angle between a FACE with layers and SWOL is sharp,
3468       // else the edge should not inflate
3469       F.Nullify();
3470       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3471         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3472           F = face2Norm[iF].first;
3473       if ( !F.IsNull())
3474       {
3475         geomNorm = getFaceNormal( node, F, helper, normOK );
3476         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3477           geomNorm.Reverse(); // inside the SOLID
3478         if ( geomNorm * edge._normal < -0.001 )
3479         {
3480           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3481           edge._nodes.resize( 1 );
3482         }
3483         else if ( edge._lenFactor > 3 )
3484         {
3485           edge._lenFactor = 2;
3486           edge.Set( _LayerEdge::RISKY_SWOL );
3487         }
3488       }
3489     }
3490   }
3491   else
3492   {
3493     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3494
3495     if ( eos.ShapeType() == TopAbs_FACE )
3496     {
3497       double angle;
3498       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3499       {
3500         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3501         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3502       }
3503     }
3504   }
3505
3506   // Set neighbor nodes for a _LayerEdge based on EDGE
3507
3508   if ( eos.ShapeType() == TopAbs_EDGE /*||
3509        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3510   {
3511     edge._2neibors = new _2NearEdges;
3512     // target nodes instead of source ones will be set later
3513   }
3514
3515   return true;
3516 }
3517
3518 //================================================================================
3519 /*!
3520  * \brief Return normal to a FACE at a node
3521  *  \param [in] n - node
3522  *  \param [in] face - FACE
3523  *  \param [in] helper - helper
3524  *  \param [out] isOK - true or false
3525  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3526  *  \return gp_XYZ - normal
3527  */
3528 //================================================================================
3529
3530 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3531                                       const TopoDS_Face&   face,
3532                                       SMESH_MesherHelper&  helper,
3533                                       bool&                isOK,
3534                                       bool                 shiftInside)
3535 {
3536   gp_XY uv;
3537   if ( shiftInside )
3538   {
3539     // get a shifted position
3540     gp_Pnt p = SMESH_TNodeXYZ( node );
3541     gp_XYZ shift( 0,0,0 );
3542     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3543     switch ( S.ShapeType() ) {
3544     case TopAbs_VERTEX:
3545     {
3546       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3547       break;
3548     }
3549     case TopAbs_EDGE:
3550     {
3551       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3552       break;
3553     }
3554     default:
3555       isOK = false;
3556     }
3557     if ( isOK )
3558       shift.Normalize();
3559     p.Translate( shift * 1e-5 );
3560
3561     TopLoc_Location loc;
3562     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3563
3564     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3565     
3566     projector.Perform( p );
3567     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3568     {
3569       isOK = false;
3570       return p.XYZ();
3571     }
3572     Quantity_Parameter U,V;
3573     projector.LowerDistanceParameters(U,V);
3574     uv.SetCoord( U,V );
3575   }
3576   else
3577   {
3578     uv = helper.GetNodeUV( face, node, 0, &isOK );
3579   }
3580
3581   gp_Dir normal;
3582   isOK = false;
3583
3584   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3585
3586   if ( !shiftInside &&
3587        helper.IsDegenShape( node->getshapeId() ) &&
3588        getFaceNormalAtSingularity( uv, face, helper, normal ))
3589   {
3590     isOK = true;
3591     return normal.XYZ();
3592   }
3593
3594   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3595   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3596
3597   if ( pointKind == IMPOSSIBLE &&
3598        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3599   {
3600     // probably NormEstim() failed due to a too high tolerance
3601     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3602     isOK = ( pointKind < IMPOSSIBLE );
3603   }
3604   if ( pointKind < IMPOSSIBLE )
3605   {
3606     if ( pointKind != REGULAR &&
3607          !shiftInside &&
3608          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3609     {
3610       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3611       if ( normShift * normal.XYZ() < 0. )
3612         normal = normShift;
3613     }
3614     isOK = true;
3615   }
3616
3617   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3618   {
3619     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3620
3621     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3622     while ( fIt->more() )
3623     {
3624       const SMDS_MeshElement* f = fIt->next();
3625       if ( f->getshapeId() == faceID )
3626       {
3627         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3628         if ( isOK )
3629         {
3630           TopoDS_Face ff = face;
3631           ff.Orientation( TopAbs_FORWARD );
3632           if ( helper.IsReversedSubMesh( ff ))
3633             normal.Reverse();
3634           break;
3635         }
3636       }
3637     }
3638   }
3639   return normal.XYZ();
3640 }
3641
3642 //================================================================================
3643 /*!
3644  * \brief Try to get normal at a singularity of a surface basing on it's nature
3645  */
3646 //================================================================================
3647
3648 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3649                                                   const TopoDS_Face&  face,
3650                                                   SMESH_MesherHelper& helper,
3651                                                   gp_Dir&             normal )
3652 {
3653   BRepAdaptor_Surface surface( face );
3654   gp_Dir axis;
3655   if ( !getRovolutionAxis( surface, axis ))
3656     return false;
3657
3658   double f,l, d, du, dv;
3659   f = surface.FirstUParameter();
3660   l = surface.LastUParameter();
3661   d = ( uv.X() - f ) / ( l - f );
3662   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3663   f = surface.FirstVParameter();
3664   l = surface.LastVParameter();
3665   d = ( uv.Y() - f ) / ( l - f );
3666   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3667
3668   gp_Dir refDir;
3669   gp_Pnt2d testUV = uv;
3670   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3671   double tol = 1e-5;
3672   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3673   for ( int iLoop = 0; true ; ++iLoop )
3674   {
3675     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3676     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3677       break;
3678     if ( iLoop > 20 )
3679       return false;
3680     tol /= 10.;
3681   }
3682
3683   if ( axis * refDir < 0. )
3684     axis.Reverse();
3685
3686   normal = axis;
3687
3688   return true;
3689 }
3690
3691 //================================================================================
3692 /*!
3693  * \brief Return a normal at a node weighted with angles taken by faces
3694  */
3695 //================================================================================
3696
3697 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3698 {
3699   const SMDS_MeshNode* n = edge->_nodes[0];
3700
3701   gp_XYZ resNorm(0,0,0);
3702   SMESH_TNodeXYZ p0( n ), pP, pN;
3703   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3704   {
3705     pP.Set( edge->_simplices[i]._nPrev );
3706     pN.Set( edge->_simplices[i]._nNext );
3707     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3708     double l0P = v0P.SquareMagnitude();
3709     double l0N = v0N.SquareMagnitude();
3710     double lPN = vPN.SquareMagnitude();
3711     if ( l0P < std::numeric_limits<double>::min() ||
3712          l0N < std::numeric_limits<double>::min() ||
3713          lPN < std::numeric_limits<double>::min() )
3714       continue;
3715     double lNorm = norm.SquareMagnitude();
3716     double  sin2 = lNorm / l0P / l0N;
3717     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3718
3719     double weight = sin2 * angle / lPN;
3720     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3721   }
3722
3723   return resNorm;
3724 }
3725
3726 //================================================================================
3727 /*!
3728  * \brief Return a normal at a node by getting a common point of offset planes
3729  *        defined by the FACE normals
3730  */
3731 //================================================================================
3732
3733 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3734                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3735                                            int                              nbFaces )
3736 {
3737   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3738
3739   gp_XYZ resNorm(0,0,0);
3740   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3741   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3742   {
3743     for ( int i = 0; i < nbFaces; ++i )
3744       resNorm += f2Normal[i].second;
3745     return resNorm;
3746   }
3747
3748   // prepare _OffsetPlane's
3749   vector< _OffsetPlane > pln( nbFaces );
3750   for ( int i = 0; i < nbFaces; ++i )
3751   {
3752     pln[i]._faceIndex = i;
3753     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3754   }
3755
3756   // intersect neighboring OffsetPlane's
3757   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3758   while ( const TopoDS_Shape* edge = edgeIt->next() )
3759   {
3760     int f1 = -1, f2 = -1;
3761     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3762       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3763         (( f1 < 0 ) ? f1 : f2 ) = i;
3764
3765     if ( f2 >= 0 )
3766       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ]);
3767   }
3768
3769   // get a common point
3770   gp_XYZ commonPnt( 0, 0, 0 );
3771   int nbPoints = 0;
3772   bool isPointFound;
3773   for ( int i = 0; i < nbFaces; ++i )
3774   {
3775     commonPnt += pln[ i ].GetCommonPoint( isPointFound );
3776     nbPoints  += isPointFound;
3777   }
3778   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3779   if ( nbPoints == 0 )
3780     return wgtNorm;
3781
3782   commonPnt /= nbPoints;
3783   resNorm = commonPnt - p0;
3784
3785   // choose the best among resNorm and wgtNorm
3786   resNorm.Normalize();
3787   wgtNorm.Normalize();
3788   double resMinDot = std::numeric_limits<double>::max();
3789   double wgtMinDot = std::numeric_limits<double>::max();
3790   for ( int i = 0; i < nbFaces; ++i )
3791   {
3792     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3793     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3794   }
3795
3796   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3797   {
3798     edge->Set( _LayerEdge::MULTI_NORMAL );
3799   }
3800
3801   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3802 }
3803
3804 //================================================================================
3805 /*!
3806  * \brief Compute line of intersection of 2 planes
3807  */
3808 //================================================================================
3809
3810 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane& pln )
3811 {
3812   int iNext = bool( _faceIndexNext[0] >= 0 );
3813   _faceIndexNext[ iNext ] = pln._faceIndex;
3814
3815   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3816   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3817
3818   gp_XYZ lineDir = n1 ^ n2;
3819
3820   double x = Abs( lineDir.X() );
3821   double y = Abs( lineDir.Y() );
3822   double z = Abs( lineDir.Z() );
3823
3824   int cooMax; // max coordinate
3825   if (x > y) {
3826     if (x > z) cooMax = 1;
3827     else       cooMax = 3;
3828   }
3829   else {
3830     if (y > z) cooMax = 2;
3831     else       cooMax = 3;
3832   }
3833
3834   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3835     return;
3836
3837   gp_Pnt linePos;
3838   // the constants in the 2 plane equations
3839   double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3840   double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3841
3842   switch ( cooMax ) {
3843   case 1:
3844     linePos.SetX(  0 );
3845     linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3846     linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3847     break;
3848   case 2:
3849     linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3850     linePos.SetY(  0 );
3851     linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3852     break;
3853   case 3:
3854     linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3855     linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3856     linePos.SetZ(  0 );
3857   }
3858
3859   gp_Lin& line = _lines[ iNext ];
3860   line.SetDirection( lineDir );
3861   line.SetLocation ( linePos );
3862
3863   _isLineOK[ iNext ] = true;
3864
3865
3866   iNext = bool( pln._faceIndexNext[0] >= 0 );
3867   pln._lines        [ iNext ] = line;
3868   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3869   pln._isLineOK     [ iNext ] = true;
3870 }
3871
3872 //================================================================================
3873 /*!
3874  * \brief Computes intersection point of two _lines
3875  */
3876 //================================================================================
3877
3878 gp_XYZ _OffsetPlane::GetCommonPoint(bool& isFound) const
3879 {
3880   gp_XYZ p( 0,0,0 );
3881   isFound = false;
3882
3883   if ( NbLines() == 2 )
3884   {
3885     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3886     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
3887     if ( Abs( dot01 ) > std::numeric_limits<double>::min() )
3888     {
3889       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3890       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
3891       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3892       isFound = true;
3893     }
3894   }
3895
3896   return p;
3897 }
3898
3899 //================================================================================
3900 /*!
3901  * \brief Find 2 neigbor nodes of a node on EDGE
3902  */
3903 //================================================================================
3904
3905 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3906                                         const SMDS_MeshNode*& n1,
3907                                         const SMDS_MeshNode*& n2,
3908                                         _EdgesOnShape&        eos,
3909                                         _SolidData&           data)
3910 {
3911   const SMDS_MeshNode* node = edge->_nodes[0];
3912   const int        shapeInd = eos._shapeID;
3913   SMESHDS_SubMesh*   edgeSM = 0;
3914   if ( eos.ShapeType() == TopAbs_EDGE )
3915   {
3916     edgeSM = eos._subMesh->GetSubMeshDS();
3917     if ( !edgeSM || edgeSM->NbElements() == 0 )
3918       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3919   }
3920   int iN = 0;
3921   n2 = 0;
3922   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3923   while ( eIt->more() && !n2 )
3924   {
3925     const SMDS_MeshElement* e = eIt->next();
3926     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
3927     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3928     if ( edgeSM )
3929     {
3930       if (!edgeSM->Contains(e)) continue;
3931     }
3932     else
3933     {
3934       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
3935       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
3936     }
3937     ( iN++ ? n2 : n1 ) = nNeibor;
3938   }
3939   if ( !n2 )
3940     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3941   return true;
3942 }
3943
3944 //================================================================================
3945 /*!
3946  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3947  */
3948 //================================================================================
3949
3950 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3951                                      const SMDS_MeshNode* n2,
3952                                      const _EdgesOnShape& eos,
3953                                      SMESH_MesherHelper&  helper)
3954 {
3955   if ( eos.ShapeType() != TopAbs_EDGE )
3956     return;
3957
3958   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
3959   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3960   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3961
3962   // Set _curvature
3963
3964   double      sumLen = vec1.Modulus() + vec2.Modulus();
3965   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3966   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3967   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3968   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3969   if ( _curvature ) delete _curvature;
3970   _curvature = _Curvature::New( avgNormProj, avgLen );
3971   // if ( _curvature )
3972   //   debugMsg( _nodes[0]->GetID()
3973   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3974   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3975   //             << _curvature->lenDelta(0) );
3976
3977   // Set _plnNorm
3978
3979   if ( eos._sWOL.IsNull() )
3980   {
3981     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
3982     // if ( SMESH_Algo::isDegenerated( E ))
3983     //   return;
3984     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
3985     gp_XYZ plnNorm = dirE ^ _normal;
3986     double proj0   = plnNorm * vec1;
3987     double proj1   = plnNorm * vec2;
3988     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3989     {
3990       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3991       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3992     }
3993   }
3994 }
3995
3996 //================================================================================
3997 /*!
3998  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3999  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4000  */
4001 //================================================================================
4002
4003 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4004                          _EdgesOnShape&      eos,
4005                          SMESH_MesherHelper& helper )
4006 {
4007   _nodes     = other._nodes;
4008   _normal    = other._normal;
4009   _len       = 0;
4010   _lenFactor = other._lenFactor;
4011   _cosin     = other._cosin;
4012   _2neibors  = other._2neibors;
4013   _curvature = 0; std::swap( _curvature, other._curvature );
4014   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4015
4016   gp_XYZ lastPos( 0,0,0 );
4017   if ( eos.SWOLType() == TopAbs_EDGE )
4018   {
4019     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4020     _pos.push_back( gp_XYZ( u, 0, 0));
4021
4022     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4023     lastPos.SetX( u );
4024   }
4025   else // TopAbs_FACE
4026   {
4027     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4028     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4029
4030     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4031     lastPos.SetX( uv.X() );
4032     lastPos.SetY( uv.Y() );
4033   }
4034   return lastPos;
4035 }
4036
4037 //================================================================================
4038 /*!
4039  * \brief Set _cosin and _lenFactor
4040  */
4041 //================================================================================
4042
4043 void _LayerEdge::SetCosin( double cosin )
4044 {
4045   _cosin = cosin;
4046   cosin = Abs( _cosin );
4047   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4048   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4049 }
4050
4051 //================================================================================
4052 /*!
4053  * \brief Check if another _LayerEdge is a neighbor on EDGE
4054  */
4055 //================================================================================
4056
4057 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4058 {
4059   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4060           ( edge->_2neibors && edge->_2neibors->include( this )));
4061 }
4062
4063 //================================================================================
4064 /*!
4065  * \brief Fills a vector<_Simplex > 
4066  */
4067 //================================================================================
4068
4069 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4070                              vector<_Simplex>&    simplices,
4071                              const set<TGeomID>&  ingnoreShapes,
4072                              const _SolidData*    dataToCheckOri,
4073                              const bool           toSort)
4074 {
4075   simplices.clear();
4076   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4077   while ( fIt->more() )
4078   {
4079     const SMDS_MeshElement* f = fIt->next();
4080     const TGeomID    shapeInd = f->getshapeId();
4081     if ( ingnoreShapes.count( shapeInd )) continue;
4082     const int nbNodes = f->NbCornerNodes();
4083     const int  srcInd = f->GetNodeIndex( node );
4084     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4085     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4086     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4087     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4088       std::swap( nPrev, nNext );
4089     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4090   }
4091
4092   if ( toSort )
4093     SortSimplices( simplices );
4094 }
4095
4096 //================================================================================
4097 /*!
4098  * \brief Set neighbor simplices side by side
4099  */
4100 //================================================================================
4101
4102 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4103 {
4104   vector<_Simplex> sortedSimplices( simplices.size() );
4105   sortedSimplices[0] = simplices[0];
4106   size_t nbFound = 0;
4107   for ( size_t i = 1; i < simplices.size(); ++i )
4108   {
4109     for ( size_t j = 1; j < simplices.size(); ++j )
4110       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4111       {
4112         sortedSimplices[i] = simplices[j];
4113         nbFound++;
4114         break;
4115       }
4116   }
4117   if ( nbFound == simplices.size() - 1 )
4118     simplices.swap( sortedSimplices );
4119 }
4120
4121 //================================================================================
4122 /*!
4123  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4124  */
4125 //================================================================================
4126
4127 void _ViscousBuilder::makeGroupOfLE()
4128 {
4129 #ifdef _DEBUG_
4130   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4131   {
4132     if ( _sdVec[i]._n2eMap.empty() ) continue;
4133
4134     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4135     TNode2Edge::iterator n2e;
4136     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4137     {
4138       _LayerEdge* le = n2e->second;
4139       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4140       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4141       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4142       if ( le ) {
4143         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4144                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4145       }
4146     }
4147     dumpFunctionEnd();
4148
4149     dumpFunction( SMESH_Comment("makeNormals") << i );
4150     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4151     {
4152       _LayerEdge* edge = n2e->second;
4153       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4154       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4155       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4156               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4157     }
4158     dumpFunctionEnd();
4159
4160     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4161     dumpCmd( "faceId1 = mesh.NbElements()" );
4162     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4163     for ( ; fExp.More(); fExp.Next() )
4164     {
4165       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4166       {
4167         if ( sm->NbElements() == 0 ) continue;
4168         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4169         while ( fIt->more())
4170         {
4171           const SMDS_MeshElement* e = fIt->next();
4172           SMESH_Comment cmd("mesh.AddFace([");
4173           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4174             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4175           dumpCmd( cmd );
4176         }
4177       }
4178     }
4179     dumpCmd( "faceId2 = mesh.NbElements()" );
4180     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4181              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4182              << "'%s-%s' % (faceId1+1, faceId2))");
4183     dumpFunctionEnd();
4184   }
4185 #endif
4186 }
4187
4188 //================================================================================
4189 /*!
4190  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4191  */
4192 //================================================================================
4193
4194 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4195 {
4196   data._geomSize = Precision::Infinite();
4197   double intersecDist;
4198   const SMDS_MeshElement* face;
4199   SMESH_MesherHelper helper( *_mesh );
4200
4201   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4202     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4203                                            data._proxyMesh->GetFaces( data._solid )));
4204
4205   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4206   {
4207     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4208     if ( eos._edges.empty() )
4209       continue;
4210     // get neighbor faces intersection with which should not be considered since
4211     // collisions are avoided by means of smoothing
4212     set< TGeomID > neighborFaces;
4213     if ( eos._hyp.ToSmooth() )
4214     {
4215       SMESH_subMeshIteratorPtr subIt =
4216         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4217       while ( subIt->more() )
4218       {
4219         SMESH_subMesh* sm = subIt->next();
4220         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4221         while ( const TopoDS_Shape* face = fIt->next() )
4222           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4223       }
4224     }
4225     // find intersections
4226     double thinkness = eos._hyp.GetTotalThickness();
4227     for ( size_t i = 0; i < eos._edges.size(); ++i )
4228     {
4229       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4230       eos._edges[i]->_maxLen = thinkness;
4231       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4232       if ( intersecDist > 0 && face )
4233       {
4234         data._geomSize = Min( data._geomSize, intersecDist );
4235         if ( !neighborFaces.count( face->getshapeId() ))
4236           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4237       }
4238     }
4239   }
4240 }
4241
4242 //================================================================================
4243 /*!
4244  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4245  */
4246 //================================================================================
4247
4248 bool _ViscousBuilder::inflate(_SolidData& data)
4249 {
4250   SMESH_MesherHelper helper( *_mesh );
4251
4252   // Limit inflation step size by geometry size found by itersecting
4253   // normals of _LayerEdge's with mesh faces
4254   if ( data._stepSize > 0.3 * data._geomSize )
4255     limitStepSize( data, 0.3 * data._geomSize );
4256
4257   const double tgtThick = data._maxThickness;
4258   if ( data._stepSize > data._minThickness )
4259     limitStepSize( data, data._minThickness );
4260
4261   if ( data._stepSize < 1. )
4262     data._epsilon = data._stepSize * 1e-7;
4263
4264   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4265
4266   findCollisionEdges( data, helper );
4267
4268   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4269   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4270     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4271          data._edgesOnShape[i]._edges.size() > 0 &&
4272          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4273     {
4274       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4275       data._edgesOnShape[i]._edges[0]->Block( data );
4276     }
4277
4278   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4279
4280   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4281   int nbSteps = 0, nbRepeats = 0;
4282   while ( avgThick < 0.99 )
4283   {
4284     // new target length
4285     double prevThick = curThick;
4286     curThick += data._stepSize;
4287     if ( curThick > tgtThick )
4288     {
4289       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4290       nbRepeats++;
4291     }
4292
4293     double stepSize = curThick - prevThick;
4294     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4295
4296     // Elongate _LayerEdge's
4297     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4298     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4299     {
4300       _EdgesOnShape& eos = data._edgesOnShape[iS];
4301       if ( eos._edges.empty() ) continue;
4302
4303       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4304       for ( size_t i = 0; i < eos._edges.size(); ++i )
4305       {
4306         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4307       }
4308     }
4309     dumpFunctionEnd();
4310
4311     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4312       return false;
4313
4314     // Improve and check quality
4315     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4316     {
4317       if ( nbSteps > 0 )
4318       {
4319 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4320         debugMsg("NOT INVALIDATED STEP!");
4321         return error("Smoothing failed", data._index);
4322 #endif
4323         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4324         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4325         {
4326           _EdgesOnShape& eos = data._edgesOnShape[iS];
4327           for ( size_t i = 0; i < eos._edges.size(); ++i )
4328             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4329         }
4330         dumpFunctionEnd();
4331       }
4332       break; // no more inflating possible
4333     }
4334     nbSteps++;
4335
4336     // Evaluate achieved thickness
4337     avgThick = 0;
4338     int nbActiveEdges = 0;
4339     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4340     {
4341       _EdgesOnShape& eos = data._edgesOnShape[iS];
4342       if ( eos._edges.empty() ) continue;
4343
4344       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4345       for ( size_t i = 0; i < eos._edges.size(); ++i )
4346       {
4347         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4348         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4349       }
4350     }
4351     avgThick /= data._n2eMap.size();
4352     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4353
4354 #ifdef BLOCK_INFLATION
4355     if ( nbActiveEdges == 0 )
4356     {
4357       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4358       break;
4359     }
4360 #else
4361     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4362     {
4363       debugMsg( "-- Stop inflation since "
4364                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4365                 << tgtThick * avgThick << " ) * " << safeFactor );
4366       break;
4367     }
4368 #endif
4369     // new step size
4370     limitStepSize( data, 0.25 * distToIntersection );
4371     if ( data._stepSizeNodes[0] )
4372       data._stepSize = data._stepSizeCoeff *
4373         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4374
4375   } // while ( avgThick < 0.99 )
4376
4377   if ( nbSteps == 0 )
4378     return error("failed at the very first inflation step", data._index);
4379
4380   if ( avgThick < 0.99 )
4381   {
4382     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4383     {
4384       data._proxyMesh->_warning.reset
4385         ( new SMESH_ComputeError (COMPERR_WARNING,
4386                                   SMESH_Comment("Thickness ") << tgtThick <<
4387                                   " of viscous layers not reached,"
4388                                   " average reached thickness is " << avgThick*tgtThick));
4389     }
4390   }
4391
4392   // Restore position of src nodes moved by inflation on _noShrinkShapes
4393   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4394   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4395   {
4396     _EdgesOnShape& eos = data._edgesOnShape[iS];
4397     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4398       for ( size_t i = 0; i < eos._edges.size(); ++i )
4399       {
4400         restoreNoShrink( *eos._edges[ i ] );
4401       }
4402   }
4403   dumpFunctionEnd();
4404
4405   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4406 }
4407
4408 //================================================================================
4409 /*!
4410  * \brief Improve quality of layer inner surface and check intersection
4411  */
4412 //================================================================================
4413
4414 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4415                                      const int   infStep,
4416                                      double &    distToIntersection)
4417 {
4418   if ( data._nbShapesToSmooth == 0 )
4419     return true; // no shapes needing smoothing
4420
4421   bool moved, improved;
4422   double vol;
4423   vector< _LayerEdge* >    movedEdges, badEdges;
4424   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4425   vector< bool >           isConcaveFace;
4426
4427   SMESH_MesherHelper helper(*_mesh);
4428   Handle(ShapeAnalysis_Surface) surface;
4429   TopoDS_Face F;
4430
4431   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4432   {
4433     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4434
4435     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4436     {
4437       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4438       if ( !eos._toSmooth ||
4439            eos.ShapeType() != shapeType ||
4440            eos._edges.empty() )
4441         continue;
4442
4443       // already smoothed?
4444       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4445       // if ( !toSmooth ) continue;
4446
4447       if ( !eos._hyp.ToSmooth() )
4448       {
4449         // smooth disabled by the user; check validy only
4450         if ( !isFace ) continue;
4451         for ( size_t i = 0; i < eos._edges.size(); ++i )
4452         {
4453           _LayerEdge* edge = eos._edges[i];
4454           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4455             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4456             {
4457               debugMsg( "-- Stop inflation. Bad simplex ("
4458                         << " "<< edge->_nodes[0]->GetID()
4459                         << " "<< edge->_nodes.back()->GetID()
4460                         << " "<< edge->_simplices[iF]._nPrev->GetID()
4461                         << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4462               return false;
4463             }
4464         }
4465         continue; // goto the next EDGE or FACE
4466       }
4467
4468       // prepare data
4469       if ( eos.SWOLType() == TopAbs_FACE )
4470       {
4471         if ( !F.IsSame( eos._sWOL )) {
4472           F = TopoDS::Face( eos._sWOL );
4473           helper.SetSubShape( F );
4474           surface = helper.GetSurface( F );
4475         }
4476       }
4477       else
4478       {
4479         F.Nullify(); surface.Nullify();
4480       }
4481       const TGeomID sInd = eos._shapeID;
4482
4483       // perform smoothing
4484
4485       if ( eos.ShapeType() == TopAbs_EDGE )
4486       {
4487         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4488
4489         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4490         {
4491           // smooth on EDGE's (normally we should not get here)
4492           int step = 0;
4493           do {
4494             moved = false;
4495             for ( size_t i = 0; i < eos._edges.size(); ++i )
4496             {
4497               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4498             }
4499             dumpCmd( SMESH_Comment("# end step ")<<step);
4500           }
4501           while ( moved && step++ < 5 );
4502         }
4503         dumpFunctionEnd();
4504       }
4505
4506       else // smooth on FACE
4507       {
4508         eosC1.clear();
4509         eosC1.push_back( & eos );
4510         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4511
4512         movedEdges.clear();
4513         isConcaveFace.resize( eosC1.size() );
4514         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4515         {
4516           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4517           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4518           for ( size_t i = 0; i < edges.size(); ++i )
4519             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4520                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4521               movedEdges.push_back( edges[i] );
4522
4523           makeOffsetSurface( *eosC1[ iEOS ], helper );
4524         }
4525
4526         int step = 0, stepLimit = 5, nbBad = 0;
4527         while (( ++step <= stepLimit ) || improved )
4528         {
4529           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4530                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4531           int oldBadNb = nbBad;
4532           badEdges.clear();
4533
4534 #ifdef INCREMENTAL_SMOOTH
4535           bool findBest = false; // ( step == stepLimit );
4536           for ( size_t i = 0; i < movedEdges.size(); ++i )
4537           {
4538             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4539             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4540               badEdges.push_back( movedEdges[i] );
4541           }
4542 #else
4543           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4544           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4545           {
4546             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4547             for ( size_t i = 0; i < edges.size(); ++i )
4548             {
4549               edges[i]->Unset( _LayerEdge::SMOOTHED );
4550               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4551                 badEdges.push_back( eos._edges[i] );
4552             }
4553           }
4554 #endif
4555           nbBad = badEdges.size();
4556
4557           if ( nbBad > 0 )
4558             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4559
4560           if ( !badEdges.empty() && step >= stepLimit / 2 )
4561           {
4562             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4563               stepLimit = 9;
4564
4565             // resolve hard smoothing situation around concave VERTEXes
4566             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4567             {
4568               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4569               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4570                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4571                                                          step, badEdges );
4572             }
4573             // look for the best smooth of _LayerEdge's neighboring badEdges
4574             nbBad = 0;
4575             for ( size_t i = 0; i < badEdges.size(); ++i )
4576             {
4577               _LayerEdge* ledge = badEdges[i];
4578               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4579               {
4580                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4581                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4582               }
4583               ledge->Unset( _LayerEdge::SMOOTHED );
4584               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4585             }
4586             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4587           }
4588
4589           if ( nbBad == oldBadNb  &&
4590                nbBad > 0 &&
4591                step < stepLimit ) // smooth w/o chech of validity
4592           {
4593             dumpFunctionEnd();
4594             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4595                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4596             for ( size_t i = 0; i < movedEdges.size(); ++i )
4597             {
4598               movedEdges[i]->SmoothWoCheck();
4599             }
4600             if ( stepLimit < 9 )
4601               stepLimit++;
4602           }
4603
4604           improved = ( nbBad < oldBadNb );
4605
4606           dumpFunctionEnd();
4607
4608           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4609             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4610             {
4611               putOnOffsetSurface( *eosC1[ iEOS ], infStep, step, /*moveAll=*/step == 1 );
4612             }
4613
4614         } // smoothing steps
4615
4616         // project -- to prevent intersections or fix bad simplices
4617         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4618         {
4619           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4620             putOnOffsetSurface( *eosC1[ iEOS ], infStep );
4621         }
4622
4623         if ( !badEdges.empty() )
4624         {
4625           badEdges.clear();
4626           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4627           {
4628             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4629             {
4630               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4631
4632               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4633               edge->CheckNeiborsOnBoundary( & badEdges );
4634               if ( nbBad > 0 )
4635               {
4636                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4637                 const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4638                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4639                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4640                   {
4641                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4642                              << " "<< tgtXYZ._node->GetID()
4643                              << " "<< edge->_simplices[j]._nPrev->GetID()
4644                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4645                     badEdges.push_back( edge );
4646                     break;
4647                   }
4648               }
4649             }
4650           }
4651
4652           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4653           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4654
4655           if ( nbBad > 0 )
4656             return false;
4657         }
4658
4659       } // // smooth on FACE's
4660     } // loop on shapes
4661   } // smooth on [ EDGEs, FACEs ]
4662
4663   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4664   eosC1.resize(1);
4665   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4666   {
4667     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4668     if ( eos.ShapeType() == TopAbs_FACE ||
4669          eos._edges.empty() ||
4670          !eos._sWOL.IsNull() )
4671       continue;
4672
4673     badEdges.clear();
4674     for ( size_t i = 0; i < eos._edges.size(); ++i )
4675     {
4676       _LayerEdge*      edge = eos._edges[i];
4677       if ( edge->_nodes.size() < 2 ) continue;
4678       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4679       const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4680       //const gp_XYZ& prevXYZ = edge->PrevPos();
4681       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4682         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4683         {
4684           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4685                    << " "<< tgtXYZ._node->GetID()
4686                    << " "<< edge->_simplices[j]._nPrev->GetID()
4687                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4688           badEdges.push_back( edge );
4689           break;
4690         }
4691     }
4692
4693     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4694     eosC1[0] = &eos;
4695     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4696     if ( nbBad > 0 )
4697       return false;
4698   }
4699
4700
4701   // Check if the last segments of _LayerEdge intersects 2D elements;
4702   // checked elements are either temporary faces or faces on surfaces w/o the layers
4703
4704   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4705     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4706                                            data._proxyMesh->GetFaces( data._solid )) );
4707
4708 #ifdef BLOCK_INFLATION
4709   const bool toBlockInfaltion = true;
4710 #else
4711   const bool toBlockInfaltion = false;
4712 #endif
4713   distToIntersection = Precision::Infinite();
4714   double dist;
4715   const SMDS_MeshElement* intFace = 0;
4716   const SMDS_MeshElement* closestFace = 0;
4717   _LayerEdge* le = 0;
4718   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4719   {
4720     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4721     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4722       continue;
4723     for ( size_t i = 0; i < eos._edges.size(); ++i )
4724     {
4725       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4726            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4727         continue;
4728       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4729       {
4730         return false;
4731         // commented due to "Illegal hash-positionPosition" error in NETGEN
4732         // on Debian60 on viscous_layers_01/B2 case
4733         // Collision; try to deflate _LayerEdge's causing it
4734         // badEdges.clear();
4735         // badEdges.push_back( eos._edges[i] );
4736         // eosC1[0] = & eos;
4737         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4738         // if ( nbBad > 0 )
4739         //   return false;
4740
4741         // badEdges.clear();
4742         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4743         // {
4744         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4745         //   {
4746         //     const SMDS_MeshElement* srcFace =
4747         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4748         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4749         //     while ( nIt->more() )
4750         //     {
4751         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4752         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4753         //       if ( n2e != data._n2eMap.end() )
4754         //         badEdges.push_back( n2e->second );
4755         //     }
4756         //     eosC1[0] = eof;
4757         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4758         //     if ( nbBad > 0 )
4759         //       return false;
4760         //   }
4761         // }
4762         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4763         //   return false;
4764         // else
4765         //   continue;
4766       }
4767       if ( !intFace )
4768       {
4769         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4770         debugMsg( msg );
4771         continue;
4772       }
4773
4774       const bool isShorterDist = ( distToIntersection > dist );
4775       if ( toBlockInfaltion || isShorterDist )
4776       {
4777         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4778         // lying on this _ConvexFace
4779         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4780           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4781             continue;
4782
4783         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4784         // ( avoid limiting the thickness on the case of issue 22576)
4785         if ( intFace->getshapeId() == eos._shapeID  )
4786           continue;
4787
4788         // ignore intersection with intFace of an adjacent FACE
4789         if ( dist > 0 )
4790         {
4791           bool toIgnore = false;
4792           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4793           {
4794             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4795             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4796             {
4797               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4798               for ( ; !toIgnore && edge.More(); edge.Next() )
4799                 // is adjacent - has a common EDGE
4800                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4801
4802               if ( toIgnore ) // check angle between normals
4803               {
4804                 gp_XYZ normal;
4805                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4806                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4807               }
4808             }
4809           }
4810           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4811           {
4812             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4813             {
4814               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4815               toIgnore = ( nInd >= 0 );
4816             }
4817           }
4818           if ( toIgnore )
4819             continue;
4820         }
4821
4822         // intersection not ignored
4823
4824         if ( toBlockInfaltion &&
4825              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4826         {
4827           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4828           eos._edges[i]->Block( data );                  // not to inflate
4829
4830           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4831           {
4832             // block _LayerEdge's, on top of which intFace is
4833             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4834             {
4835               const SMDS_MeshElement* srcFace =
4836                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4837               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4838               while ( nIt->more() )
4839               {
4840                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4841                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4842                 if ( n2e != data._n2eMap.end() )
4843                   n2e->second->Block( data );
4844               }
4845             }
4846           }
4847         }
4848
4849         if ( isShorterDist )
4850         {
4851           distToIntersection = dist;
4852           le = eos._edges[i];
4853           closestFace = intFace;
4854         }
4855
4856       } // if ( toBlockInfaltion || isShorterDist )
4857     } // loop on eos._edges
4858   } // loop on data._edgesOnShape
4859
4860 #ifdef __myDEBUG
4861   if ( closestFace )
4862   {
4863     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4864     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4865          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4866          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4867          << ") distance = " << distToIntersection<< endl;
4868   }
4869 #endif
4870
4871   return true;
4872 }
4873
4874 //================================================================================
4875 /*!
4876  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4877  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
4878  *  \return int - resulting nb of bad _LayerEdge's
4879  */
4880 //================================================================================
4881
4882 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
4883                                           SMESH_MesherHelper&       helper,
4884                                           vector< _LayerEdge* >&    badSmooEdges,
4885                                           vector< _EdgesOnShape* >& eosC1,
4886                                           const int                 infStep )
4887 {
4888   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4889
4890   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4891
4892   //data.UnmarkEdges();
4893
4894   double vol;
4895   //size_t iniNbBad = badSmooEdges.size();
4896   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
4897   {
4898     _LayerEdge* edge = badSmooEdges[i];
4899     if ( edge->NbSteps() < 2 /*|| edge->Is( _LayerEdge::MARKED )*/)
4900       continue;
4901
4902     _EdgesOnShape* eos = data.GetShapeEdges( edge );
4903     edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
4904     edge->Block( data );
4905     //edge->Set( _LayerEdge::MARKED );
4906
4907     // look for _LayerEdge's of bad _simplices
4908     SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
4909     const gp_XYZ& prevXYZ1 = edge->PrevCheckPos();
4910     const gp_XYZ& prevXYZ2 = edge->PrevPos();
4911     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4912     {
4913       if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) &&
4914           ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol )))
4915         continue;
4916       for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
4917         if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
4918           badSmooEdges.push_back( edge->_neibors[iN] );
4919     }
4920
4921     if ( eos->ShapeType() == TopAbs_VERTEX )
4922     {
4923       // re-smooth on analytical EDGEs
4924       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
4925       while ( const TopoDS_Shape* e = eIt->next() )
4926         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
4927           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
4928           {
4929             TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
4930             if ( eoe->SWOLType() == TopAbs_FACE ) {
4931               F       = TopoDS::Face( eoe->_sWOL );
4932               surface = helper.GetSurface( F );
4933             }
4934             eoe->_edgeSmoother->Perform( data, surface, F, helper );
4935           }
4936
4937     }
4938   } // loop on badSmooEdges
4939
4940
4941   // check result of invalidation
4942
4943   int nbBad = 0;
4944   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4945   {
4946     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4947     {
4948       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4949       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
4950       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4951       const gp_XYZ& prevXYZ = edge->PrevCheckPos();
4952       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4953         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4954         {
4955           ++nbBad;
4956           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
4957                    << " "<< tgtXYZ._node->GetID()
4958                    << " "<< edge->_simplices[j]._nPrev->GetID()
4959                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4960         }
4961     }
4962   }
4963   dumpFunctionEnd();
4964
4965   return nbBad;
4966 }
4967
4968 //================================================================================
4969 /*!
4970  * \brief Create an offset surface
4971  */
4972 //================================================================================
4973
4974 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
4975 {
4976   if ( eos._offsetSurf.IsNull() ||
4977        eos._edgeForOffset == 0 ||
4978        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
4979     return;
4980
4981   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
4982
4983   // find offset
4984   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
4985   gp_Pnt2d   uv = baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
4986   double offset = baseSurface->Gap();
4987
4988   eos._offsetSurf.Nullify();
4989
4990   try
4991   {
4992     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
4993     if ( !offsetMaker.IsDone() ) return;
4994
4995     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
4996     if ( !fExp.More() ) return;
4997
4998     TopoDS_Face F = TopoDS::Face( fExp.Current() );
4999     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5000     if ( surf.IsNull() ) return;
5001
5002     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5003   }
5004   catch ( Standard_Failure )
5005   {
5006   }
5007 }
5008
5009 //================================================================================
5010 /*!
5011  * \brief Put nodes of a curved FACE to its offset surface
5012  */
5013 //================================================================================
5014
5015 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape& eos,
5016                                           int            infStep,
5017                                           int            smooStep,
5018                                           bool           moveAll )
5019 {
5020   if ( eos._offsetSurf.IsNull() ||
5021        eos.ShapeType() != TopAbs_FACE ||
5022        eos._edgeForOffset == 0 ||
5023        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5024     return;
5025
5026   double preci = BRep_Tool::Tolerance( TopoDS::Face( eos._shape )), vol;
5027   for ( size_t i = 0; i < eos._edges.size(); ++i )
5028   {
5029     _LayerEdge* edge = eos._edges[i];
5030     edge->Unset( _LayerEdge::MARKED );
5031     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5032       continue;
5033     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5034         continue;
5035
5036     int nbBlockedAround = 0;
5037     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5038       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5039     if ( nbBlockedAround > 1 )
5040       continue;
5041
5042     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5043     gp_Pnt2d uv = eos._offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5044     if ( eos._offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5045     edge->_curvature->_uv = uv;
5046     if ( eos._offsetSurf->Gap() < 10 * preci ) continue; // same pos
5047
5048     gp_XYZ  newP = eos._offsetSurf->Value( uv ).XYZ();
5049     gp_XYZ prevP = edge->PrevCheckPos();
5050     bool      ok = true;
5051     if ( !moveAll )
5052       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5053       {
5054         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5055       }
5056     if ( ok )
5057     {
5058       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5059       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5060       edge->_pos.back() = newP;
5061
5062       edge->Set( _LayerEdge::MARKED );
5063     }
5064   }
5065
5066 #ifdef _DEBUG_
5067   // dumpMove() for debug
5068   size_t i = 0;
5069   for ( ; i < eos._edges.size(); ++i )
5070     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5071       break;
5072   if ( i < eos._edges.size() )
5073   {
5074     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5075                  << "_InfStep" << infStep << "_" << smooStep );
5076     for ( ; i < eos._edges.size(); ++i )
5077     {
5078       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5079         dumpMove( eos._edges[i]->_nodes.back() );
5080     }
5081     dumpFunctionEnd();
5082   }
5083 #endif
5084 }
5085
5086 //================================================================================
5087 /*!
5088  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5089  *        _LayerEdge's to be in a consequent order
5090  */
5091 //================================================================================
5092
5093 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5094                                                 _EdgesOnShape&      eos,
5095                                                 SMESH_MesherHelper& helper)
5096 {
5097   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5098
5099   TopLoc_Location loc; double f,l;
5100
5101   Handle(Geom_Line)   line;
5102   Handle(Geom_Circle) circle;
5103   bool isLine, isCirc;
5104   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5105   {
5106     // check if the EDGE is a line
5107     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5108     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5109       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5110
5111     line   = Handle(Geom_Line)::DownCast( curve );
5112     circle = Handle(Geom_Circle)::DownCast( curve );
5113     isLine = (!line.IsNull());
5114     isCirc = (!circle.IsNull());
5115
5116     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5117     {
5118       isLine = SMESH_Algo::IsStraight( E );
5119
5120       if ( isLine )
5121         line = new Geom_Line( gp::OX() ); // only type does matter
5122     }
5123     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5124     {
5125       // TODO
5126     }
5127   }
5128   else //////////////////////////////////////////////////////////////////////// 2D case
5129   {
5130     if ( !eos._isRegularSWOL ) // 23190
5131       return NULL;
5132
5133     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5134
5135     // check if the EDGE is a line
5136     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5137     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5138       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5139
5140     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5141     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5142     isLine = (!line2d.IsNull());
5143     isCirc = (!circle2d.IsNull());
5144
5145     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5146     {
5147       Bnd_B2d bndBox;
5148       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5149       while ( nIt->more() )
5150         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5151       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5152
5153       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5154       for ( int i = 0; i < 2 && !isLine; ++i )
5155         isLine = ( size.Coord( i+1 ) <= lineTol );
5156     }
5157     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5158     {
5159       // TODO
5160     }
5161     if ( isLine )
5162     {
5163       line = new Geom_Line( gp::OX() ); // only type does matter
5164     }
5165     else if ( isCirc )
5166     {
5167       gp_Pnt2d p = circle2d->Location();
5168       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5169       circle = new Geom_Circle( ax, 1.); // only center position does matter
5170     }
5171   }
5172
5173   if ( isLine )
5174     return line;
5175   if ( isCirc )
5176     return circle;
5177
5178   return Handle(Geom_Curve)();
5179 }
5180
5181 //================================================================================
5182 /*!
5183  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5184  */
5185 //================================================================================
5186
5187 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5188                                       Handle(ShapeAnalysis_Surface)& surface,
5189                                       const TopoDS_Face&             F,
5190                                       SMESH_MesherHelper&            helper)
5191 {
5192   if ( !isAnalytic() ) return false;
5193
5194   const size_t iFrom = 0, iTo = _eos._edges.size();
5195
5196   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5197   {
5198     if ( F.IsNull() ) // 3D
5199     {
5200       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5201       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5202       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5203       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5204       gp_XYZ newPos;
5205       for ( size_t i = iFrom; i < iTo; ++i )
5206       {
5207         _LayerEdge*       edge = _eos._edges[i];
5208         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5209         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5210
5211         if ( _eos._edges[i]->Is( _LayerEdge::NORMAL_UPDATED ))
5212         {
5213           gp_XYZ curPos  = SMESH_TNodeXYZ ( tgtNode );
5214           gp_XYZ lineDir = pSrc1 - pSrc0;
5215           double   shift = ( lineDir * ( newPos - pSrc0 ) -
5216                              lineDir * ( curPos - pSrc0 ));
5217           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5218         }
5219         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED ))
5220         {
5221           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5222           double curThick = pSrc.SquareDistance( tgtNode );
5223           double newThink = ( pSrc - newPos ).SquareModulus();
5224           if ( newThink > curThick )
5225             continue;
5226         }
5227         edge->_pos.back() = newPos;
5228         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5229         dumpMove( tgtNode );
5230       }
5231     }
5232     else // 2D
5233     {
5234       _LayerEdge* e0 = getLEdgeOnV( 0 );
5235       _LayerEdge* e1 = getLEdgeOnV( 1 );
5236       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5237       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5238       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5239       {
5240         int iPeriodic = helper.GetPeriodicIndex();
5241         if ( iPeriodic == 1 || iPeriodic == 2 )
5242         {
5243           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5244           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5245             std::swap( uv0, uv1 );
5246         }
5247       }
5248       const gp_XY rangeUV = uv1 - uv0;
5249       for ( size_t i = iFrom; i < iTo; ++i )
5250       {
5251         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5252         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5253         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5254
5255         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5256         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5257         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5258         dumpMove( tgtNode );
5259
5260         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5261         pos->SetUParameter( newUV.X() );
5262         pos->SetVParameter( newUV.Y() );
5263       }
5264     }
5265     return true;
5266   }
5267
5268   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5269   {
5270     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5271     gp_Pnt center3D = circle->Location();
5272
5273     if ( F.IsNull() ) // 3D
5274     {
5275       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5276         return true; // closed EDGE - nothing to do
5277
5278       // circle is a real curve of EDGE
5279       gp_Circ circ = circle->Circ();
5280
5281       // new center is shifted along its axis
5282       const gp_Dir& axis = circ.Axis().Direction();
5283       _LayerEdge*     e0 = getLEdgeOnV(0);
5284       _LayerEdge*     e1 = getLEdgeOnV(1);
5285       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5286       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5287       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5288       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5289       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5290
5291       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5292
5293       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5294       gp_Circ newCirc( newAxis, newRadius );
5295       gp_Vec  vecC1  ( newCenter, p1 );
5296
5297       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5298       if ( uLast < 0 )
5299         uLast += 2 * M_PI;
5300       
5301       for ( size_t i = iFrom; i < iTo; ++i )
5302       {
5303         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5304         double u = uLast * _leParams[i];
5305         gp_Pnt p = ElCLib::Value( u, newCirc );
5306         _eos._edges[i]->_pos.back() = p.XYZ();
5307
5308         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5309         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5310         dumpMove( tgtNode );
5311       }
5312       return true;
5313     }
5314     else // 2D
5315     {
5316       const gp_XY center( center3D.X(), center3D.Y() );
5317
5318       _LayerEdge* e0 = getLEdgeOnV(0);
5319       _LayerEdge* eM = _eos._edges[ 0 ];
5320       _LayerEdge* e1 = getLEdgeOnV(1);
5321       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5322       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5323       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5324       gp_Vec2d vec0( center, uv0 );
5325       gp_Vec2d vecM( center, uvM );
5326       gp_Vec2d vec1( center, uv1 );
5327       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5328       double uMidl = vec0.Angle( vecM );
5329       if ( uLast * uMidl <= 0. )
5330         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5331       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5332
5333       gp_Ax2d   axis( center, vec0 );
5334       gp_Circ2d circ( axis, radius );
5335       for ( size_t i = iFrom; i < iTo; ++i )
5336       {
5337         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5338         double    newU = uLast * _leParams[i];
5339         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5340         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5341
5342         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5343         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5344         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5345         dumpMove( tgtNode );
5346
5347         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5348         pos->SetUParameter( newUV.X() );
5349         pos->SetVParameter( newUV.Y() );
5350       }
5351     }
5352     return true;
5353   }
5354
5355   return false;
5356 }
5357
5358 //================================================================================
5359 /*!
5360  * \brief smooth _LayerEdge's on a an EDGE
5361  */
5362 //================================================================================
5363
5364 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5365                                      Handle(ShapeAnalysis_Surface)& surface,
5366                                      const TopoDS_Face&             F,
5367                                      SMESH_MesherHelper&            helper)
5368 {
5369   if ( _offPoints.empty() )
5370     return false;
5371
5372   // move _offPoints to positions along normals of _LayerEdge's
5373
5374   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5375   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 0, helper );
5376   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) setNormalOnV( 1, helper );
5377   _leOnV[0]._len = e[0]->_len;
5378   _leOnV[1]._len = e[1]->_len;
5379   for ( size_t i = 0; i < _offPoints.size(); i++ )
5380   {
5381     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5382     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5383     const double w0 = _offPoints[i]._2edges._wgt[0];
5384     const double w1 = _offPoints[i]._2edges._wgt[1];
5385     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5386     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5387     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5388
5389     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5390     _offPoints[i]._len  = avgLen;
5391   }
5392
5393   double fTol = 0;
5394   if ( !surface.IsNull() ) // project _offPoints to the FACE
5395   {
5396     fTol = 100 * BRep_Tool::Tolerance( F );
5397     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5398
5399     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5400     //if ( surface->Gap() < 0.5 * segLen )
5401       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5402
5403     for ( size_t i = 1; i < _offPoints.size(); ++i )
5404     {
5405       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5406       //if ( surface->Gap() < 0.5 * segLen )
5407         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5408     }
5409   }
5410
5411   // project tgt nodes of extreme _LayerEdge's to the offset segments
5412
5413   gp_Pnt pExtreme[2], pProj[2];
5414   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5415   {
5416     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5417     int  i = _iSeg[ is2nd ];
5418     int di = is2nd ? -1 : +1;
5419     bool projected = false;
5420     double uOnSeg, uOnSegDiff, uOnSegBestDiff = Precision::Infinite(), uOnSegPrevDiff = 0;
5421     int nbWorse = 0;
5422     do {
5423       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5424       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5425       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();
5426       uOnSegDiff = Abs( uOnSeg - 0.5 );
5427       projected  = ( uOnSegDiff <= 0.5 );
5428       if ( uOnSegDiff < uOnSegBestDiff )
5429       {
5430         _iSeg[ is2nd ] = i;
5431         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5432         uOnSegBestDiff = uOnSegDiff;
5433       }
5434       else if ( uOnSegDiff > uOnSegPrevDiff )
5435       {
5436         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5437           break;
5438       }
5439       uOnSegPrevDiff = uOnSegDiff;
5440       i += di;
5441     }
5442     while ( !projected &&
5443             i >= 0 && i+1 < (int)_offPoints.size() );
5444
5445     if ( !projected )
5446     {
5447       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5448       {
5449         _iSeg[0] = 0;
5450         _iSeg[1] = _offPoints.size()-2;
5451         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5452         return false;
5453       }
5454     }
5455   }
5456   if ( _iSeg[0] > _iSeg[1] )
5457   {
5458     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5459     return false;
5460   }
5461
5462   // compute normalized length of the offset segments located between the projections
5463
5464   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5465   vector< double > len( nbSeg + 1 );
5466   len[ iSeg++ ] = 0;
5467   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
5468   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5469   {
5470     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5471   }
5472   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
5473
5474   double d0 = pProj[0].Distance( pExtreme[0]);
5475   double d1 = pProj[1].Distance( pExtreme[1]);
5476   double fullLen = len.back() - d0 - d1;
5477   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5478     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5479
5480   // temporary replace extreme _offPoints by pExtreme
5481   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5482                    _offPoints[ _iSeg[1]+1 ]._xyz };
5483   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5484   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5485
5486   // distribute tgt nodes of _LayerEdge's between the projections
5487
5488   iSeg = 0;
5489   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5490   {
5491     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5492     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5493       iSeg++;
5494     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5495     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5496                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5497
5498     if ( surface.IsNull() )
5499     {
5500       _eos._edges[i]->_pos.back() = p;
5501     }
5502     else // project a new node position to a FACE
5503     {
5504       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5505       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5506
5507       p = surface->Value( uv2 ).XYZ();
5508       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5509     }
5510     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5511     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5512     dumpMove( tgtNode );
5513   }
5514
5515   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5516   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5517
5518   return true;
5519 }
5520
5521 //================================================================================
5522 /*!
5523  * \brief Prepare for smoothing
5524  */
5525 //================================================================================
5526
5527 void _Smoother1D::prepare(_SolidData& data)
5528 {
5529   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5530   _curveLen = SMESH_Algo::EdgeLength( E );
5531
5532   // sort _LayerEdge's by position on the EDGE
5533   data.SortOnEdge( E, _eos._edges );
5534
5535   SMESH_MesherHelper& helper = data.GetHelper();
5536
5537   // compute normalized param of _eos._edges on EDGE
5538   _leParams.resize( _eos._edges.size() + 1 );
5539   {
5540     double curLen, prevLen = _leParams[0] = 1.0;
5541     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5542     _leParams[0] = 0;
5543     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5544     {
5545       gp_Pnt p = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5546       //curLen = prevLen * _eos._edges[i]->_2neibors->_wgt[1] / _eos._edges[i]->_2neibors->_wgt[0];
5547       curLen = p.Distance( pPrev );
5548       _leParams[i+1] = _leParams[i] + curLen;
5549       prevLen = curLen;
5550       pPrev = p;
5551     }
5552     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5553     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5554       _leParams[i] = _leParams[i+1] / fullLen;
5555   }
5556
5557   // find intersection of neighbor _LayerEdge's to limit _maxLen
5558   // according to EDGE curvature (IPAL52648)
5559   _LayerEdge* e0 = _eos._edges[0];
5560   for ( size_t i = 1; i < _eos._edges.size(); ++i )
5561   {
5562     _LayerEdge* ei = _eos._edges[i];
5563     gp_XYZ plnNorm = e0->_normal ^ ei->_normal;
5564     gp_XYZ   perp0 = e0->_normal ^ plnNorm;
5565     double   dot0i = perp0 * ei->_normal;
5566     if ( Abs( dot0i ) > std::numeric_limits<double>::min() )
5567     {
5568       SMESH_TNodeXYZ srci( ei->_nodes[0] ), src0( e0->_nodes[0] );
5569       double ui = ( perp0 * ( src0 - srci )) / dot0i;
5570       if ( ui > 0 )
5571       {
5572         ei->_maxLen = Min(  ei->_maxLen, 0.75 * ui / ei->_lenFactor );
5573         if ( ei->_maxLen < ei->_len )
5574         {
5575           ei->InvalidateStep( ei->NbSteps(), _eos, /*restoreLength=*/true  );
5576           ei->SetNewLength( ei->_maxLen, _eos, helper );
5577           ei->Block( data );
5578         }
5579         gp_Pnt pi = srci + ei->_normal * ui;
5580         double u0 = pi.Distance( src0 );
5581         e0->_maxLen = Min(  e0->_maxLen, 0.75 * u0 / e0->_lenFactor );
5582         if ( e0->_maxLen < e0->_len )
5583         {
5584           e0->InvalidateStep( e0->NbSteps(), _eos, /*restoreLength=*/true  );
5585           e0->SetNewLength( e0->_maxLen, _eos, helper );
5586           e0->Block( data );
5587         }
5588       }
5589     }
5590     e0 = ei;
5591   }
5592     
5593   if ( isAnalytic() )
5594     return;
5595
5596   // divide E to have offset segments with low deflection
5597   BRepAdaptor_Curve c3dAdaptor( E );
5598   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5599   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5600   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5601   if ( discret.NbPoints() <= 2 )
5602   {
5603     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5604     return;
5605   }
5606
5607   const double edgeLen = SMESH_Algo::EdgeLength( E );
5608   const double u0      = c3dAdaptor.FirstParameter();
5609   _offPoints.resize( discret.NbPoints() );
5610   for ( size_t i = 0; i < _offPoints.size(); i++ )
5611   {
5612     _offPoints[i]._xyz = discret.Value( i+1 ).XYZ();
5613     // use OffPnt::_len to  TEMPORARY  store normalized param of an offset point
5614     double u = discret.Parameter( i+1 );
5615     _offPoints[i]._len = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / edgeLen;
5616   }
5617
5618   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5619
5620   // set _2edges
5621   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5622   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5623   _2NearEdges tmp2edges;
5624   tmp2edges._edges[1] = _eos._edges[0];
5625   _leOnV[0]._2neibors = & tmp2edges;
5626   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5627   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5628   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5629   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5630   {
5631     // find _LayerEdge's located before and after an offset point
5632     // (_eos._edges[ iLE ] is next after ePrev)
5633     while ( iLE < _eos._edges.size() && _offPoints[i]._len > _leParams[ iLE ] )
5634       ePrev = _eos._edges[ iLE++ ];
5635     eNext = ePrev->_2neibors->_edges[1];
5636
5637     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5638     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5639     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5640     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5641   }
5642
5643   int iLBO = _offPoints.size() - 2; // last but one
5644   _offPoints[iLBO]._2edges._edges[1] = & _leOnV[1];
5645
5646   // {
5647   //   TopoDS_Face face[2]; // FACEs sharing the EDGE
5648   //   PShapeIteratorPtr fIt = helper.GetAncestors( _eos._shape, *helper.GetMesh(), TopAbs_FACE );
5649   //   while ( const TopoDS_Shape* F = fIt->next() )
5650   //   {
5651   //     TGeomID fID = helper.GetMeshDS()->ShapeToIndex( *F );
5652   //     if ( ! data._ignoreFaceIds.count( fID ))
5653   //       face[ !face[0].IsNull() ] = *F;
5654   //   }
5655   //   if ( face[0].IsNull() ) return;
5656   //   if ( face[1].IsNull() ) face[1] = face[0];
5657   // }
5658
5659
5660   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5661
5662   setNormalOnV( 0, data.GetHelper() );
5663   setNormalOnV( 1, data.GetHelper() );
5664   _leOnV[ 0 ]._len = 0;
5665   _leOnV[ 1 ]._len = 0;
5666   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5667   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5668
5669   _iSeg[0] = 0;
5670   _iSeg[1] = _offPoints.size()-2;
5671
5672   // initialize OffPnt::_len
5673   for ( size_t i = 0; i < _offPoints.size(); ++i )
5674     _offPoints[i]._len = 0;
5675
5676   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5677   {
5678     _leOnV[0]._len = leOnV[0]->_len;
5679     _leOnV[1]._len = leOnV[1]->_len;
5680     for ( size_t i = 0; i < _offPoints.size(); i++ )
5681     {
5682       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5683       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5684       const double w0 = _offPoints[i]._2edges._wgt[0];
5685       const double w1 = _offPoints[i]._2edges._wgt[1];
5686       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5687       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5688                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5689       _offPoints[i]._xyz = avgXYZ;
5690       _offPoints[i]._len = avgLen;
5691     }
5692   }
5693 }
5694
5695 //================================================================================
5696 /*!
5697  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5698  */
5699 //================================================================================
5700
5701 void _Smoother1D::setNormalOnV( const bool          is2nd,
5702                                 SMESH_MesherHelper& helper)
5703 {
5704   _LayerEdge*    leOnV = getLEdgeOnV( is2nd );
5705   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5706   TopoDS_Shape       V = helper.GetSubShapeByNode( leOnV->_nodes[0], helper.GetMeshDS() );
5707   gp_XYZ          eDir = getEdgeDir( E, TopoDS::Vertex( V ));
5708   gp_XYZ         cross = leOnV->_normal ^ eDir;
5709   gp_XYZ          norm = eDir ^ cross;
5710   double          size = norm.Modulus();
5711
5712   _leOnV[ is2nd ]._normal = norm / size;
5713 }
5714
5715 //================================================================================
5716 /*!
5717  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5718  */
5719 //================================================================================
5720
5721 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5722                              vector< _LayerEdge* >& edges)
5723 {
5724   map< double, _LayerEdge* > u2edge;
5725   for ( size_t i = 0; i < edges.size(); ++i )
5726     u2edge.insert( u2edge.end(),
5727                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5728
5729   ASSERT( u2edge.size() == edges.size() );
5730   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5731   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5732     edges[i] = u2e->second;
5733
5734   Sort2NeiborsOnEdge( edges );
5735 }
5736
5737 //================================================================================
5738 /*!
5739  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5740  */
5741 //================================================================================
5742
5743 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5744 {
5745   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5746
5747   for ( size_t i = 0; i < edges.size()-1; ++i )
5748     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5749       edges[i]->_2neibors->reverse();
5750
5751   const size_t iLast = edges.size() - 1;
5752   if ( edges.size() > 1 &&
5753        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5754     edges[iLast]->_2neibors->reverse();
5755 }
5756
5757 //================================================================================
5758 /*!
5759  * \brief Return _EdgesOnShape* corresponding to the shape
5760  */
5761 //================================================================================
5762
5763 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5764 {
5765   if ( shapeID < (int)_edgesOnShape.size() &&
5766        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5767     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5768
5769   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5770     if ( _edgesOnShape[i]._shapeID == shapeID )
5771       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5772
5773   return 0;
5774 }
5775
5776 //================================================================================
5777 /*!
5778  * \brief Return _EdgesOnShape* corresponding to the shape
5779  */
5780 //================================================================================
5781
5782 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5783 {
5784   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5785   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5786 }
5787
5788 //================================================================================
5789 /*!
5790  * \brief Prepare data of the _LayerEdge for smoothing on FACE
5791  */
5792 //================================================================================
5793
5794 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5795 {
5796   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5797
5798   set< TGeomID > vertices;
5799   TopoDS_Face F;
5800   if ( eos->ShapeType() == TopAbs_FACE )
5801   {
5802     // check FACE concavity and get concave VERTEXes
5803     F = TopoDS::Face( eos->_shape );
5804     if ( isConcave( F, helper, &vertices ))
5805       _concaveFaces.insert( eos->_shapeID );
5806
5807     // set eos._eosConcaVer
5808     eos->_eosConcaVer.clear();
5809     eos->_eosConcaVer.reserve( vertices.size() );
5810     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5811     {
5812       _EdgesOnShape* eov = GetShapeEdges( *v );
5813       if ( eov && eov->_edges.size() == 1 )
5814       {
5815         eos->_eosConcaVer.push_back( eov );
5816         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5817           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5818       }
5819     }
5820
5821     // SetSmooLen() to _LayerEdge's on FACE
5822     for ( size_t i = 0; i < eos->_edges.size(); ++i )
5823     {
5824       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5825     }
5826     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5827     while ( smIt->more() ) // loop on sub-shapes of the FACE
5828     {
5829       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5830       if ( !eoe ) continue;
5831
5832       vector<_LayerEdge*>& eE = eoe->_edges;
5833       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5834       {
5835         if ( eE[iE]->_cosin <= theMinSmoothCosin )
5836           continue;
5837
5838         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5839         while ( segIt->more() )
5840         {
5841           const SMDS_MeshElement* seg = segIt->next();
5842           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
5843             continue;
5844           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
5845             continue; // not to check a seg twice
5846           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
5847           {
5848             _LayerEdge* eN = eE[iE]->_neibors[iN];
5849             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
5850               continue;
5851             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
5852             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
5853             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
5854             eN->Set( _LayerEdge::NEAR_BOUNDARY );
5855           }
5856         }
5857       }
5858     }
5859   } // if ( eos->ShapeType() == TopAbs_FACE )
5860
5861   for ( size_t i = 0; i < eos->_edges.size(); ++i )
5862   {
5863     eos->_edges[i]->_smooFunction = 0;
5864     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
5865   }
5866   bool isCurved = false;
5867   for ( size_t i = 0; i < eos->_edges.size(); ++i )
5868   {
5869     _LayerEdge* edge = eos->_edges[i];
5870
5871     // get simplices sorted
5872     _Simplex::SortSimplices( edge->_simplices );
5873
5874     // smoothing function
5875     edge->ChooseSmooFunction( vertices, _n2eMap );
5876
5877     // set _curvature
5878     double avgNormProj = 0, avgLen = 0;
5879     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
5880     {
5881       _Simplex& s = edge->_simplices[iS];
5882
5883       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
5884       avgNormProj += edge->_normal * vec;
5885       avgLen      += vec.Modulus();
5886       if ( substituteSrcNodes )
5887       {
5888         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
5889         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
5890       }
5891     }
5892     avgNormProj /= edge->_simplices.size();
5893     avgLen      /= edge->_simplices.size();
5894     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
5895     {
5896       isCurved = true;
5897       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
5898       if ( !fPos )
5899         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
5900           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
5901       if ( fPos )
5902         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
5903     }
5904   }
5905
5906   // prepare for putOnOffsetSurface()
5907   if (( eos->ShapeType() == TopAbs_FACE ) &&
5908       ( isCurved || !eos->_eosConcaVer.empty() ))
5909   {
5910     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
5911     eos->_edgeForOffset = 0;
5912
5913     double maxCosin = -1;
5914     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
5915     {
5916       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
5917       if ( !eoe || eoe->_edges.empty() ) continue;
5918
5919       vector<_LayerEdge*>& eE = eoe->_edges;
5920       _LayerEdge* e = eE[ eE.size() / 2 ];
5921       if ( e->_cosin > maxCosin )
5922       {
5923         eos->_edgeForOffset = e;
5924         maxCosin = e->_cosin;
5925       }
5926     }
5927   }
5928 }
5929
5930 //================================================================================
5931 /*!
5932  * \brief Add faces for smoothing
5933  */
5934 //================================================================================
5935
5936 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
5937                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
5938 {
5939   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
5940   for ( ; eos != eosToSmooth.end(); ++eos )
5941   {
5942     if ( !*eos || (*eos)->_toSmooth ) continue;
5943
5944     (*eos)->_toSmooth = true;
5945
5946     if ( (*eos)->ShapeType() == TopAbs_FACE )
5947     {
5948       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
5949       (*eos)->_toSmooth = true;
5950     }
5951   }
5952
5953   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
5954   if ( edgesNoAnaSmooth )
5955     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
5956     {
5957       if ( (*eos)->_edgeSmoother )
5958         (*eos)->_edgeSmoother->_anaCurve.Nullify();
5959     }
5960 }
5961
5962 //================================================================================
5963 /*!
5964  * \brief Fill data._collisionEdges
5965  */
5966 //================================================================================
5967
5968 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
5969 {
5970   data._collisionEdges.clear();
5971
5972   // set the full thickness of the layers to LEs
5973   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5974   {
5975     _EdgesOnShape& eos = data._edgesOnShape[iS];
5976     if ( eos._edges.empty() ) continue;
5977     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
5978
5979     for ( size_t i = 0; i < eos._edges.size(); ++i )
5980     {
5981       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5982       double maxLen = eos._edges[i]->_maxLen;
5983       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
5984       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
5985       eos._edges[i]->_maxLen = maxLen;
5986     }
5987   }
5988
5989   // make temporary quadrangles got by extrusion of
5990   // mesh edges along _LayerEdge._normal's
5991
5992   vector< const SMDS_MeshElement* > tmpFaces;
5993
5994   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5995   {
5996     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5997     if ( eos.ShapeType() != TopAbs_EDGE )
5998       continue;
5999     if ( eos._edges.empty() )
6000     {
6001       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6002       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6003       while ( smIt->more() )
6004         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6005           if ( eov->_edges.size() == 1 )
6006             edge[ bool( edge[0]) ] = eov->_edges[0];
6007
6008       if ( edge[1] )
6009       {
6010         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6011         tmpFaces.push_back( f );
6012       }
6013     }
6014     for ( size_t i = 0; i < eos._edges.size(); ++i )
6015     {
6016       _LayerEdge* edge = eos._edges[i];
6017       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6018       {
6019         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6020         if ( src2->GetPosition()->GetDim() > 0 &&
6021              src2->GetID() < edge->_nodes[0]->GetID() )
6022           continue; // avoid using same segment twice
6023
6024         // a _LayerEdge containg tgt2
6025         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6026
6027         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6028         tmpFaces.push_back( f );
6029       }
6030     }
6031   }
6032
6033   // Find _LayerEdge's intersecting tmpFaces.
6034
6035   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6036                                                             tmpFaces.end()));
6037   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6038     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6039
6040   double dist1, dist2, segLen, eps;
6041   _CollisionEdges collEdges;
6042   vector< const SMDS_MeshElement* > suspectFaces;
6043   const double angle30 = Cos( 30. * M_PI / 180. );
6044
6045   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6046   {
6047     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6048     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6049       continue;
6050     // find sub-shapes whose VL can influence VL on eos
6051     set< TGeomID > neighborShapes;
6052     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6053     while ( const TopoDS_Shape* face = fIt->next() )
6054     {
6055       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6056       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6057       {
6058         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6059         while ( subIt->more() )
6060           neighborShapes.insert( subIt->next()->GetId() );
6061       }
6062     }
6063     if ( eos.ShapeType() == TopAbs_VERTEX )
6064     {
6065       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6066       while ( const TopoDS_Shape* edge = eIt->next() )
6067         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6068     }
6069     // find intersecting _LayerEdge's
6070     for ( size_t i = 0; i < eos._edges.size(); ++i )
6071     {
6072       _LayerEdge*   edge = eos._edges[i];
6073       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6074       eps     = 0.5 * edge->_len;
6075       segLen *= 1.2;
6076
6077       gp_Vec eSegDir0, eSegDir1;
6078       if ( edge->IsOnEdge() )
6079       {
6080         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6081         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6082         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6083       }
6084       suspectFaces.clear();
6085       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len,
6086                                      SMDSAbs_Face, suspectFaces );
6087       collEdges._intEdges.clear();
6088       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6089       {
6090         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6091         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6092         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6093         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6094         if ( edge->IsOnEdge() ) {
6095           if ( edge->_2neibors->include( f->_le1 ) ||
6096                edge->_2neibors->include( f->_le2 )) continue;
6097         }
6098         else {
6099           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6100               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6101         }
6102         dist1 = dist2 = Precision::Infinite();
6103         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6104           dist1 = Precision::Infinite();
6105         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6106           dist2 = Precision::Infinite();
6107         if (( dist1 > segLen ) && ( dist2 > segLen ))
6108           continue;
6109
6110         if ( edge->IsOnEdge() )
6111         {
6112           // skip perpendicular EDGEs
6113           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6114           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle30 ) ||
6115                               isLessAngle( eSegDir1, fSegDir, angle30 ) ||
6116                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle30 ) ||
6117                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle30 ));
6118           if ( !isParallel )
6119             continue;
6120         }
6121
6122         // either limit inflation of edges or remember them for updating _normal
6123         // double dot = edge->_normal * f->GetDir();
6124         // if ( dot > 0.1 )
6125         {
6126           collEdges._intEdges.push_back( f->_le1 );
6127           collEdges._intEdges.push_back( f->_le2 );
6128         }
6129         // else
6130         // {
6131         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6132         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6133         // }
6134       }
6135
6136       if ( !collEdges._intEdges.empty() )
6137       {
6138         collEdges._edge = edge;
6139         data._collisionEdges.push_back( collEdges );
6140       }
6141     }
6142   }
6143
6144   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6145     delete tmpFaces[i];
6146
6147   // restore the zero thickness
6148   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6149   {
6150     _EdgesOnShape& eos = data._edgesOnShape[iS];
6151     if ( eos._edges.empty() ) continue;
6152     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6153
6154     for ( size_t i = 0; i < eos._edges.size(); ++i )
6155     {
6156       eos._edges[i]->InvalidateStep( 1, eos );
6157       eos._edges[i]->_len = 0;
6158     }
6159   }
6160 }
6161
6162 //================================================================================
6163 /*!
6164  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6165  * _LayerEdge's on neighbor EDGE's
6166  */
6167 //================================================================================
6168
6169 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6170                                      SMESH_MesherHelper& helper,
6171                                      int                 stepNb,
6172                                      double              stepSize)
6173 {
6174   updateNormalsOfC1Vertices( data );
6175
6176   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6177     return false;
6178
6179   // map to store new _normal and _cosin for each intersected edge
6180   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6181   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6182   _LayerEdge zeroEdge;
6183   zeroEdge._normal.SetCoord( 0,0,0 );
6184   zeroEdge._maxLen = Precision::Infinite();
6185   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6186
6187   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6188
6189   double segLen, dist1, dist2;
6190   vector< pair< _LayerEdge*, double > > intEdgesDist;
6191   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6192
6193   for ( int iter = 0; iter < 5; ++iter )
6194   {
6195     edge2newEdge.clear();
6196
6197     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6198     {
6199       _CollisionEdges& ce = data._collisionEdges[iE];
6200       _LayerEdge*   edge1 = ce._edge;
6201       if ( !edge1 || edge1->Is( _LayerEdge::BLOCKED )) continue;
6202       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6203       if ( !eos1 ) continue;
6204
6205       // detect intersections
6206       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6207       double testLen = 1.5 * edge1->_maxLen; //2 + edge1->_len * edge1->_lenFactor;
6208       double     eps = 0.5 * edge1->_len;
6209       intEdgesDist.clear();
6210       double minIntDist = Precision::Infinite();
6211       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6212       {
6213         if ( ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) ||
6214              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6215           continue;
6216         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6217         double fact = ( 1.1 + dot * dot );
6218         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6219         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6220         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6221         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6222         dist1 = dist2 = Precision::Infinite();
6223         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pTgt0, pSrc1, dist1, eps ) &&
6224              !edge1->SegTriaInter( lastSeg, pSrc1, pTgt1, pTgt0, dist2, eps ))
6225           continue;
6226         if (( dist1 > testLen || dist1 < 0 ) &&
6227             ( dist2 > testLen || dist2 < 0 ))
6228           continue;
6229
6230         // choose a closest edge
6231         gp_Pnt intP( lastSeg.Location().XYZ() +
6232                      lastSeg.Direction().XYZ() * ( Min( dist1, dist2 ) + segLen ));
6233         double d1 = intP.SquareDistance( pSrc0 );
6234         double d2 = intP.SquareDistance( pSrc1 );
6235         int iClose = i + ( d2 < d1 );
6236         _LayerEdge* edge2 = ce._intEdges[iClose];
6237         edge2->Unset( _LayerEdge::MARKED );
6238
6239         // choose a closest edge among neighbors
6240         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6241         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6242         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6243         {
6244           _LayerEdge * edgeJ = intEdgesDist[j].first;
6245           if ( edge2->IsNeiborOnEdge( edgeJ ))
6246           {
6247             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6248             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6249           }
6250         }
6251         intEdgesDist.push_back( make_pair( edge2, Min( dist1, dist2 )));
6252         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6253         // {
6254         //   iClose = i + !( d2 < d1 );
6255         //   intEdges.push_back( ce._intEdges[iClose] );
6256         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6257         // }
6258         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist1, minIntDist );
6259         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist2, minIntDist );
6260       }
6261
6262       //ce._edge = 0;
6263
6264       // compute new _normals
6265       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6266       {
6267         _LayerEdge* edge2    = intEdgesDist[i].first;
6268         double       distWgt = edge1->_len / intEdgesDist[i].second;
6269         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6270         edge2->Set( _LayerEdge::MARKED );
6271
6272         // get a new normal
6273         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6274
6275         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6276         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6277         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6278         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6279         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6280         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6281         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6282         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6283         newNormal.Normalize();
6284
6285         // get new cosin
6286         double newCos;
6287         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6288         if ( cos1 < theMinSmoothCosin )
6289         {
6290           newCos = cos2 * sgn1;
6291         }
6292         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6293         {
6294           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6295         }
6296         else
6297         {
6298           newCos = edge1->_cosin;
6299         }
6300
6301         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6302         e2neIt->second._normal += distWgt * newNormal;
6303         e2neIt->second._cosin   = newCos;
6304         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6305         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6306           e2neIt->second._normal += dir2;
6307         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6308         e2neIt->second._normal += distWgt * newNormal;
6309         e2neIt->second._cosin   = edge2->_cosin;
6310         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6311           e2neIt->second._normal += dir1;
6312       }
6313     }
6314
6315     if ( edge2newEdge.empty() )
6316       break; //return true;
6317
6318     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6319
6320     // Update data of edges depending on a new _normal
6321
6322     data.UnmarkEdges();
6323     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6324     {
6325       _LayerEdge*    edge = e2neIt->first;
6326       _LayerEdge& newEdge = e2neIt->second;
6327       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6328
6329       // Check if a new _normal is OK:
6330       newEdge._normal.Normalize();
6331       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6332       {
6333         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6334         {
6335           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6336           edge->_maxLen = newEdge._maxLen;
6337           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6338         }
6339         continue; // the new _normal is bad
6340       }
6341       // the new _normal is OK
6342
6343       // find shapes that need smoothing due to change of _normal
6344       if ( edge->_cosin   < theMinSmoothCosin &&
6345            newEdge._cosin > theMinSmoothCosin )
6346       {
6347         if ( eos->_sWOL.IsNull() )
6348         {
6349           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6350           while ( fIt->more() )
6351             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6352         }
6353         else // edge inflates along a FACE
6354         {
6355           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6356           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6357           while ( const TopoDS_Shape* E = eIt->next() )
6358           {
6359             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6360               continue;
6361             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6362             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6363             if ( angle < M_PI / 2 )
6364               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6365           }
6366         }
6367       }
6368
6369       double len = edge->_len;
6370       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6371       edge->SetNormal( newEdge._normal );
6372       edge->SetCosin( newEdge._cosin );
6373       edge->SetNewLength( len, *eos, helper );
6374       edge->Set( _LayerEdge::MARKED );
6375       edge->Set( _LayerEdge::NORMAL_UPDATED );
6376       edgesNoAnaSmooth.insert( eos );
6377     }
6378
6379     // Update normals and other dependent data of not intersecting _LayerEdge's
6380     // neighboring the intersecting ones
6381
6382     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6383     {
6384       _LayerEdge*   edge1 = e2neIt->first;
6385       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6386       if ( !edge1->Is( _LayerEdge::MARKED ))
6387         continue;
6388
6389       if ( edge1->IsOnEdge() )
6390       {
6391         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6392         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6393         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6394       }
6395
6396       if ( !edge1->_2neibors )
6397         continue;
6398       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6399       {
6400         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6401         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6402           continue; // j-th neighbor is also intersected
6403         _LayerEdge* prevEdge = edge1;
6404         const int nbSteps = 10;
6405         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6406         {
6407           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6408                neighbor->Is( _LayerEdge::MARKED ))
6409             break;
6410           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6411           if ( !eos ) continue;
6412           _LayerEdge* nextEdge = neighbor;
6413           if ( neighbor->_2neibors )
6414           {
6415             int iNext = 0;
6416             nextEdge = neighbor->_2neibors->_edges[iNext];
6417             if ( nextEdge == prevEdge )
6418               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6419           }
6420           double r = double(step-1)/nbSteps;
6421           if ( !nextEdge->_2neibors )
6422             r = Min( r, 0.5 );
6423
6424           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6425           newNorm.Normalize();
6426           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6427             break;
6428
6429           double len = neighbor->_len;
6430           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6431           neighbor->SetNormal( newNorm );
6432           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6433           if ( neighbor->_2neibors )
6434             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6435           neighbor->SetNewLength( len, *eos, helper );
6436           neighbor->Set( _LayerEdge::MARKED );
6437           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6438           edgesNoAnaSmooth.insert( eos );
6439
6440           if ( !neighbor->_2neibors )
6441             break; // neighbor is on VERTEX
6442
6443           // goto the next neighbor
6444           prevEdge = neighbor;
6445           neighbor = nextEdge;
6446         }
6447       }
6448     }
6449     dumpFunctionEnd();
6450   } // iterations
6451
6452   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6453
6454   return true;
6455 }
6456
6457 //================================================================================
6458 /*!
6459  * \brief Check if a new normal is OK
6460  */
6461 //================================================================================
6462
6463 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6464                                      _LayerEdge&   edge,
6465                                      const gp_XYZ& newNormal)
6466 {
6467   // check a min angle between the newNormal and surrounding faces
6468   vector<_Simplex> simplices;
6469   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6470   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6471   double newMinDot = 1, curMinDot = 1;
6472   for ( size_t i = 0; i < simplices.size(); ++i )
6473   {
6474     n1.Set( simplices[i]._nPrev );
6475     n2.Set( simplices[i]._nNext );
6476     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6477     double normLen2 = normFace.SquareModulus();
6478     if ( normLen2 < std::numeric_limits<double>::min() )
6479       continue;
6480     normFace /= Sqrt( normLen2 );
6481     newMinDot = Min( newNormal    * normFace, newMinDot );
6482     curMinDot = Min( edge._normal * normFace, curMinDot );
6483   }
6484   if ( newMinDot < 0.5 )
6485   {
6486     return ( newMinDot >= curMinDot * 0.9 );
6487     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6488     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6489     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6490   }
6491   return true;
6492 }
6493
6494 //================================================================================
6495 /*!
6496  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6497  */
6498 //================================================================================
6499
6500 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6501                                                SMESH_MesherHelper& helper,
6502                                                const int           nbSteps,
6503                                                const double        stepSize )
6504 {
6505   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6506     return true; // no shapes needing smoothing
6507
6508   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6509   {
6510     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6511     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6512          !eos._hyp.ToSmooth() ||
6513          eos.ShapeType() != TopAbs_FACE ||
6514          eos._edges.empty() )
6515       continue;
6516
6517     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6518     if ( !toSmooth ) continue;
6519
6520     for ( size_t i = 0; i < eos._edges.size(); ++i )
6521     {
6522       _LayerEdge* edge = eos._edges[i];
6523       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6524         continue;
6525       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6526         continue;
6527
6528       const gp_XYZ& pPrev = edge->PrevPos();
6529       const gp_XYZ& pLast = edge->_pos.back();
6530       gp_XYZ      stepVec = pLast - pPrev;
6531       double realStepSize = stepVec.Modulus();
6532       if ( realStepSize < numeric_limits<double>::min() )
6533         continue;
6534
6535       edge->_lenFactor = realStepSize / stepSize;
6536       edge->_normal    = stepVec / realStepSize;
6537       edge->Set( _LayerEdge::NORMAL_UPDATED );
6538     }
6539   }
6540
6541   return true;
6542 }
6543
6544 //================================================================================
6545 /*!
6546  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6547  */
6548 //================================================================================
6549
6550 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6551 {
6552   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6553   {
6554     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6555     if ( eov._eosC1.empty() ||
6556          eov.ShapeType() != TopAbs_VERTEX ||
6557          eov._edges.empty() )
6558       continue;
6559
6560     gp_XYZ newNorm   = eov._edges[0]->_normal;
6561     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6562     bool normChanged = false;
6563
6564     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6565     {
6566       _EdgesOnShape*   eoe = eov._eosC1[i];
6567       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6568       const double    eLen = SMESH_Algo::EdgeLength( e );
6569       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6570       if ( oppV.IsSame( eov._shape ))
6571         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6572       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6573       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6574
6575       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6576       if ( curThickOpp + curThick < eLen )
6577         continue;
6578
6579       double wgt = 2. * curThick / eLen;
6580       newNorm += wgt * eovOpp->_edges[0]->_normal;
6581       normChanged = true;
6582     }
6583     if ( normChanged )
6584     {
6585       eov._edges[0]->SetNormal( newNorm.Normalized() );
6586       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6587     }
6588   }
6589 }
6590
6591 //================================================================================
6592 /*!
6593  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6594  */
6595 //================================================================================
6596
6597 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6598                                                   SMESH_MesherHelper& helper,
6599                                                   int                 stepNb )
6600 {
6601   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6602   bool isOK;
6603
6604   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6605   for ( ; id2face != data._convexFaces.end(); ++id2face )
6606   {
6607     _ConvexFace & convFace = (*id2face).second;
6608     if ( convFace._normalsFixed )
6609       continue; // already fixed
6610     if ( convFace.CheckPrisms() )
6611       continue; // nothing to fix
6612
6613     convFace._normalsFixed = true;
6614
6615     BRepAdaptor_Surface surface ( convFace._face, false );
6616     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6617
6618     // check if the convex FACE is of spherical shape
6619
6620     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6621     Bnd_B3d nodesBox;
6622     gp_Pnt  center;
6623
6624     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6625     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6626     {
6627       _EdgesOnShape& eos = *(id2eos->second);
6628       if ( eos.ShapeType() == TopAbs_VERTEX )
6629       {
6630         _LayerEdge* ledge = eos._edges[ 0 ];
6631         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6632           centersBox.Add( center );
6633       }
6634       for ( size_t i = 0; i < eos._edges.size(); ++i )
6635         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6636     }
6637     if ( centersBox.IsVoid() )
6638     {
6639       debugMsg( "Error: centersBox.IsVoid()" );
6640       return false;
6641     }
6642     const bool isSpherical =
6643       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6644
6645     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6646     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6647
6648     if ( isSpherical )
6649     {
6650       // set _LayerEdge::_normal as average of all normals
6651
6652       // WARNING: different density of nodes on EDGEs is not taken into account that
6653       // can lead to an improper new normal
6654
6655       gp_XYZ avgNormal( 0,0,0 );
6656       nbEdges = 0;
6657       id2eos = convFace._subIdToEOS.begin();
6658       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6659       {
6660         _EdgesOnShape& eos = *(id2eos->second);
6661         // set data of _CentralCurveOnEdge
6662         if ( eos.ShapeType() == TopAbs_EDGE )
6663         {
6664           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6665           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6666           if ( !eos._sWOL.IsNull() )
6667             ceCurve._adjFace.Nullify();
6668           else
6669             ceCurve._ledges.insert( ceCurve._ledges.end(),
6670                                     eos._edges.begin(), eos._edges.end());
6671         }
6672         // summarize normals
6673         for ( size_t i = 0; i < eos._edges.size(); ++i )
6674           avgNormal += eos._edges[ i ]->_normal;
6675       }
6676       double normSize = avgNormal.SquareModulus();
6677       if ( normSize < 1e-200 )
6678       {
6679         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6680         return false;
6681       }
6682       avgNormal /= Sqrt( normSize );
6683
6684       // compute new _LayerEdge::_cosin on EDGEs
6685       double avgCosin = 0;
6686       int     nbCosin = 0;
6687       gp_Vec inFaceDir;
6688       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6689       {
6690         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6691         if ( ceCurve._adjFace.IsNull() )
6692           continue;
6693         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6694         {
6695           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6696           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6697           if ( isOK )
6698           {
6699             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6700             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6701             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6702             nbCosin++;
6703           }
6704         }
6705       }
6706       if ( nbCosin > 0 )
6707         avgCosin /= nbCosin;
6708
6709       // set _LayerEdge::_normal = avgNormal
6710       id2eos = convFace._subIdToEOS.begin();
6711       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6712       {
6713         _EdgesOnShape& eos = *(id2eos->second);
6714         if ( eos.ShapeType() != TopAbs_EDGE )
6715           for ( size_t i = 0; i < eos._edges.size(); ++i )
6716             eos._edges[ i ]->_cosin = avgCosin;
6717
6718         for ( size_t i = 0; i < eos._edges.size(); ++i )
6719         {
6720           eos._edges[ i ]->SetNormal( avgNormal );
6721           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6722         }
6723       }
6724     }
6725     else // if ( isSpherical )
6726     {
6727       // We suppose that centers of curvature at all points of the FACE
6728       // lie on some curve, let's call it "central curve". For all _LayerEdge's
6729       // having a common center of curvature we define the same new normal
6730       // as a sum of normals of _LayerEdge's on EDGEs among them.
6731
6732       // get all centers of curvature for each EDGE
6733
6734       helper.SetSubShape( convFace._face );
6735       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6736
6737       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6738       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6739       {
6740         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6741
6742         // set adjacent FACE
6743         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
6744
6745         // get _LayerEdge's of the EDGE
6746         TGeomID edgeID = meshDS->ShapeToIndex( edge );
6747         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
6748         if ( !eos || eos->_edges.empty() )
6749         {
6750           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
6751           for ( int iV = 0; iV < 2; ++iV )
6752           {
6753             TopoDS_Vertex v = helper.IthVertex( iV, edge );
6754             TGeomID     vID = meshDS->ShapeToIndex( v );
6755             eos = data.GetShapeEdges( vID );
6756             vertexLEdges[ iV ] = eos->_edges[ 0 ];
6757           }
6758           edgeLEdge    = &vertexLEdges[0];
6759           edgeLEdgeEnd = edgeLEdge + 2;
6760
6761           centerCurves[ iE ]._adjFace.Nullify();
6762         }
6763         else
6764         {
6765           if ( ! eos->_toSmooth )
6766             data.SortOnEdge( edge, eos->_edges );
6767           edgeLEdge    = &eos->_edges[ 0 ];
6768           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
6769           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
6770           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
6771
6772           if ( ! eos->_sWOL.IsNull() )
6773             centerCurves[ iE ]._adjFace.Nullify();
6774         }
6775
6776         // Get curvature centers
6777
6778         centersBox.Clear();
6779
6780         if ( edgeLEdge[0]->IsOnEdge() &&
6781              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
6782         { // 1st VERTEX
6783           centerCurves[ iE ].Append( center, vertexLEdges[0] );
6784           centersBox.Add( center );
6785         }
6786         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
6787           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
6788           { // EDGE or VERTEXes
6789             centerCurves[ iE ].Append( center, *edgeLEdge );
6790             centersBox.Add( center );
6791           }
6792         if ( edgeLEdge[-1]->IsOnEdge() &&
6793              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
6794         { // 2nd VERTEX
6795           centerCurves[ iE ].Append( center, vertexLEdges[1] );
6796           centersBox.Add( center );
6797         }
6798         centerCurves[ iE ]._isDegenerated =
6799           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6800
6801       } // loop on EDGES of convFace._face to set up data of centerCurves
6802
6803       // Compute new normals for _LayerEdge's on EDGEs
6804
6805       double avgCosin = 0;
6806       int     nbCosin = 0;
6807       gp_Vec inFaceDir;
6808       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
6809       {
6810         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
6811         if ( ceCurve._isDegenerated )
6812           continue;
6813         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
6814         vector< gp_XYZ > &   newNormals = ceCurve._normals;
6815         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
6816         {
6817           isOK = false;
6818           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
6819           {
6820             if ( iE1 != iE2 )
6821               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
6822           }
6823           if ( isOK && !ceCurve._adjFace.IsNull() )
6824           {
6825             // compute new _LayerEdge::_cosin
6826             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
6827             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6828             if ( isOK )
6829             {
6830               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
6831               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
6832               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
6833               nbCosin++;
6834             }
6835           }
6836         }
6837       }
6838       // set new normals to _LayerEdge's of NOT degenerated central curves
6839       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6840       {
6841         if ( centerCurves[ iE ]._isDegenerated )
6842           continue;
6843         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6844         {
6845           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
6846           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6847         }
6848       }
6849       // set new normals to _LayerEdge's of     degenerated central curves
6850       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6851       {
6852         if ( !centerCurves[ iE ]._isDegenerated ||
6853              centerCurves[ iE ]._ledges.size() < 3 )
6854           continue;
6855         // new normal is an average of new normals at VERTEXes that
6856         // was computed on non-degenerated _CentralCurveOnEdge's
6857         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
6858                            centerCurves[ iE ]._ledges.back ()->_normal );
6859         double sz = newNorm.Modulus();
6860         if ( sz < 1e-200 )
6861           continue;
6862         newNorm /= sz;
6863         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
6864                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
6865         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
6866         {
6867           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
6868           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
6869           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
6870         }
6871       }
6872
6873       // Find new normals for _LayerEdge's based on FACE
6874
6875       if ( nbCosin > 0 )
6876         avgCosin /= nbCosin;
6877       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
6878       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
6879       if ( id2eos != convFace._subIdToEOS.end() )
6880       {
6881         int iE = 0;
6882         gp_XYZ newNorm;
6883         _EdgesOnShape& eos = * ( id2eos->second );
6884         for ( size_t i = 0; i < eos._edges.size(); ++i )
6885         {
6886           _LayerEdge* ledge = eos._edges[ i ];
6887           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6888             continue;
6889           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
6890           {
6891             iE = iE % centerCurves.size();
6892             if ( centerCurves[ iE ]._isDegenerated )
6893               continue;
6894             newNorm.SetCoord( 0,0,0 );
6895             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
6896             {
6897               ledge->SetNormal( newNorm );
6898               ledge->_cosin  = avgCosin;
6899               ledge->Set( _LayerEdge::NORMAL_UPDATED );
6900               break;
6901             }
6902           }
6903         }
6904       }
6905
6906     } // not a quasi-spherical FACE
6907
6908     // Update _LayerEdge's data according to a new normal
6909
6910     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
6911                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
6912
6913     id2eos = convFace._subIdToEOS.begin();
6914     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6915     {
6916       _EdgesOnShape& eos = * ( id2eos->second );
6917       for ( size_t i = 0; i < eos._edges.size(); ++i )
6918       {
6919         _LayerEdge* & ledge = eos._edges[ i ];
6920         double len = ledge->_len;
6921         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
6922         ledge->SetCosin( ledge->_cosin );
6923         ledge->SetNewLength( len, eos, helper );
6924       }
6925       if ( eos.ShapeType() != TopAbs_FACE )
6926         for ( size_t i = 0; i < eos._edges.size(); ++i )
6927         {
6928           _LayerEdge* ledge = eos._edges[ i ];
6929           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
6930           {
6931             _LayerEdge* neibor = ledge->_neibors[iN];
6932             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
6933             {
6934               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
6935               neibor->Set( _LayerEdge::MOVED );
6936               neibor->SetSmooLen( neibor->_len );
6937             }
6938           }
6939         }
6940     } // loop on sub-shapes of convFace._face
6941
6942     // Find FACEs adjacent to convFace._face that got necessity to smooth
6943     // as a result of normals modification
6944
6945     set< _EdgesOnShape* > adjFacesToSmooth;
6946     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6947     {
6948       if ( centerCurves[ iE ]._adjFace.IsNull() ||
6949            centerCurves[ iE ]._adjFaceToSmooth )
6950         continue;
6951       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
6952       {
6953         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
6954         {
6955           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
6956           break;
6957         }
6958       }
6959     }
6960     data.AddShapesToSmooth( adjFacesToSmooth );
6961
6962     dumpFunctionEnd();
6963
6964
6965   } // loop on data._convexFaces
6966
6967   return true;
6968 }
6969
6970 //================================================================================
6971 /*!
6972  * \brief Finds a center of curvature of a surface at a _LayerEdge
6973  */
6974 //================================================================================
6975
6976 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
6977                                         BRepLProp_SLProps&  surfProp,
6978                                         SMESH_MesherHelper& helper,
6979                                         gp_Pnt &            center ) const
6980 {
6981   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
6982   surfProp.SetParameters( uv.X(), uv.Y() );
6983   if ( !surfProp.IsCurvatureDefined() )
6984     return false;
6985
6986   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
6987   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
6988   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
6989   if ( surfCurvatureMin > surfCurvatureMax )
6990     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
6991   else
6992     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
6993
6994   return true;
6995 }
6996
6997 //================================================================================
6998 /*!
6999  * \brief Check that prisms are not distorted
7000  */
7001 //================================================================================
7002
7003 bool _ConvexFace::CheckPrisms() const
7004 {
7005   double vol = 0;
7006   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7007   {
7008     const _LayerEdge* edge = _simplexTestEdges[i];
7009     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7010     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7011       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7012       {
7013         debugMsg( "Bad simplex of _simplexTestEdges ("
7014                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7015                   << " "<< edge->_simplices[j]._nPrev->GetID()
7016                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7017         return false;
7018       }
7019   }
7020   return true;
7021 }
7022
7023 //================================================================================
7024 /*!
7025  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7026  *        stored in this _CentralCurveOnEdge.
7027  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7028  *  \param [in,out] newNormal - current normal at this point, to be redefined
7029  *  \return bool - true if succeeded.
7030  */
7031 //================================================================================
7032
7033 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7034 {
7035   if ( this->_isDegenerated )
7036     return false;
7037
7038   // find two centers the given one lies between
7039
7040   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7041   {
7042     double sl2 = 1.001 * _segLength2[ i ];
7043
7044     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7045     if ( d1 > sl2 )
7046       continue;
7047     
7048     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7049     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7050       continue;
7051
7052     d1 = Sqrt( d1 );
7053     d2 = Sqrt( d2 );
7054     double r = d1 / ( d1 + d2 );
7055     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7056                    (      r ) * _ledges[ i+1 ]->_normal );
7057     norm.Normalize();
7058
7059     newNormal += norm;
7060     double sz = newNormal.Modulus();
7061     if ( sz < 1e-200 )
7062       break;
7063     newNormal /= sz;
7064     return true;
7065   }
7066   return false;
7067 }
7068
7069 //================================================================================
7070 /*!
7071  * \brief Set shape members
7072  */
7073 //================================================================================
7074
7075 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7076                                      const _ConvexFace&  convFace,
7077                                      _SolidData&         data,
7078                                      SMESH_MesherHelper& helper)
7079 {
7080   _edge = edge;
7081
7082   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7083   while ( const TopoDS_Shape* F = fIt->next())
7084     if ( !convFace._face.IsSame( *F ))
7085     {
7086       _adjFace = TopoDS::Face( *F );
7087       _adjFaceToSmooth = false;
7088       // _adjFace already in a smoothing queue ?
7089       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7090         _adjFaceToSmooth = eos->_toSmooth;
7091       break;
7092     }
7093 }
7094
7095 //================================================================================
7096 /*!
7097  * \brief Looks for intersection of it's last segment with faces
7098  *  \param distance - returns shortest distance from the last node to intersection
7099  */
7100 //================================================================================
7101
7102 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7103                                    double &                 distance,
7104                                    const double&            epsilon,
7105                                    _EdgesOnShape&           eos,
7106                                    const SMDS_MeshElement** intFace)
7107 {
7108   vector< const SMDS_MeshElement* > suspectFaces;
7109   double segLen;
7110   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7111   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7112
7113   bool segmentIntersected = false;
7114   distance = Precision::Infinite();
7115   int iFace = -1; // intersected face
7116   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7117   {
7118     const SMDS_MeshElement* face = suspectFaces[j];
7119     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7120          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7121       continue; // face sharing _LayerEdge node
7122     const int nbNodes = face->NbCornerNodes();
7123     bool intFound = false;
7124     double dist;
7125     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7126     if ( nbNodes == 3 )
7127     {
7128       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7129     }
7130     else
7131     {
7132       const SMDS_MeshNode* tria[3];
7133       tria[0] = *nIt++;
7134       tria[1] = *nIt++;
7135       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7136       {
7137         tria[2] = *nIt++;
7138         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7139         tria[1] = tria[2];
7140       }
7141     }
7142     if ( intFound )
7143     {
7144       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7145         segmentIntersected = true;
7146       if ( distance > dist )
7147         distance = dist, iFace = j;
7148     }
7149   }
7150   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7151
7152   distance -= segLen;
7153
7154   if ( segmentIntersected )
7155   {
7156 #ifdef __myDEBUG
7157     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7158     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7159     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7160          << ", intersection with face ("
7161          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7162          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7163          << ") distance = " << distance << endl;
7164 #endif
7165   }
7166
7167   return segmentIntersected;
7168 }
7169
7170 //================================================================================
7171 /*!
7172  * \brief Returns size and direction of the last segment
7173  */
7174 //================================================================================
7175
7176 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7177 {
7178   // find two non-coincident positions
7179   gp_XYZ orig = _pos.back();
7180   gp_XYZ vec;
7181   int iPrev = _pos.size() - 2;
7182   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7183   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7184   while ( iPrev >= 0 )
7185   {
7186     vec = orig - _pos[iPrev];
7187     if ( vec.SquareModulus() > tol*tol )
7188       break;
7189     else
7190       iPrev--;
7191   }
7192
7193   // make gp_Ax1
7194   gp_Ax1 segDir;
7195   if ( iPrev < 0 )
7196   {
7197     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7198     segDir.SetDirection( _normal );
7199     segLen = 0;
7200   }
7201   else
7202   {
7203     gp_Pnt pPrev = _pos[ iPrev ];
7204     if ( !eos._sWOL.IsNull() )
7205     {
7206       TopLoc_Location loc;
7207       if ( eos.SWOLType() == TopAbs_EDGE )
7208       {
7209         double f,l;
7210         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7211         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7212       }
7213       else
7214       {
7215         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7216         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7217       }
7218       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7219     }
7220     segDir.SetLocation( pPrev );
7221     segDir.SetDirection( vec );
7222     segLen = vec.Modulus();
7223   }
7224
7225   return segDir;
7226 }
7227
7228 //================================================================================
7229 /*!
7230  * \brief Return the last position of the target node on a FACE. 
7231  *  \param [in] F - the FACE this _LayerEdge is inflated along
7232  *  \return gp_XY - result UV
7233  */
7234 //================================================================================
7235
7236 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7237 {
7238   if ( F.IsSame( eos._sWOL )) // F is my FACE
7239     return gp_XY( _pos.back().X(), _pos.back().Y() );
7240
7241   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7242     return gp_XY( 1e100, 1e100 );
7243
7244   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7245   double f, l, u = _pos.back().X();
7246   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7247   if ( !C2d.IsNull() && f <= u && u <= l )
7248     return C2d->Value( u ).XY();
7249
7250   return gp_XY( 1e100, 1e100 );
7251 }
7252
7253 //================================================================================
7254 /*!
7255  * \brief Test intersection of the last segment with a given triangle
7256  *   using Moller-Trumbore algorithm
7257  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7258  */
7259 //================================================================================
7260
7261 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7262                                const gp_XYZ& vert0,
7263                                const gp_XYZ& vert1,
7264                                const gp_XYZ& vert2,
7265                                double&       t,
7266                                const double& EPSILON) const
7267 {
7268   const gp_Pnt& orig = lastSegment.Location();
7269   const gp_Dir& dir  = lastSegment.Direction();
7270
7271   /* calculate distance from vert0 to ray origin */
7272   gp_XYZ tvec = orig.XYZ() - vert0;
7273
7274   //if ( tvec * dir > EPSILON )
7275     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7276     //return false;
7277
7278   gp_XYZ edge1 = vert1 - vert0;
7279   gp_XYZ edge2 = vert2 - vert0;
7280
7281   /* begin calculating determinant - also used to calculate U parameter */
7282   gp_XYZ pvec = dir.XYZ() ^ edge2;
7283
7284   /* if determinant is near zero, ray lies in plane of triangle */
7285   double det = edge1 * pvec;
7286
7287   const double ANGL_EPSILON = 1e-12;
7288   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7289     return false;
7290
7291   /* calculate U parameter and test bounds */
7292   double u = ( tvec * pvec ) / det;
7293   //if (u < 0.0 || u > 1.0)
7294   if ( u < -EPSILON || u > 1.0 + EPSILON )
7295     return false;
7296
7297   /* prepare to test V parameter */
7298   gp_XYZ qvec = tvec ^ edge1;
7299
7300   /* calculate V parameter and test bounds */
7301   double v = (dir.XYZ() * qvec) / det;
7302   //if ( v < 0.0 || u + v > 1.0 )
7303   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7304     return false;
7305
7306   /* calculate t, ray intersects triangle */
7307   t = (edge2 * qvec) / det;
7308
7309   //return true;
7310   return t > 0.;
7311 }
7312
7313 //================================================================================
7314 /*!
7315  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7316  *        neighbor _LayerEdge's by it's own inflation vector.
7317  *  \param [in] eov - EOS of the VERTEX
7318  *  \param [in] eos - EOS of the FACE
7319  *  \param [in] step - inflation step
7320  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7321  */
7322 //================================================================================
7323
7324 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7325                                    const _EdgesOnShape*    eos,
7326                                    const int               step,
7327                                    vector< _LayerEdge* > & badSmooEdges )
7328 {
7329   // check if any of _neibors is in badSmooEdges
7330   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7331                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7332     return;
7333
7334   // get all edges to move
7335
7336   set< _LayerEdge* > edges;
7337
7338   // find a distance between _LayerEdge on VERTEX and its neighbors
7339   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7340   double dist2 = 0;
7341   for ( size_t i = 0; i < _neibors.size(); ++i )
7342   {
7343     _LayerEdge* nEdge = _neibors[i];
7344     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7345     {
7346       edges.insert( nEdge );
7347       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7348     }
7349   }
7350   // add _LayerEdge's close to curPosV
7351   size_t nbE;
7352   do {
7353     nbE = edges.size();
7354     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7355     {
7356       _LayerEdge* edgeF = *e;
7357       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7358       {
7359         _LayerEdge* nEdge = edgeF->_neibors[i];
7360         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7361              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7362           edges.insert( nEdge );
7363       }
7364     }
7365   }
7366   while ( nbE < edges.size() );
7367
7368   // move the target node of the got edges
7369
7370   gp_XYZ prevPosV = PrevPos();
7371   if ( eov->SWOLType() == TopAbs_EDGE )
7372   {
7373     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7374     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7375   }
7376   else if ( eov->SWOLType() == TopAbs_FACE )
7377   {
7378     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7379     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7380   }
7381
7382   SMDS_FacePosition* fPos;
7383   //double r = 1. - Min( 0.9, step / 10. );
7384   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7385   {
7386     _LayerEdge*       edgeF = *e;
7387     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7388     const gp_XYZ    newPosF = curPosV + prevVF;
7389     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7390     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7391     edgeF->_pos.back() = newPosF;
7392     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7393
7394     // set _curvature to make edgeF updated by putOnOffsetSurface()
7395     if ( !edgeF->_curvature )
7396       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7397       {
7398         edgeF->_curvature = new _Curvature;
7399         edgeF->_curvature->_r = 0;
7400         edgeF->_curvature->_k = 0;
7401         edgeF->_curvature->_h2lenRatio = 0;
7402         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7403       }
7404   }
7405   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7406   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7407   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7408   // {
7409   //   _LayerEdge*      edgeF = *e;
7410   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7411   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7412   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7413   //   edgeF->_pos.back() = newPosF;
7414   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7415   // }
7416
7417   // smooth _LayerEdge's around moved nodes
7418   //size_t nbBadBefore = badSmooEdges.size();
7419   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7420   {
7421     _LayerEdge* edgeF = *e;
7422     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7423       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7424         //&& !edges.count( edgeF->_neibors[j] ))
7425       {
7426         _LayerEdge* edgeFN = edgeF->_neibors[j];
7427         edgeFN->Unset( SMOOTHED );
7428         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7429         // if ( nbBad > 0 )
7430         // {
7431         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7432         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7433         //   int        nbBadAfter = edgeFN->_simplices.size();
7434         //   double vol;
7435         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7436         //   {
7437         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7438         //   }
7439         //   if ( nbBadAfter <= nbBad )
7440         //   {
7441         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7442         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7443         //     edgeF->_pos.back() = newPosF;
7444         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7445         //     nbBad = nbBadAfter;
7446         //   }
7447         // }
7448         if ( nbBad > 0 )
7449           badSmooEdges.push_back( edgeFN );
7450       }
7451   }
7452     // move a bit not smoothed around moved nodes
7453   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7454   //   {
7455   //   _LayerEdge*      edgeF = badSmooEdges[i];
7456   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7457   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7458   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7459   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7460   //   edgeF->_pos.back() = newPosF;
7461   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7462   // }
7463 }
7464
7465 //================================================================================
7466 /*!
7467  * \brief Perform smooth of _LayerEdge's based on EDGE's
7468  *  \retval bool - true if node has been moved
7469  */
7470 //================================================================================
7471
7472 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7473                               const TopoDS_Face&             F,
7474                               SMESH_MesherHelper&            helper)
7475 {
7476   ASSERT( IsOnEdge() );
7477
7478   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7479   SMESH_TNodeXYZ oldPos( tgtNode );
7480   double dist01, distNewOld;
7481   
7482   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7483   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7484   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7485
7486   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7487   double lenDelta = 0;
7488   if ( _curvature )
7489   {
7490     //lenDelta = _curvature->lenDelta( _len );
7491     lenDelta = _curvature->lenDeltaByDist( dist01 );
7492     newPos.ChangeCoord() += _normal * lenDelta;
7493   }
7494
7495   distNewOld = newPos.Distance( oldPos );
7496
7497   if ( F.IsNull() )
7498   {
7499     if ( _2neibors->_plnNorm )
7500     {
7501       // put newPos on the plane defined by source node and _plnNorm
7502       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7503       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7504       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7505     }
7506     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7507     _pos.back() = newPos.XYZ();
7508   }
7509   else
7510   {
7511     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7512     gp_XY uv( Precision::Infinite(), 0 );
7513     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7514     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7515
7516     newPos = surface->Value( uv );
7517     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7518   }
7519
7520   // commented for IPAL0052478
7521   // if ( _curvature && lenDelta < 0 )
7522   // {
7523   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7524   //   _len -= prevPos.Distance( oldPos );
7525   //   _len += prevPos.Distance( newPos );
7526   // }
7527   bool moved = distNewOld > dist01/50;
7528   //if ( moved )
7529   dumpMove( tgtNode ); // debug
7530
7531   return moved;
7532 }
7533
7534 //================================================================================
7535 /*!
7536  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7537  */
7538 //================================================================================
7539
7540 void _LayerEdge::SmoothWoCheck()
7541 {
7542   if ( Is( DIFFICULT ))
7543     return;
7544
7545   bool moved = Is( SMOOTHED );
7546   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7547     moved = _neibors[i]->Is( SMOOTHED );
7548   if ( !moved )
7549     return;
7550
7551   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7552
7553   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7554   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7555   _pos.back() = newPos;
7556
7557   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7558 }
7559
7560 //================================================================================
7561 /*!
7562  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7563  */
7564 //================================================================================
7565
7566 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7567 {
7568   if ( ! Is( NEAR_BOUNDARY ))
7569     return 0;
7570
7571   int nbBad = 0;
7572   double vol;
7573   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7574   {
7575     _LayerEdge* eN = _neibors[iN];
7576     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7577       continue;
7578     if ( needSmooth )
7579       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) || eN->Is( _LayerEdge::NORMAL_UPDATED ));
7580
7581     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7582     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7583     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7584       if ( eN->_nodes.size() > 1 &&
7585            eN->_simplices[i].Includes( _nodes.back() ) &&
7586            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7587       {
7588         ++nbBad;
7589         if ( badNeibors )
7590         {
7591           badNeibors->push_back( eN );
7592           debugMsg("Bad boundary simplex ( "
7593                    << " "<< eN->_nodes[0]->GetID()
7594                    << " "<< eN->_nodes.back()->GetID()
7595                    << " "<< eN->_simplices[i]._nPrev->GetID()
7596                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7597         }
7598         else
7599         {
7600           break;
7601         }
7602       }
7603   }
7604   return nbBad;
7605 }
7606
7607 //================================================================================
7608 /*!
7609  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7610  *  \retval int - nb of bad simplices around this _LayerEdge
7611  */
7612 //================================================================================
7613
7614 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7615 {
7616   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7617     return 0; // shape of simplices not changed
7618   if ( _simplices.size() < 2 )
7619     return 0; // _LayerEdge inflated along EDGE or FACE
7620
7621   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7622     findBest = true;
7623
7624   const gp_XYZ& curPos  = _pos.back();
7625   const gp_XYZ& prevPos = PrevCheckPos();
7626
7627   // quality metrics (orientation) of tetras around _tgtNode
7628   int nbOkBefore = 0;
7629   double vol, minVolBefore = 1e100;
7630   for ( size_t i = 0; i < _simplices.size(); ++i )
7631   {
7632     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7633     minVolBefore = Min( minVolBefore, vol );
7634   }
7635   int nbBad = _simplices.size() - nbOkBefore;
7636
7637   bool bndNeedSmooth = false;
7638   if ( nbBad == 0 )
7639     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7640   if ( nbBad > 0 )
7641     Set( DISTORTED );
7642
7643   // evaluate min angle
7644   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7645   {
7646     size_t nbGoodAngles = _simplices.size();
7647     double angle;
7648     for ( size_t i = 0; i < _simplices.size(); ++i )
7649     {
7650       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7651         --nbGoodAngles;
7652     }
7653     if ( nbGoodAngles == _simplices.size() )
7654     {
7655       Unset( MOVED );
7656       return 0;
7657     }
7658   }
7659   if ( Is( ON_CONCAVE_FACE ))
7660     findBest = true;
7661
7662   if ( step % 2 == 0 )
7663     findBest = false;
7664
7665   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7666   {
7667     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7668       _smooFunction = _funs[ FUN_CENTROIDAL ];
7669     else
7670       _smooFunction = _funs[ FUN_LAPLACIAN ];
7671   }
7672
7673   // compute new position for the last _pos using different _funs
7674   gp_XYZ newPos;
7675   bool moved = false;
7676   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7677   {
7678     if ( iFun < 0 )
7679       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7680     else if ( _funs[ iFun ] == _smooFunction )
7681       continue; // _smooFunction again
7682     else if ( step > 1 )
7683       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7684     else
7685       break; // let "easy" functions improve elements around distorted ones
7686
7687     if ( _curvature )
7688     {
7689       double delta  = _curvature->lenDelta( _len );
7690       if ( delta > 0 )
7691         newPos += _normal * delta;
7692       else
7693       {
7694         double segLen = _normal * ( newPos - prevPos );
7695         if ( segLen + delta > 0 )
7696           newPos += _normal * delta;
7697       }
7698       // double segLenChange = _normal * ( curPos - newPos );
7699       // newPos += 0.5 * _normal * segLenChange;
7700     }
7701
7702     int nbOkAfter = 0;
7703     double minVolAfter = 1e100;
7704     for ( size_t i = 0; i < _simplices.size(); ++i )
7705     {
7706       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7707       minVolAfter = Min( minVolAfter, vol );
7708     }
7709     // get worse?
7710     if ( nbOkAfter < nbOkBefore )
7711       continue;
7712
7713     if (( findBest ) &&
7714         ( nbOkAfter == nbOkBefore ) &&
7715         ( minVolAfter <= minVolBefore ))
7716       continue;
7717
7718     nbBad        = _simplices.size() - nbOkAfter;
7719     minVolBefore = minVolAfter;
7720     nbOkBefore   = nbOkAfter;
7721     moved        = true;
7722
7723     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7724     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7725     _pos.back() = newPos;
7726
7727     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7728                   << (nbBad ? " --BAD" : ""));
7729
7730     if ( iFun > -1 )
7731     {
7732       continue; // look for a better function
7733     }
7734
7735     if ( !findBest )
7736       break;
7737
7738   } // loop on smoothing functions
7739
7740   if ( moved ) // notify _neibors
7741   {
7742     Set( SMOOTHED );
7743     for ( size_t i = 0; i < _neibors.size(); ++i )
7744       if ( !_neibors[i]->Is( MOVED ))
7745       {
7746         _neibors[i]->Set( MOVED );
7747         toSmooth.push_back( _neibors[i] );
7748       }
7749   }
7750
7751   return nbBad;
7752 }
7753
7754 //================================================================================
7755 /*!
7756  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7757  *  \retval int - nb of bad simplices around this _LayerEdge
7758  */
7759 //================================================================================
7760
7761 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
7762 {
7763   if ( !_smooFunction )
7764     return 0; // _LayerEdge inflated along EDGE or FACE
7765   if ( Is( BLOCKED ))
7766     return 0; // not inflated
7767
7768   const gp_XYZ& curPos  = _pos.back();
7769   const gp_XYZ& prevPos = PrevCheckPos();
7770
7771   // quality metrics (orientation) of tetras around _tgtNode
7772   int nbOkBefore = 0;
7773   double vol, minVolBefore = 1e100;
7774   for ( size_t i = 0; i < _simplices.size(); ++i )
7775   {
7776     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7777     minVolBefore = Min( minVolBefore, vol );
7778   }
7779   int nbBad = _simplices.size() - nbOkBefore;
7780
7781   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7782   {
7783     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
7784       _smooFunction = _funs[ FUN_LAPLACIAN ];
7785     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
7786       _smooFunction = _funs[ FUN_CENTROIDAL ];
7787   }
7788
7789   // compute new position for the last _pos using different _funs
7790   gp_XYZ newPos;
7791   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7792   {
7793     if ( iFun < 0 )
7794       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7795     else if ( _funs[ iFun ] == _smooFunction )
7796       continue; // _smooFunction again
7797     else if ( step > 1 )
7798       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7799     else
7800       break; // let "easy" functions improve elements around distorted ones
7801
7802     if ( _curvature )
7803     {
7804       double delta  = _curvature->lenDelta( _len );
7805       if ( delta > 0 )
7806         newPos += _normal * delta;
7807       else
7808       {
7809         double segLen = _normal * ( newPos - prevPos );
7810         if ( segLen + delta > 0 )
7811           newPos += _normal * delta;
7812       }
7813       // double segLenChange = _normal * ( curPos - newPos );
7814       // newPos += 0.5 * _normal * segLenChange;
7815     }
7816
7817     int nbOkAfter = 0;
7818     double minVolAfter = 1e100;
7819     for ( size_t i = 0; i < _simplices.size(); ++i )
7820     {
7821       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7822       minVolAfter = Min( minVolAfter, vol );
7823     }
7824     // get worse?
7825     if ( nbOkAfter < nbOkBefore )
7826       continue;
7827     if (( isConcaveFace || findBest ) &&
7828         ( nbOkAfter == nbOkBefore ) &&
7829         ( minVolAfter <= minVolBefore )
7830         )
7831       continue;
7832
7833     nbBad        = _simplices.size() - nbOkAfter;
7834     minVolBefore = minVolAfter;
7835     nbOkBefore   = nbOkAfter;
7836
7837     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7838     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7839     _pos.back() = newPos;
7840
7841     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
7842                   << ( nbBad ? "--BAD" : ""));
7843
7844     // commented for IPAL0052478
7845     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
7846     // _len += prevPos.Distance(newPos);
7847
7848     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
7849     {
7850       //_smooFunction = _funs[ iFun ];
7851       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
7852       // << "\t nbBad: " << _simplices.size() - nbOkAfter
7853       // << " minVol: " << minVolAfter
7854       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
7855       // << endl;
7856       continue; // look for a better function
7857     }
7858
7859     if ( !findBest )
7860       break;
7861
7862   } // loop on smoothing functions
7863
7864   return nbBad;
7865 }
7866
7867 //================================================================================
7868 /*!
7869  * \brief Chooses a smoothing technic giving a position most close to an initial one.
7870  *        For a correct result, _simplices must contain nodes lying on geometry.
7871  */
7872 //================================================================================
7873
7874 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
7875                                      const TNode2Edge&     n2eMap)
7876 {
7877   if ( _smooFunction ) return;
7878
7879   // use smoothNefPolygon() near concaveVertices
7880   if ( !concaveVertices.empty() )
7881   {
7882     _smooFunction = _funs[ FUN_CENTROIDAL ];
7883
7884     Set( ON_CONCAVE_FACE );
7885
7886     for ( size_t i = 0; i < _simplices.size(); ++i )
7887     {
7888       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
7889       {
7890         _smooFunction = _funs[ FUN_NEFPOLY ];
7891
7892         // set FUN_CENTROIDAL to neighbor edges
7893         for ( i = 0; i < _neibors.size(); ++i )
7894         {
7895           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
7896           {
7897             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
7898           }
7899         }
7900         return;
7901       }
7902     }
7903
7904     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
7905     // // where the nodes are smoothed too far along a sphere thus creating
7906     // // inverted _simplices
7907     // double dist[theNbSmooFuns];
7908     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
7909     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
7910
7911     // double minDist = Precision::Infinite();
7912     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
7913     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
7914     // {
7915     //   gp_Pnt newP = (this->*_funs[i])();
7916     //   dist[i] = p.SquareDistance( newP );
7917     //   if ( dist[i]*coef[i] < minDist )
7918     //   {
7919     //     _smooFunction = _funs[i];
7920     //     minDist = dist[i]*coef[i];
7921     //   }
7922     // }
7923   }
7924   else
7925   {
7926     _smooFunction = _funs[ FUN_LAPLACIAN ];
7927   }
7928   // int minDim = 3;
7929   // for ( size_t i = 0; i < _simplices.size(); ++i )
7930   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
7931   // if ( minDim == 0 )
7932   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
7933   // else if ( minDim == 1 )
7934   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
7935
7936
7937   // int iMin;
7938   // for ( int i = 0; i < FUN_NB; ++i )
7939   // {
7940   //   //cout << dist[i] << " ";
7941   //   if ( _smooFunction == _funs[i] ) {
7942   //     iMin = i;
7943   //     //debugMsg( fNames[i] );
7944   //     break;
7945   //   }
7946   // }
7947   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
7948 }
7949
7950 //================================================================================
7951 /*!
7952  * \brief Returns a name of _SmooFunction
7953  */
7954 //================================================================================
7955
7956 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
7957 {
7958   if ( !fun )
7959     fun = _smooFunction;
7960   for ( int i = 0; i < theNbSmooFuns; ++i )
7961     if ( fun == _funs[i] )
7962       return i;
7963
7964   return theNbSmooFuns;
7965 }
7966
7967 //================================================================================
7968 /*!
7969  * \brief Computes a new node position using Laplacian smoothing
7970  */
7971 //================================================================================
7972
7973 gp_XYZ _LayerEdge::smoothLaplacian()
7974 {
7975   gp_XYZ newPos (0,0,0);
7976   for ( size_t i = 0; i < _simplices.size(); ++i )
7977     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
7978   newPos /= _simplices.size();
7979
7980   return newPos;
7981 }
7982
7983 //================================================================================
7984 /*!
7985  * \brief Computes a new node position using angular-based smoothing
7986  */
7987 //================================================================================
7988
7989 gp_XYZ _LayerEdge::smoothAngular()
7990 {
7991   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
7992   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
7993   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
7994
7995   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
7996   gp_XYZ pN( 0,0,0 );
7997   for ( size_t i = 0; i < _simplices.size(); ++i )
7998   {
7999     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8000     edgeDir.push_back( p - pPrev );
8001     edgeSize.push_back( edgeDir.back().Magnitude() );
8002     if ( edgeSize.back() < numeric_limits<double>::min() )
8003     {
8004       edgeDir.pop_back();
8005       edgeSize.pop_back();
8006     }
8007     else
8008     {
8009       edgeDir.back() /= edgeSize.back();
8010       points.push_back( p );
8011       pN += p;
8012     }
8013     pPrev = p;
8014   }
8015   edgeDir.push_back ( edgeDir[0] );
8016   edgeSize.push_back( edgeSize[0] );
8017   pN /= points.size();
8018
8019   gp_XYZ newPos(0,0,0);
8020   double sumSize = 0;
8021   for ( size_t i = 0; i < points.size(); ++i )
8022   {
8023     gp_Vec toN    = pN - points[i];
8024     double toNLen = toN.Magnitude();
8025     if ( toNLen < numeric_limits<double>::min() )
8026     {
8027       newPos += pN;
8028       continue;
8029     }
8030     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8031     double bisecLen = bisec.SquareMagnitude();
8032     if ( bisecLen < numeric_limits<double>::min() )
8033     {
8034       gp_Vec norm = edgeDir[i] ^ toN;
8035       bisec = norm ^ edgeDir[i];
8036       bisecLen = bisec.SquareMagnitude();
8037     }
8038     bisecLen = Sqrt( bisecLen );
8039     bisec /= bisecLen;
8040
8041 #if 1
8042     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8043     sumSize += bisecLen;
8044 #else
8045     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8046     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8047 #endif
8048     newPos += pNew;
8049   }
8050   newPos /= sumSize;
8051
8052   // project newPos to an average plane
8053
8054   gp_XYZ norm(0,0,0); // plane normal
8055   points.push_back( points[0] );
8056   for ( size_t i = 1; i < points.size(); ++i )
8057   {
8058     gp_XYZ vec1 = points[ i-1 ] - pN;
8059     gp_XYZ vec2 = points[ i   ] - pN;
8060     gp_XYZ cross = vec1 ^ vec2;
8061     try {
8062       cross.Normalize();
8063       if ( cross * norm < numeric_limits<double>::min() )
8064         norm += cross.Reversed();
8065       else
8066         norm += cross;
8067     }
8068     catch (Standard_Failure) { // if |cross| == 0.
8069     }
8070   }
8071   gp_XYZ vec = newPos - pN;
8072   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8073   newPos     = newPos - r * norm;
8074
8075   return newPos;
8076 }
8077
8078 //================================================================================
8079 /*!
8080  * \brief Computes a new node position using weigthed node positions
8081  */
8082 //================================================================================
8083
8084 gp_XYZ _LayerEdge::smoothLengthWeighted()
8085 {
8086   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8087   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8088
8089   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8090   for ( size_t i = 0; i < _simplices.size(); ++i )
8091   {
8092     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8093     edgeSize.push_back( ( p - pPrev ).Modulus() );
8094     if ( edgeSize.back() < numeric_limits<double>::min() )
8095     {
8096       edgeSize.pop_back();
8097     }
8098     else
8099     {
8100       points.push_back( p );
8101     }
8102     pPrev = p;
8103   }
8104   edgeSize.push_back( edgeSize[0] );
8105
8106   gp_XYZ newPos(0,0,0);
8107   double sumSize = 0;
8108   for ( size_t i = 0; i < points.size(); ++i )
8109   {
8110     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8111     sumSize += edgeSize[i] + edgeSize[i+1];
8112   }
8113   newPos /= sumSize;
8114   return newPos;
8115 }
8116
8117 //================================================================================
8118 /*!
8119  * \brief Computes a new node position using angular-based smoothing
8120  */
8121 //================================================================================
8122
8123 gp_XYZ _LayerEdge::smoothCentroidal()
8124 {
8125   gp_XYZ newPos(0,0,0);
8126   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8127   double sumSize = 0;
8128   for ( size_t i = 0; i < _simplices.size(); ++i )
8129   {
8130     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8131     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8132     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8133     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8134
8135     sumSize += size;
8136     newPos += gc * size;
8137   }
8138   newPos /= sumSize;
8139
8140   return newPos;
8141 }
8142
8143 //================================================================================
8144 /*!
8145  * \brief Computes a new node position located inside a Nef polygon
8146  */
8147 //================================================================================
8148
8149 gp_XYZ _LayerEdge::smoothNefPolygon()
8150 #ifdef OLD_NEF_POLYGON
8151 {
8152   gp_XYZ newPos(0,0,0);
8153
8154   // get a plane to seach a solution on
8155
8156   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8157   size_t i;
8158   const double tol = numeric_limits<double>::min();
8159   gp_XYZ center(0,0,0);
8160   for ( i = 0; i < _simplices.size(); ++i )
8161   {
8162     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8163                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8164     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8165   }
8166   vecs.back() = vecs[0];
8167   center /= _simplices.size();
8168
8169   gp_XYZ zAxis(0,0,0);
8170   for ( i = 0; i < _simplices.size(); ++i )
8171     zAxis += vecs[i] ^ vecs[i+1];
8172
8173   gp_XYZ yAxis;
8174   for ( i = 0; i < _simplices.size(); ++i )
8175   {
8176     yAxis = vecs[i];
8177     if ( yAxis.SquareModulus() > tol )
8178       break;
8179   }
8180   gp_XYZ xAxis = yAxis ^ zAxis;
8181   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8182   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8183   //                             p0.Distance( _simplices[2]._nPrev ));
8184   // gp_XYZ center = smoothLaplacian();
8185   // gp_XYZ xAxis, yAxis, zAxis;
8186   // for ( i = 0; i < _simplices.size(); ++i )
8187   // {
8188   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8189   //   if ( xAxis.SquareModulus() > tol*tol )
8190   //     break;
8191   // }
8192   // for ( i = 1; i < _simplices.size(); ++i )
8193   // {
8194   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8195   //   zAxis = xAxis ^ yAxis;
8196   //   if ( zAxis.SquareModulus() > tol*tol )
8197   //     break;
8198   // }
8199   // if ( i == _simplices.size() ) return newPos;
8200
8201   yAxis = zAxis ^ xAxis;
8202   xAxis /= xAxis.Modulus();
8203   yAxis /= yAxis.Modulus();
8204
8205   // get half-planes of _simplices
8206
8207   vector< _halfPlane > halfPlns( _simplices.size() );
8208   int nbHP = 0;
8209   for ( size_t i = 0; i < _simplices.size(); ++i )
8210   {
8211     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8212     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8213     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8214     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8215     gp_XY  vec12 = p2 - p1;
8216     double dist12 = vec12.Modulus();
8217     if ( dist12 < tol )
8218       continue;
8219     vec12 /= dist12;
8220     halfPlns[ nbHP ]._pos = p1;
8221     halfPlns[ nbHP ]._dir = vec12;
8222     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8223     ++nbHP;
8224   }
8225
8226   // intersect boundaries of half-planes, define state of intersection points
8227   // in relation to all half-planes and calculate internal point of a 2D polygon
8228
8229   double sumLen = 0;
8230   gp_XY newPos2D (0,0);
8231
8232   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8233   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8234   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8235
8236   vector< vector< TIntPntState > > allIntPnts( nbHP );
8237   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8238   {
8239     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8240     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8241
8242     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8243     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8244
8245     int nbNotOut = 0;
8246     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8247
8248     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8249     {
8250       if ( iHP1 == iHP2 ) continue;
8251
8252       TIntPntState & ips1 = intPnts1[ iHP2 ];
8253       if ( ips1.second == UNDEF )
8254       {
8255         // find an intersection point of boundaries of iHP1 and iHP2
8256
8257         if ( iHP2 == iPrev ) // intersection with neighbors is known
8258           ips1.first = halfPlns[ iHP1 ]._pos;
8259         else if ( iHP2 == iNext )
8260           ips1.first = halfPlns[ iHP2 ]._pos;
8261         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8262           ips1.second = NO_INT;
8263
8264         // classify the found intersection point
8265         if ( ips1.second != NO_INT )
8266         {
8267           ips1.second = NOT_OUT;
8268           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8269             if ( i != iHP1 && i != iHP2 &&
8270                  halfPlns[ i ].IsOut( ips1.first, tol ))
8271               ips1.second = IS_OUT;
8272         }
8273         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8274         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8275         TIntPntState & ips2 = intPnts2[ iHP1 ];
8276         ips2 = ips1;
8277       }
8278       if ( ips1.second == NOT_OUT )
8279       {
8280         ++nbNotOut;
8281         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8282       }
8283     }
8284
8285     // find a NOT_OUT segment of boundary which is located between
8286     // two NOT_OUT int points
8287
8288     if ( nbNotOut < 2 )
8289       continue; // no such a segment
8290
8291     if ( nbNotOut > 2 )
8292     {
8293       // sort points along the boundary
8294       map< double, TIntPntState* > ipsByParam;
8295       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8296       {
8297         TIntPntState & ips1 = intPnts1[ iHP2 ];
8298         if ( ips1.second != NO_INT )
8299         {
8300           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8301           double param = op * halfPlns[ iHP1 ]._dir;
8302           ipsByParam.insert( make_pair( param, & ips1 ));
8303         }
8304       }
8305       // look for two neighboring NOT_OUT points
8306       nbNotOut = 0;
8307       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8308       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8309       {
8310         TIntPntState & ips1 = *(u2ips->second);
8311         if ( ips1.second == NOT_OUT )
8312           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8313         else if ( nbNotOut >= 2 )
8314           break;
8315         else
8316           nbNotOut = 0;
8317       }
8318     }
8319
8320     if ( nbNotOut >= 2 )
8321     {
8322       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8323       sumLen += len;
8324
8325       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8326     }
8327   }
8328
8329   if ( sumLen > 0 )
8330   {
8331     newPos2D /= sumLen;
8332     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8333   }
8334   else
8335   {
8336     newPos = center;
8337   }
8338
8339   return newPos;
8340 }
8341 #else // OLD_NEF_POLYGON
8342 { ////////////////////////////////// NEW
8343   gp_XYZ newPos(0,0,0);
8344
8345   // get a plane to seach a solution on
8346
8347   size_t i;
8348   gp_XYZ center(0,0,0);
8349   for ( i = 0; i < _simplices.size(); ++i )
8350     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8351   center /= _simplices.size();
8352
8353   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8354   for ( i = 0; i < _simplices.size(); ++i )
8355     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8356   vecs.back() = vecs[0];
8357
8358   const double tol = numeric_limits<double>::min();
8359   gp_XYZ zAxis(0,0,0);
8360   for ( i = 0; i < _simplices.size(); ++i )
8361   {
8362     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8363     try {
8364       cross.Normalize();
8365       if ( cross * zAxis < tol )
8366         zAxis += cross.Reversed();
8367       else
8368         zAxis += cross;
8369     }
8370     catch (Standard_Failure) { // if |cross| == 0.
8371     }
8372   }
8373
8374   gp_XYZ yAxis;
8375   for ( i = 0; i < _simplices.size(); ++i )
8376   {
8377     yAxis = vecs[i];
8378     if ( yAxis.SquareModulus() > tol )
8379       break;
8380   }
8381   gp_XYZ xAxis = yAxis ^ zAxis;
8382   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8383   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8384   //                             p0.Distance( _simplices[2]._nPrev ));
8385   // gp_XYZ center = smoothLaplacian();
8386   // gp_XYZ xAxis, yAxis, zAxis;
8387   // for ( i = 0; i < _simplices.size(); ++i )
8388   // {
8389   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8390   //   if ( xAxis.SquareModulus() > tol*tol )
8391   //     break;
8392   // }
8393   // for ( i = 1; i < _simplices.size(); ++i )
8394   // {
8395   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8396   //   zAxis = xAxis ^ yAxis;
8397   //   if ( zAxis.SquareModulus() > tol*tol )
8398   //     break;
8399   // }
8400   // if ( i == _simplices.size() ) return newPos;
8401
8402   yAxis = zAxis ^ xAxis;
8403   xAxis /= xAxis.Modulus();
8404   yAxis /= yAxis.Modulus();
8405
8406   // get half-planes of _simplices
8407
8408   vector< _halfPlane > halfPlns( _simplices.size() );
8409   int nbHP = 0;
8410   for ( size_t i = 0; i < _simplices.size(); ++i )
8411   {
8412     const gp_XYZ& OP1 = vecs[ i   ];
8413     const gp_XYZ& OP2 = vecs[ i+1 ];
8414     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8415     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8416     gp_XY  vec12 = p2 - p1;
8417     double dist12 = vec12.Modulus();
8418     if ( dist12 < tol )
8419       continue;
8420     vec12 /= dist12;
8421     halfPlns[ nbHP ]._pos = p1;
8422     halfPlns[ nbHP ]._dir = vec12;
8423     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8424     ++nbHP;
8425   }
8426
8427   // intersect boundaries of half-planes, define state of intersection points
8428   // in relation to all half-planes and calculate internal point of a 2D polygon
8429
8430   double sumLen = 0;
8431   gp_XY newPos2D (0,0);
8432
8433   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8434   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8435   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8436
8437   vector< vector< TIntPntState > > allIntPnts( nbHP );
8438   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8439   {
8440     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8441     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8442
8443     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8444     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8445
8446     int nbNotOut = 0;
8447     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8448
8449     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8450     {
8451       if ( iHP1 == iHP2 ) continue;
8452
8453       TIntPntState & ips1 = intPnts1[ iHP2 ];
8454       if ( ips1.second == UNDEF )
8455       {
8456         // find an intersection point of boundaries of iHP1 and iHP2
8457
8458         if ( iHP2 == iPrev ) // intersection with neighbors is known
8459           ips1.first = halfPlns[ iHP1 ]._pos;
8460         else if ( iHP2 == iNext )
8461           ips1.first = halfPlns[ iHP2 ]._pos;
8462         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8463           ips1.second = NO_INT;
8464
8465         // classify the found intersection point
8466         if ( ips1.second != NO_INT )
8467         {
8468           ips1.second = NOT_OUT;
8469           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8470             if ( i != iHP1 && i != iHP2 &&
8471                  halfPlns[ i ].IsOut( ips1.first, tol ))
8472               ips1.second = IS_OUT;
8473         }
8474         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8475         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8476         TIntPntState & ips2 = intPnts2[ iHP1 ];
8477         ips2 = ips1;
8478       }
8479       if ( ips1.second == NOT_OUT )
8480       {
8481         ++nbNotOut;
8482         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8483       }
8484     }
8485
8486     // find a NOT_OUT segment of boundary which is located between
8487     // two NOT_OUT int points
8488
8489     if ( nbNotOut < 2 )
8490       continue; // no such a segment
8491
8492     if ( nbNotOut > 2 )
8493     {
8494       // sort points along the boundary
8495       map< double, TIntPntState* > ipsByParam;
8496       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8497       {
8498         TIntPntState & ips1 = intPnts1[ iHP2 ];
8499         if ( ips1.second != NO_INT )
8500         {
8501           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8502           double param = op * halfPlns[ iHP1 ]._dir;
8503           ipsByParam.insert( make_pair( param, & ips1 ));
8504         }
8505       }
8506       // look for two neighboring NOT_OUT points
8507       nbNotOut = 0;
8508       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8509       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8510       {
8511         TIntPntState & ips1 = *(u2ips->second);
8512         if ( ips1.second == NOT_OUT )
8513           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8514         else if ( nbNotOut >= 2 )
8515           break;
8516         else
8517           nbNotOut = 0;
8518       }
8519     }
8520
8521     if ( nbNotOut >= 2 )
8522     {
8523       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8524       sumLen += len;
8525
8526       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8527     }
8528   }
8529
8530   if ( sumLen > 0 )
8531   {
8532     newPos2D /= sumLen;
8533     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8534   }
8535   else
8536   {
8537     newPos = center;
8538   }
8539
8540   return newPos;
8541 }
8542 #endif // OLD_NEF_POLYGON
8543
8544 //================================================================================
8545 /*!
8546  * \brief Add a new segment to _LayerEdge during inflation
8547  */
8548 //================================================================================
8549
8550 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8551 {
8552   if ( Is( BLOCKED ))
8553     return;
8554
8555   if ( len > _maxLen )
8556   {
8557     len = _maxLen;
8558     Block( eos.GetData() );
8559   }
8560   const double lenDelta = len - _len;
8561   if ( lenDelta < len * 1e-3  )
8562   {
8563     Block( eos.GetData() );
8564     return;
8565   }
8566
8567   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8568   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8569   gp_XYZ newXYZ;
8570   if ( eos._hyp.IsOffsetMethod() )
8571   {
8572     newXYZ = oldXYZ;
8573     gp_Vec faceNorm;
8574     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8575     while ( faceIt->more() )
8576     {
8577       const SMDS_MeshElement* face = faceIt->next();
8578       if ( !eos.GetNormal( face, faceNorm ))
8579         continue;
8580
8581       // translate plane of a face
8582       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8583
8584       // find point of intersection of the face plane located at baryCenter
8585       // and _normal located at newXYZ
8586       double d    = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8587       double dot  = ( faceNorm.XYZ() * _normal );
8588       if ( dot < std::numeric_limits<double>::min() )
8589         dot = lenDelta * 1e-3;
8590       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8591       newXYZ += step * _normal;
8592     }
8593   }
8594   else
8595   {
8596     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8597   }
8598
8599   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8600   _pos.push_back( newXYZ );
8601
8602   if ( !eos._sWOL.IsNull() )
8603   {
8604     double distXYZ[4];
8605     bool uvOK = false;
8606     if ( eos.SWOLType() == TopAbs_EDGE )
8607     {
8608       double u = Precision::Infinite(); // to force projection w/o distance check
8609       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8610                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8611       _pos.back().SetCoord( u, 0, 0 );
8612       if ( _nodes.size() > 1 && uvOK )
8613       {
8614         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8615         pos->SetUParameter( u );
8616       }
8617     }
8618     else //  TopAbs_FACE
8619     {
8620       gp_XY uv( Precision::Infinite(), 0 );
8621       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8622                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8623       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8624       if ( _nodes.size() > 1 && uvOK )
8625       {
8626         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8627         pos->SetUParameter( uv.X() );
8628         pos->SetVParameter( uv.Y() );
8629       }
8630     }
8631     if ( uvOK )
8632     {
8633       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8634     }
8635     else
8636     {
8637       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8638       _pos.pop_back();
8639       Block( eos.GetData() );
8640       return;
8641     }
8642   }
8643
8644   _len = len;
8645
8646   // notify _neibors
8647   if ( eos.ShapeType() != TopAbs_FACE )
8648   {
8649     for ( size_t i = 0; i < _neibors.size(); ++i )
8650       //if (  _len > _neibors[i]->GetSmooLen() )
8651         _neibors[i]->Set( MOVED );
8652
8653     Set( MOVED );
8654   }
8655   dumpMove( n ); //debug
8656 }
8657
8658 //================================================================================
8659 /*!
8660  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8661  */
8662 //================================================================================
8663
8664 void _LayerEdge::Block( _SolidData& data )
8665 {
8666   if ( Is( BLOCKED )) return;
8667   Set( BLOCKED );
8668
8669   _maxLen = _len;
8670   std::queue<_LayerEdge*> queue;
8671   queue.push( this );
8672
8673   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8674   while ( !queue.empty() )
8675   {
8676     _LayerEdge* edge = queue.front(); queue.pop();
8677     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8678     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8679     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8680     {
8681       _LayerEdge* neibor = edge->_neibors[iN];
8682       if ( neibor->Is( BLOCKED ) ||
8683            neibor->_maxLen < edge->_maxLen )
8684         continue;
8685       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8686       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8687       double minDist = pSrc.SquareDistance( pSrcN );
8688       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
8689       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
8690       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
8691       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8692       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
8693       {
8694         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
8695       }
8696       if ( neibor->_maxLen > newMaxLen )
8697       {
8698         neibor->_maxLen = newMaxLen;
8699         if ( neibor->_maxLen < neibor->_len )
8700         {
8701           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8702           while ( neibor->_len > neibor->_maxLen &&
8703                   neibor->NbSteps() > 1 )
8704             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8705           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8706         }
8707         queue.push( neibor );
8708       }
8709     }
8710   }
8711 }
8712
8713 //================================================================================
8714 /*!
8715  * \brief Remove last inflation step
8716  */
8717 //================================================================================
8718
8719 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
8720 {
8721   if ( _pos.size() > curStep && _nodes.size() > 1 )
8722   {
8723     _pos.resize( curStep );
8724
8725     gp_Pnt      nXYZ = _pos.back();
8726     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8727     SMESH_TNodeXYZ curXYZ( n );
8728     if ( !eos._sWOL.IsNull() )
8729     {
8730       TopLoc_Location loc;
8731       if ( eos.SWOLType() == TopAbs_EDGE )
8732       {
8733         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8734         pos->SetUParameter( nXYZ.X() );
8735         double f,l;
8736         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8737         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
8738       }
8739       else
8740       {
8741         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8742         pos->SetUParameter( nXYZ.X() );
8743         pos->SetVParameter( nXYZ.Y() );
8744         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
8745         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
8746       }
8747     }
8748     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
8749     dumpMove( n );
8750
8751     if ( restoreLength )
8752     {
8753       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
8754     }
8755   }
8756 }
8757
8758 //================================================================================
8759 /*!
8760  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
8761  */
8762 //================================================================================
8763
8764 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
8765 {
8766   //return;
8767   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
8768     return;
8769
8770   // find the 1st smoothed _pos
8771   int iSmoothed = 0;
8772   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
8773   {
8774     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
8775     if ( normDist > tol * tol )
8776       iSmoothed = i;
8777   }
8778   if ( !iSmoothed ) return;
8779
8780   if ( 1 || Is( DISTORTED ))
8781   {
8782     // if ( segLen[ iSmoothed ] / segLen.back() < 0.5 )
8783     //   return;
8784     gp_XYZ normal = _normal;
8785     if ( Is( NORMAL_UPDATED ))
8786       for ( size_t i = 1; i < _pos.size(); ++i )
8787       {
8788         normal = _pos[i] - _pos[0];
8789         double size = normal.Modulus();
8790         if ( size > RealSmall() )
8791         {
8792           normal /= size;
8793           break;
8794         }
8795       }
8796     const double r = 0.2;
8797     for ( int iter = 0; iter < 3; ++iter )
8798     {
8799       double minDot = 1;
8800       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
8801       {
8802         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
8803         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
8804         _pos[i] = newPos;
8805         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
8806         double newLen = ( 1-r ) * midLen + r * segLen[i];
8807         const_cast< double& >( segLen[i] ) = newLen;
8808         // check angle between normal and (_pos[i+1], _pos[i] )
8809         gp_XYZ posDir = _pos[i+1] - _pos[i];
8810         double size   = posDir.Modulus();
8811         if ( size > RealSmall() )
8812           minDot = Min( minDot, ( normal * posDir ) / size );
8813       }
8814       if ( minDot > 0.5 )
8815         break;
8816     }
8817   }
8818   // else
8819   // {
8820   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
8821   //   {
8822   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
8823   //       continue;
8824
8825   //     double     wgt = segLen[i] / segLen.back();
8826   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
8827   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
8828   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
8829   //     _pos[i] = newPos;
8830   //   }
8831   // }
8832 }
8833
8834 //================================================================================
8835 /*!
8836  * \brief Create layers of prisms
8837  */
8838 //================================================================================
8839
8840 bool _ViscousBuilder::refine(_SolidData& data)
8841 {
8842   SMESH_MesherHelper& helper = data.GetHelper();
8843   helper.SetElementsOnShape(false);
8844
8845   Handle(Geom_Curve) curve;
8846   Handle(ShapeAnalysis_Surface) surface;
8847   TopoDS_Edge geomEdge;
8848   TopoDS_Face geomFace;
8849   TopLoc_Location loc;
8850   double f,l, u = 0;
8851   gp_XY uv;
8852   vector< gp_XYZ > pos3D;
8853   bool isOnEdge;
8854   TGeomID prevBaseId = -1;
8855   TNode2Edge* n2eMap = 0;
8856   TNode2Edge::iterator n2e;
8857
8858   // Create intermediate nodes on each _LayerEdge
8859
8860   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
8861   {
8862     _EdgesOnShape& eos = data._edgesOnShape[iS];
8863     if ( eos._edges.empty() ) continue;
8864
8865     if ( eos._edges[0]->_nodes.size() < 2 )
8866       continue; // on _noShrinkShapes
8867
8868     // get data of a shrink shape
8869     isOnEdge = false;
8870     geomEdge.Nullify(); geomFace.Nullify();
8871     curve.Nullify(); surface.Nullify();
8872     if ( !eos._sWOL.IsNull() )
8873     {
8874       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
8875       if ( isOnEdge )
8876       {
8877         geomEdge = TopoDS::Edge( eos._sWOL );
8878         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
8879       }
8880       else
8881       {
8882         geomFace = TopoDS::Face( eos._sWOL );
8883         surface  = helper.GetSurface( geomFace );
8884       }
8885     }
8886     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
8887     {
8888       geomFace = TopoDS::Face( eos._shape );
8889       surface  = helper.GetSurface( geomFace );
8890       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
8891       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
8892       {
8893         eos._eosC1[ i ]->_toSmooth = true;
8894         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
8895           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
8896       }
8897     }
8898
8899     vector< double > segLen;
8900     for ( size_t i = 0; i < eos._edges.size(); ++i )
8901     {
8902       _LayerEdge& edge = *eos._edges[i];
8903       if ( edge._pos.size() < 2 )
8904         continue;
8905
8906       // get accumulated length of segments
8907       segLen.resize( edge._pos.size() );
8908       segLen[0] = 0.0;
8909       if ( eos._sWOL.IsNull() )
8910       {
8911         bool useNormal = true;
8912         bool   usePos  = false;
8913         bool smoothed  = false;
8914         const double preci = 0.1 * edge._len;
8915         if ( eos._toSmooth )
8916         {
8917           gp_Pnt tgtExpected = edge._pos[0] + edge._normal * edge._len;
8918           smoothed = tgtExpected.SquareDistance( edge._pos.back() ) > preci * preci;
8919         }
8920         if ( smoothed )
8921         {
8922           if ( !surface.IsNull() &&
8923                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
8924           {
8925             useNormal = usePos = false;
8926             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
8927             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
8928             {
8929               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
8930               if ( surface->Gap() < 2. * edge._len )
8931                 segLen[j] = surface->Gap();
8932               else
8933                 useNormal = true;
8934             }
8935           }
8936         }
8937         else
8938         {
8939           useNormal = usePos = false;
8940           edge._pos[1] = edge._pos.back();
8941           edge._pos.resize( 2 );
8942           segLen.resize( 2 );
8943           segLen[ 1 ] = edge._len;
8944         }
8945         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
8946         {
8947           useNormal = usePos = false;
8948           _LayerEdge tmpEdge; // get original _normal
8949           tmpEdge._nodes.push_back( edge._nodes[0] );
8950           if ( !setEdgeData( tmpEdge, eos, helper, data ))
8951             usePos = true;
8952           else
8953             for ( size_t j = 1; j < edge._pos.size(); ++j )
8954               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
8955         }
8956         if ( useNormal )
8957         {
8958           for ( size_t j = 1; j < edge._pos.size(); ++j )
8959             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
8960         }
8961         if ( usePos )
8962         {
8963           for ( size_t j = 1; j < edge._pos.size(); ++j )
8964             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
8965         }
8966         else
8967         {
8968           bool swapped = ( edge._pos.size() > 2 );
8969           while ( swapped )
8970           {
8971             swapped = false;
8972             for ( size_t j = 1; j < edge._pos.size(); ++j )
8973               if ( segLen[j] > segLen.back() )
8974               {
8975                 segLen.erase( segLen.begin() + j );
8976                 edge._pos.erase( edge._pos.begin() + j );
8977               }
8978               else if ( segLen[j] < segLen[j-1] )
8979               {
8980                 std::swap( segLen[j], segLen[j-1] );
8981                 std::swap( edge._pos[j], edge._pos[j-1] );
8982                 swapped = true;
8983               }
8984           }
8985         }
8986         // smooth a path formed by edge._pos
8987         if (( smoothed ) /*&&
8988             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
8989           edge.SmoothPos( segLen, preci );
8990       }
8991       else if ( eos._isRegularSWOL ) // usual SWOL
8992       {
8993         for ( size_t j = 1; j < edge._pos.size(); ++j )
8994           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
8995       }
8996       else if ( !surface.IsNull() ) // SWOL surface with singularities
8997       {
8998         pos3D.resize( edge._pos.size() );
8999         for ( size_t j = 0; j < edge._pos.size(); ++j )
9000           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9001
9002         for ( size_t j = 1; j < edge._pos.size(); ++j )
9003           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9004       }
9005
9006       // allocate memory for new nodes if it is not yet refined
9007       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9008       if ( edge._nodes.size() == 2 )
9009       {
9010         edge._nodes.resize( eos._hyp.GetNumberLayers() + 1, 0 );
9011         edge._nodes[1] = 0;
9012         edge._nodes.back() = tgtNode;
9013       }
9014       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9015       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9016       if ( baseShapeId != prevBaseId )
9017       {
9018         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9019         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9020         prevBaseId = baseShapeId;
9021       }
9022       _LayerEdge* edgeOnSameNode = 0;
9023       bool        useExistingPos = false;
9024       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9025       {
9026         edgeOnSameNode = n2e->second;
9027         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9028         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9029         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9030         if ( isOnEdge )
9031         {
9032           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9033           epos->SetUParameter( otherTgtPos.X() );
9034         }
9035         else
9036         {
9037           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9038           fpos->SetUParameter( otherTgtPos.X() );
9039           fpos->SetVParameter( otherTgtPos.Y() );
9040         }
9041       }
9042       // calculate height of the first layer
9043       double h0;
9044       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9045       const double f = eos._hyp.GetStretchFactor();
9046       const int    N = eos._hyp.GetNumberLayers();
9047       const double fPowN = pow( f, N );
9048       if ( fPowN - 1 <= numeric_limits<double>::min() )
9049         h0 = T / N;
9050       else
9051         h0 = T * ( f - 1 )/( fPowN - 1 );
9052
9053       const double zeroLen = std::numeric_limits<double>::min();
9054
9055       // create intermediate nodes
9056       double hSum = 0, hi = h0/f;
9057       size_t iSeg = 1;
9058       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9059       {
9060         // compute an intermediate position
9061         hi *= f;
9062         hSum += hi;
9063         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9064           ++iSeg;
9065         int iPrevSeg = iSeg-1;
9066         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9067           --iPrevSeg;
9068         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9069         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9070
9071         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9072         if ( !eos._sWOL.IsNull() )
9073         {
9074           // compute XYZ by parameters <pos>
9075           if ( isOnEdge )
9076           {
9077             u = pos.X();
9078             if ( !node )
9079               pos = curve->Value( u ).Transformed(loc);
9080           }
9081           else if ( eos._isRegularSWOL )
9082           {
9083             uv.SetCoord( pos.X(), pos.Y() );
9084             if ( !node )
9085               pos = surface->Value( pos.X(), pos.Y() );
9086           }
9087           else
9088           {
9089             uv.SetCoord( pos.X(), pos.Y() );
9090             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9091             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9092             if ( !node )
9093               pos = surface->Value( uv );
9094           }
9095         }
9096         // create or update the node
9097         if ( !node )
9098         {
9099           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9100           if ( !eos._sWOL.IsNull() )
9101           {
9102             if ( isOnEdge )
9103               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9104             else
9105               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9106           }
9107           else
9108           {
9109             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9110           }
9111         }
9112         else
9113         {
9114           if ( !eos._sWOL.IsNull() )
9115           {
9116             // make average pos from new and current parameters
9117             if ( isOnEdge )
9118             {
9119               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9120               if ( useExistingPos )
9121                 u = helper.GetNodeU( geomEdge, node );
9122               pos = curve->Value( u ).Transformed(loc);
9123
9124               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9125               epos->SetUParameter( u );
9126             }
9127             else
9128             {
9129               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9130               if ( useExistingPos )
9131                 uv = helper.GetNodeUV( geomFace, node );
9132               pos = surface->Value( uv );
9133
9134               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9135               fpos->SetUParameter( uv.X() );
9136               fpos->SetVParameter( uv.Y() );
9137             }
9138           }
9139           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9140         }
9141       } // loop on edge._nodes
9142
9143       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9144       {
9145         if ( isOnEdge )
9146           edge._pos.back().SetCoord( u, 0,0);
9147         else
9148           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9149
9150         if ( edgeOnSameNode )
9151           edgeOnSameNode->_pos.back() = edge._pos.back();
9152       }
9153
9154     } // loop on eos._edges to create nodes
9155
9156
9157     if ( !getMeshDS()->IsEmbeddedMode() )
9158       // Log node movement
9159       for ( size_t i = 0; i < eos._edges.size(); ++i )
9160       {
9161         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9162         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9163       }
9164   }
9165
9166
9167   // Create volumes
9168
9169   helper.SetElementsOnShape(true);
9170
9171   vector< vector<const SMDS_MeshNode*>* > nnVec;
9172   set< vector<const SMDS_MeshNode*>* >    nnSet;
9173   set< int >                       degenEdgeInd;
9174   vector<const SMDS_MeshElement*>     degenVols;
9175   vector<int>                       isRiskySWOL;
9176
9177   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9178   for ( ; exp.More(); exp.Next() )
9179   {
9180     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9181     if ( data._ignoreFaceIds.count( faceID ))
9182       continue;
9183     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9184     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9185     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9186     while ( fIt->more() )
9187     {
9188       const SMDS_MeshElement* face = fIt->next();
9189       const int            nbNodes = face->NbCornerNodes();
9190       nnVec.resize( nbNodes );
9191       nnSet.clear();
9192       degenEdgeInd.clear();
9193       isRiskySWOL.resize( nbNodes );
9194       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9195       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9196       for ( int iN = 0; iN < nbNodes; ++iN )
9197       {
9198         const SMDS_MeshNode* n = nIt->next();
9199         _LayerEdge*       edge = data._n2eMap[ n ];
9200         const int i = isReversedFace ? nbNodes-1-iN : iN;
9201         nnVec[ i ] = & edge->_nodes;
9202         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9203         minZ = std::min( minZ, nnVec[ i ]->size() );
9204         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9205
9206         if ( helper.HasDegeneratedEdges() )
9207           nnSet.insert( nnVec[ i ]);
9208       }
9209
9210       if ( maxZ == 0 )
9211         continue;
9212       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9213         continue;
9214
9215       switch ( nbNodes )
9216       {
9217       case 3: // TRIA
9218       {
9219         // PENTA
9220         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9221           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9222                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9223
9224         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9225         {
9226           for ( int iN = 0; iN < nbNodes; ++iN )
9227             if ( nnVec[ iN ]->size() < iZ+1 )
9228               degenEdgeInd.insert( iN );
9229
9230           if ( degenEdgeInd.size() == 1 )  // PYRAM
9231           {
9232             int i2 = *degenEdgeInd.begin();
9233             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9234             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9235             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9236                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9237           }
9238           else  // TETRA
9239           {
9240             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9241             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9242                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9243                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9244                               (*nnVec[ i3 ])[ iZ ]);
9245           }
9246         }
9247         break; // TRIA
9248       }
9249       case 4: // QUAD
9250       {
9251         // HEX
9252         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9253           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9254                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9255                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9256                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9257
9258         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9259         {
9260           for ( int iN = 0; iN < nbNodes; ++iN )
9261             if ( nnVec[ iN ]->size() < iZ+1 )
9262               degenEdgeInd.insert( iN );
9263
9264           switch ( degenEdgeInd.size() )
9265           {
9266           case 2: // PENTA
9267           {
9268             int i2 = *degenEdgeInd.begin();
9269             int i3 = *degenEdgeInd.rbegin();
9270             bool ok = ( i3 - i2 == 1 );
9271             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9272             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9273             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9274
9275             const SMDS_MeshElement* vol =
9276               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9277                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9278             if ( !ok && vol )
9279               degenVols.push_back( vol );
9280           }
9281           break;
9282
9283           default: // degen HEX
9284           {
9285             const SMDS_MeshElement* vol =
9286               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9287                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9288                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9289                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9290                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9291                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9292                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9293                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9294             degenVols.push_back( vol );
9295           }
9296           }
9297         }
9298         break; // HEX
9299       }
9300       default:
9301         return error("Not supported type of element", data._index);
9302
9303       } // switch ( nbNodes )
9304     } // while ( fIt->more() )
9305   } // loop on FACEs
9306
9307   if ( !degenVols.empty() )
9308   {
9309     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9310     if ( !err || err->IsOK() )
9311     {
9312       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9313                                          "Degenerated volumes created" ));
9314       err->myBadElements.insert( err->myBadElements.end(),
9315                                  degenVols.begin(),degenVols.end() );
9316     }
9317   }
9318
9319   return true;
9320 }
9321
9322 //================================================================================
9323 /*!
9324  * \brief Shrink 2D mesh on faces to let space for inflated layers
9325  */
9326 //================================================================================
9327
9328 bool _ViscousBuilder::shrink()
9329 {
9330   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9331   // inflated along FACE or EDGE)
9332   map< TGeomID, _SolidData* > f2sdMap;
9333   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9334   {
9335     _SolidData& data = _sdVec[i];
9336     TopTools_MapOfShape FFMap;
9337     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9338     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9339       if ( s2s->second.ShapeType() == TopAbs_FACE )
9340       {
9341         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9342
9343         if ( FFMap.Add( (*s2s).second ))
9344           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9345           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9346           // by StdMeshers_QuadToTriaAdaptor
9347           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9348           {
9349             SMESH_ProxyMesh::SubMesh* proxySub =
9350               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9351             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9352             while ( fIt->more() )
9353               proxySub->AddElement( fIt->next() );
9354             // as a result 3D algo will use elements from proxySub and not from smDS
9355           }
9356       }
9357   }
9358
9359   SMESH_MesherHelper helper( *_mesh );
9360   helper.ToFixNodeParameters( true );
9361
9362   // EDGE's to shrink
9363   map< TGeomID, _Shrinker1D > e2shrMap;
9364   vector< _EdgesOnShape* > subEOS;
9365   vector< _LayerEdge* > lEdges;
9366
9367   // loop on FACES to srink mesh on
9368   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9369   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9370   {
9371     _SolidData&      data = *f2sd->second;
9372     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9373     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9374     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9375
9376     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9377
9378     helper.SetSubShape(F);
9379
9380     // ===========================
9381     // Prepare data for shrinking
9382     // ===========================
9383
9384     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9385     // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9386     vector < const SMDS_MeshNode* > smoothNodes;
9387     {
9388       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9389       while ( nIt->more() )
9390       {
9391         const SMDS_MeshNode* n = nIt->next();
9392         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9393           smoothNodes.push_back( n );
9394       }
9395     }
9396     // Find out face orientation
9397     double refSign = 1;
9398     const set<TGeomID> ignoreShapes;
9399     bool isOkUV;
9400     if ( !smoothNodes.empty() )
9401     {
9402       vector<_Simplex> simplices;
9403       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9404       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9405       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9406       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9407       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9408         refSign = -1;
9409     }
9410
9411     // Find _LayerEdge's inflated along F
9412     subEOS.clear();
9413     lEdges.clear();
9414     {
9415       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9416                                                                 /*complexFirst=*/true); //!!!
9417       while ( subIt->more() )
9418       {
9419         const TGeomID subID = subIt->next()->GetId();
9420         if ( data._noShrinkShapes.count( subID ))
9421           continue;
9422         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9423         if ( !eos || eos->_sWOL.IsNull() ) continue;
9424
9425         subEOS.push_back( eos );
9426
9427         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9428         {
9429           lEdges.push_back( eos->_edges[ i ] );
9430           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9431         }
9432       }
9433     }
9434
9435     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9436     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9437     while ( fIt->more() )
9438       if ( const SMDS_MeshElement* f = fIt->next() )
9439         dumpChangeNodes( f );
9440     dumpFunctionEnd();
9441
9442     // Replace source nodes by target nodes in mesh faces to shrink
9443     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9444     const SMDS_MeshNode* nodes[20];
9445     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9446     {
9447       _EdgesOnShape& eos = * subEOS[ iS ];
9448       for ( size_t i = 0; i < eos._edges.size(); ++i )
9449       {
9450         _LayerEdge& edge = *eos._edges[i];
9451         const SMDS_MeshNode* srcNode = edge._nodes[0];
9452         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9453         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9454         while ( fIt->more() )
9455         {
9456           const SMDS_MeshElement* f = fIt->next();
9457           if ( !smDS->Contains( f ))
9458             continue;
9459           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9460           for ( int iN = 0; nIt->more(); ++iN )
9461           {
9462             const SMDS_MeshNode* n = nIt->next();
9463             nodes[iN] = ( n == srcNode ? tgtNode : n );
9464           }
9465           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9466           dumpChangeNodes( f );
9467         }
9468       }
9469     }
9470     dumpFunctionEnd();
9471
9472     // find out if a FACE is concave
9473     const bool isConcaveFace = isConcave( F, helper );
9474
9475     // Create _SmoothNode's on face F
9476     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9477     {
9478       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9479       const bool sortSimplices = isConcaveFace;
9480       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9481       {
9482         const SMDS_MeshNode* n = smoothNodes[i];
9483         nodesToSmooth[ i ]._node = n;
9484         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9485         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9486         // fix up incorrect uv of nodes on the FACE
9487         helper.GetNodeUV( F, n, 0, &isOkUV);
9488         dumpMove( n );
9489       }
9490       dumpFunctionEnd();
9491     }
9492     //if ( nodesToSmooth.empty() ) continue;
9493
9494     // Find EDGE's to shrink and set simpices to LayerEdge's
9495     set< _Shrinker1D* > eShri1D;
9496     {
9497       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9498       {
9499         _EdgesOnShape& eos = * subEOS[ iS ];
9500         if ( eos.SWOLType() == TopAbs_EDGE )
9501         {
9502           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9503           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9504           eShri1D.insert( & srinker );
9505           srinker.AddEdge( eos._edges[0], eos, helper );
9506           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9507           // restore params of nodes on EGDE if the EDGE has been already
9508           // srinked while srinking other FACE
9509           srinker.RestoreParams();
9510         }
9511         for ( size_t i = 0; i < eos._edges.size(); ++i )
9512         {
9513           _LayerEdge& edge = * eos._edges[i];
9514           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9515         }
9516       }
9517     }
9518
9519     bool toFixTria = false; // to improve quality of trias by diagonal swap
9520     if ( isConcaveFace )
9521     {
9522       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9523       if ( hasTria != hasQuad ) {
9524         toFixTria = hasTria;
9525       }
9526       else {
9527         set<int> nbNodesSet;
9528         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9529         while ( fIt->more() && nbNodesSet.size() < 2 )
9530           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9531         toFixTria = ( *nbNodesSet.begin() == 3 );
9532       }
9533     }
9534
9535     // ==================
9536     // Perform shrinking
9537     // ==================
9538
9539     bool shrinked = true;
9540     int nbBad, shriStep=0, smooStep=0;
9541     _SmoothNode::SmoothType smoothType
9542       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9543     SMESH_Comment errMsg;
9544     while ( shrinked )
9545     {
9546       shriStep++;
9547       // Move boundary nodes (actually just set new UV)
9548       // -----------------------------------------------
9549       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9550       shrinked = false;
9551       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9552       {
9553         _EdgesOnShape& eos = * subEOS[ iS ];
9554         for ( size_t i = 0; i < eos._edges.size(); ++i )
9555         {
9556           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9557         }
9558       }
9559       dumpFunctionEnd();
9560
9561       // Move nodes on EDGE's
9562       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9563       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9564       for ( ; shr != eShri1D.end(); ++shr )
9565         (*shr)->Compute( /*set3D=*/false, helper );
9566
9567       // Smoothing in 2D
9568       // -----------------
9569       int nbNoImpSteps = 0;
9570       bool       moved = true;
9571       nbBad = 1;
9572       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9573       {
9574         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9575
9576         int oldBadNb = nbBad;
9577         nbBad = 0;
9578         moved = false;
9579         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9580         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9581         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9582         {
9583           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9584                                             smooTy, /*set3D=*/isConcaveFace);
9585         }
9586         if ( nbBad < oldBadNb )
9587           nbNoImpSteps = 0;
9588         else
9589           nbNoImpSteps++;
9590
9591         dumpFunctionEnd();
9592       }
9593
9594       errMsg.clear();
9595       if ( nbBad > 0 )
9596         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9597       if ( shriStep > 200 )
9598         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9599       if ( !errMsg.empty() )
9600         break;
9601
9602       // Fix narrow triangles by swapping diagonals
9603       // ---------------------------------------
9604       if ( toFixTria )
9605       {
9606         set<const SMDS_MeshNode*> usedNodes;
9607         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9608
9609         // update working data
9610         set<const SMDS_MeshNode*>::iterator n;
9611         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9612         {
9613           n = usedNodes.find( nodesToSmooth[ i ]._node );
9614           if ( n != usedNodes.end())
9615           {
9616             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9617                                     nodesToSmooth[ i ]._simplices,
9618                                     ignoreShapes, NULL,
9619                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9620             usedNodes.erase( n );
9621           }
9622         }
9623         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9624         {
9625           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9626           if ( n != usedNodes.end())
9627           {
9628             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9629                                     lEdges[i]->_simplices,
9630                                     ignoreShapes );
9631             usedNodes.erase( n );
9632           }
9633         }
9634       }
9635       // TODO: check effect of this additional smooth
9636       // additional laplacian smooth to increase allowed shrink step
9637       // for ( int st = 1; st; --st )
9638       // {
9639       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9640       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9641       //   {
9642       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9643       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
9644       //   }
9645       // }
9646
9647     } // while ( shrinked )
9648
9649     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9650     {
9651       // remove faces
9652       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9653       {
9654         vector< const SMDS_MeshElement* > facesToRm;
9655         if ( psm )
9656         {
9657           facesToRm.reserve( psm->NbElements() );
9658           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9659             facesToRm.push_back( ite->next() );
9660
9661           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9662             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9663               psm->Clear();
9664         }
9665         for ( size_t i = 0; i < facesToRm.size(); ++i )
9666           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9667       }
9668       // remove nodes
9669       {
9670         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9671         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9672           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9673             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9674                                 subEOS[iS]->_edges[i]->_nodes.end() );
9675         }
9676         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9677         while ( itn->more() ) {
9678           const SMDS_MeshNode* n = itn->next();
9679           if ( !nodesToKeep.count( n ))
9680             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9681         }
9682       }
9683       // restore position and UV of target nodes
9684       gp_Pnt p;
9685       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9686         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9687         {
9688           _LayerEdge*       edge = subEOS[iS]->_edges[i];
9689           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9690           if ( edge->_pos.empty() ) continue;
9691           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9692           {
9693             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9694             pos->SetUParameter( edge->_pos[0].X() );
9695             pos->SetVParameter( edge->_pos[0].Y() );
9696             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
9697           }
9698           else
9699           {
9700             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9701             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
9702             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
9703           }
9704           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
9705           dumpMove( tgtNode );
9706         }
9707       // shrink EDGE sub-meshes and set proxy sub-meshes
9708       UVPtStructVec uvPtVec;
9709       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
9710       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
9711       {
9712         _Shrinker1D* shr = (*shrIt);
9713         shr->Compute( /*set3D=*/true, helper );
9714
9715         // set proxy mesh of EDGEs w/o layers
9716         map< double, const SMDS_MeshNode* > nodes;
9717         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
9718         // remove refinement nodes
9719         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
9720         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
9721         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
9722         if ( u2n->second == sn0 || u2n->second == sn1 )
9723         {
9724           while ( u2n->second != tn0 && u2n->second != tn1 )
9725             ++u2n;
9726           nodes.erase( nodes.begin(), u2n );
9727         }
9728         u2n = --nodes.end();
9729         if ( u2n->second == sn0 || u2n->second == sn1 )
9730         {
9731           while ( u2n->second != tn0 && u2n->second != tn1 )
9732             --u2n;
9733           nodes.erase( ++u2n, nodes.end() );
9734         }
9735         // set proxy sub-mesh
9736         uvPtVec.resize( nodes.size() );
9737         u2n = nodes.begin();
9738         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
9739         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
9740         {
9741           uvPtVec[ i ].node = u2n->second;
9742           uvPtVec[ i ].param = u2n->first;
9743           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
9744         }
9745         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
9746         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9747       }
9748
9749       // set proxy mesh of EDGEs with layers
9750       vector< _LayerEdge* > edges;
9751       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9752       {
9753         _EdgesOnShape& eos = * subEOS[ iS ];
9754         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
9755
9756         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
9757         data.SortOnEdge( E, eos._edges );
9758
9759         edges.clear();
9760         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
9761           if ( !eov->_edges.empty() )
9762             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
9763
9764         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
9765
9766         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
9767           if ( !eov->_edges.empty() )
9768             edges.push_back( eov->_edges[0] ); // on last VERTEX
9769
9770         uvPtVec.resize( edges.size() );
9771         for ( size_t i = 0; i < edges.size(); ++i )
9772         {
9773           uvPtVec[ i ].node = edges[i]->_nodes.back();
9774           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
9775           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
9776         }
9777         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
9778         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
9779         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
9780       }
9781       // temporary clear the FACE sub-mesh from faces made by refine()
9782       vector< const SMDS_MeshElement* > elems;
9783       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
9784       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9785         elems.push_back( ite->next() );
9786       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
9787         elems.push_back( ite->next() );
9788       smDS->Clear();
9789
9790       // compute the mesh on the FACE
9791       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
9792       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
9793
9794       // re-fill proxy sub-meshes of the FACE
9795       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9796         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9797           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
9798             psm->AddElement( ite->next() );
9799
9800       // re-fill smDS
9801       for ( size_t i = 0; i < elems.size(); ++i )
9802         smDS->AddElement( elems[i] );
9803
9804       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
9805         return error( errMsg );
9806
9807     } // end of re-meshing in case of failed smoothing
9808     else
9809     {
9810       // No wrongly shaped faces remain; final smooth. Set node XYZ.
9811       bool isStructuredFixed = false;
9812       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
9813         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
9814       if ( !isStructuredFixed )
9815       {
9816         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
9817           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
9818
9819         for ( int st = 3; st; --st )
9820         {
9821           switch( st ) {
9822           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
9823           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
9824           case 3: smoothType = _SmoothNode::ANGULAR; break;
9825           }
9826           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9827           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9828           {
9829             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9830                                      smoothType,/*set3D=*/st==1 );
9831           }
9832           dumpFunctionEnd();
9833         }
9834       }
9835       if ( !getMeshDS()->IsEmbeddedMode() )
9836         // Log node movement
9837         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9838         {
9839           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
9840           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
9841         }
9842     }
9843
9844     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
9845     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
9846
9847   } // loop on FACES to srink mesh on
9848
9849
9850   // Replace source nodes by target nodes in shrinked mesh edges
9851
9852   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
9853   for ( ; e2shr != e2shrMap.end(); ++e2shr )
9854     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
9855
9856   return true;
9857 }
9858
9859 //================================================================================
9860 /*!
9861  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
9862  */
9863 //================================================================================
9864
9865 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
9866                                            _EdgesOnShape&         eos,
9867                                            SMESH_MesherHelper&    helper,
9868                                            const SMESHDS_SubMesh* faceSubMesh)
9869 {
9870   const SMDS_MeshNode* srcNode = edge._nodes[0];
9871   const SMDS_MeshNode* tgtNode = edge._nodes.back();
9872
9873   if ( eos.SWOLType() == TopAbs_FACE )
9874   {
9875     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
9876     {
9877       edge._pos.clear();
9878       return srcNode == tgtNode;
9879     }
9880     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
9881     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
9882     gp_Vec2d uvDir( srcUV, tgtUV );
9883     double uvLen = uvDir.Magnitude();
9884     uvDir /= uvLen;
9885     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
9886     edge._len = uvLen;
9887
9888     edge._pos.resize(1);
9889     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
9890
9891     // set UV of source node to target node
9892     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9893     pos->SetUParameter( srcUV.X() );
9894     pos->SetVParameter( srcUV.Y() );
9895   }
9896   else // _sWOL is TopAbs_EDGE
9897   {
9898     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
9899     {
9900       edge._pos.clear();
9901       return srcNode == tgtNode;
9902     }
9903     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
9904     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
9905     if ( !edgeSM || edgeSM->NbElements() == 0 )
9906       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9907
9908     const SMDS_MeshNode* n2 = 0;
9909     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
9910     while ( eIt->more() && !n2 )
9911     {
9912       const SMDS_MeshElement* e = eIt->next();
9913       if ( !edgeSM->Contains(e)) continue;
9914       n2 = e->GetNode( 0 );
9915       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
9916     }
9917     if ( !n2 )
9918       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
9919
9920     double uSrc = helper.GetNodeU( E, srcNode, n2 );
9921     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
9922     double u2   = helper.GetNodeU( E, n2, srcNode );
9923
9924     edge._pos.clear();
9925
9926     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
9927     {
9928       // tgtNode is located so that it does not make faces with wrong orientation
9929       return true;
9930     }
9931     edge._pos.resize(1);
9932     edge._pos[0].SetCoord( U_TGT, uTgt );
9933     edge._pos[0].SetCoord( U_SRC, uSrc );
9934     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
9935
9936     edge._simplices.resize( 1 );
9937     edge._simplices[0]._nPrev = n2;
9938
9939     // set U of source node to the target node
9940     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
9941     pos->SetUParameter( uSrc );
9942   }
9943   return true;
9944 }
9945
9946 //================================================================================
9947 /*!
9948  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
9949  */
9950 //================================================================================
9951
9952 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
9953 {
9954   if ( edge._nodes.size() == 1 )
9955   {
9956     edge._pos.clear();
9957     edge._len = 0;
9958
9959     const SMDS_MeshNode* srcNode = edge._nodes[0];
9960     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
9961     if ( S.IsNull() ) return;
9962
9963     gp_Pnt p;
9964
9965     switch ( S.ShapeType() )
9966     {
9967     case TopAbs_EDGE:
9968     {
9969       double f,l;
9970       TopLoc_Location loc;
9971       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
9972       if ( curve.IsNull() ) return;
9973       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
9974       p = curve->Value( ePos->GetUParameter() );
9975       break;
9976     }
9977     case TopAbs_VERTEX:
9978     {
9979       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
9980       break;
9981     }
9982     default: return;
9983     }
9984     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
9985     dumpMove( srcNode );
9986   }
9987 }
9988
9989 //================================================================================
9990 /*!
9991  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
9992  */
9993 //================================================================================
9994
9995 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
9996                                   SMESH_MesherHelper&         helper,
9997                                   const bool                  is2D,
9998                                   const int                   step,
9999                                   set<const SMDS_MeshNode*> * involvedNodes)
10000 {
10001   SMESH::Controls::AspectRatio qualifier;
10002   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10003   const double maxAspectRatio = is2D ? 4. : 2;
10004   _NodeCoordHelper xyz( F, helper, is2D );
10005
10006   // find bad triangles
10007
10008   vector< const SMDS_MeshElement* > badTrias;
10009   vector< double >                  badAspects;
10010   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10011   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10012   while ( fIt->more() )
10013   {
10014     const SMDS_MeshElement * f = fIt->next();
10015     if ( f->NbCornerNodes() != 3 ) continue;
10016     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10017     double aspect = qualifier.GetValue( points );
10018     if ( aspect > maxAspectRatio )
10019     {
10020       badTrias.push_back( f );
10021       badAspects.push_back( aspect );
10022     }
10023   }
10024   if ( step == 1 )
10025   {
10026     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10027     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10028     while ( fIt->more() )
10029     {
10030       const SMDS_MeshElement * f = fIt->next();
10031       if ( f->NbCornerNodes() == 3 )
10032         dumpChangeNodes( f );
10033     }
10034     dumpFunctionEnd();
10035   }
10036   if ( badTrias.empty() )
10037     return;
10038
10039   // find couples of faces to swap diagonal
10040
10041   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10042   vector< T2Trias > triaCouples; 
10043
10044   TIDSortedElemSet involvedFaces, emptySet;
10045   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10046   {
10047     T2Trias trias    [3];
10048     double  aspRatio [3];
10049     int i1, i2, i3;
10050
10051     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10052       continue;
10053     for ( int iP = 0; iP < 3; ++iP )
10054       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10055
10056     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10057     int bestCouple = -1;
10058     for ( int iSide = 0; iSide < 3; ++iSide )
10059     {
10060       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10061       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10062       trias [iSide].first  = badTrias[iTia];
10063       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10064                                                              & i1, & i2 );
10065       if (( ! trias[iSide].second ) ||
10066           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10067           ( ! sm->Contains( trias[iSide].second )))
10068         continue;
10069
10070       // aspect ratio of an adjacent tria
10071       for ( int iP = 0; iP < 3; ++iP )
10072         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10073       double aspectInit = qualifier.GetValue( points2 );
10074
10075       // arrange nodes as after diag-swaping
10076       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10077         i3 = helper.WrapIndex( i1-1, 3 );
10078       else
10079         i3 = helper.WrapIndex( i1+1, 3 );
10080       points1 = points;
10081       points1( 1+ iSide ) = points2( 1+ i3 );
10082       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10083
10084       // aspect ratio after diag-swaping
10085       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10086       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10087         continue;
10088
10089       // prevent inversion of a triangle
10090       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10091       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10092       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10093         continue;
10094
10095       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10096         bestCouple = iSide;
10097     }
10098
10099     if ( bestCouple >= 0 )
10100     {
10101       triaCouples.push_back( trias[bestCouple] );
10102       involvedFaces.insert ( trias[bestCouple].second );
10103     }
10104     else
10105     {
10106       involvedFaces.erase( badTrias[iTia] );
10107     }
10108   }
10109   if ( triaCouples.empty() )
10110     return;
10111
10112   // swap diagonals
10113
10114   SMESH_MeshEditor editor( helper.GetMesh() );
10115   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10116   for ( size_t i = 0; i < triaCouples.size(); ++i )
10117   {
10118     dumpChangeNodes( triaCouples[i].first );
10119     dumpChangeNodes( triaCouples[i].second );
10120     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10121   }
10122
10123   if ( involvedNodes )
10124     for ( size_t i = 0; i < triaCouples.size(); ++i )
10125     {
10126       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10127                              triaCouples[i].first->end_nodes() );
10128       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10129                              triaCouples[i].second->end_nodes() );
10130     }
10131
10132   // just for debug dump resulting triangles
10133   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10134   for ( size_t i = 0; i < triaCouples.size(); ++i )
10135   {
10136     dumpChangeNodes( triaCouples[i].first );
10137     dumpChangeNodes( triaCouples[i].second );
10138   }
10139 }
10140
10141 //================================================================================
10142 /*!
10143  * \brief Move target node to it's final position on the FACE during shrinking
10144  */
10145 //================================================================================
10146
10147 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10148                                  const TopoDS_Face&    F,
10149                                  _EdgesOnShape&        eos,
10150                                  SMESH_MesherHelper&   helper )
10151 {
10152   if ( _pos.empty() )
10153     return false; // already at the target position
10154
10155   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10156
10157   if ( eos.SWOLType() == TopAbs_FACE )
10158   {
10159     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10160     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10161     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10162     const double uvLen = tgtUV.Distance( curUV );
10163     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10164
10165     // Select shrinking step such that not to make faces with wrong orientation.
10166     double stepSize = 1e100;
10167     for ( size_t i = 0; i < _simplices.size(); ++i )
10168     {
10169       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10170       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10171       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10172       gp_XY dirN = uvN2 - uvN1;
10173       double det = uvDir.Crossed( dirN );
10174       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10175       gp_XY dirN2Cur = curUV - uvN1;
10176       double step = dirN.Crossed( dirN2Cur ) / det;
10177       if ( step > 0 )
10178         stepSize = Min( step, stepSize );
10179     }
10180     gp_Pnt2d newUV;
10181     if ( uvLen <= stepSize )
10182     {
10183       newUV = tgtUV;
10184       _pos.clear();
10185     }
10186     else if ( stepSize > 0 )
10187     {
10188       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10189     }
10190     else
10191     {
10192       return true;
10193     }
10194     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10195     pos->SetUParameter( newUV.X() );
10196     pos->SetVParameter( newUV.Y() );
10197
10198 #ifdef __myDEBUG
10199     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10200     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10201     dumpMove( tgtNode );
10202 #endif
10203   }
10204   else // _sWOL is TopAbs_EDGE
10205   {
10206     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10207     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10208     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10209
10210     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10211     const double uSrc   = _pos[0].Coord( U_SRC );
10212     const double lenTgt = _pos[0].Coord( LEN_TGT );
10213
10214     double newU = _pos[0].Coord( U_TGT );
10215     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10216     {
10217       _pos.clear();
10218     }
10219     else
10220     {
10221       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10222     }
10223     tgtPos->SetUParameter( newU );
10224 #ifdef __myDEBUG
10225     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10226     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10227     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10228     dumpMove( tgtNode );
10229 #endif
10230   }
10231
10232   return true;
10233 }
10234
10235 //================================================================================
10236 /*!
10237  * \brief Perform smooth on the FACE
10238  *  \retval bool - true if the node has been moved
10239  */
10240 //================================================================================
10241
10242 bool _SmoothNode::Smooth(int&                  nbBad,
10243                          Handle(Geom_Surface)& surface,
10244                          SMESH_MesherHelper&   helper,
10245                          const double          refSign,
10246                          SmoothType            how,
10247                          bool                  set3D)
10248 {
10249   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10250
10251   // get uv of surrounding nodes
10252   vector<gp_XY> uv( _simplices.size() );
10253   for ( size_t i = 0; i < _simplices.size(); ++i )
10254     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10255
10256   // compute new UV for the node
10257   gp_XY newPos (0,0);
10258   if ( how == TFI && _simplices.size() == 4 )
10259   {
10260     gp_XY corners[4];
10261     for ( size_t i = 0; i < _simplices.size(); ++i )
10262       if ( _simplices[i]._nOpp )
10263         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10264       else
10265         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10266
10267     newPos = helper.calcTFI ( 0.5, 0.5,
10268                               corners[0], corners[1], corners[2], corners[3],
10269                               uv[1], uv[2], uv[3], uv[0] );
10270   }
10271   else if ( how == ANGULAR )
10272   {
10273     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10274   }
10275   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10276   {
10277     // average centers of diagonals wieghted with their reciprocal lengths
10278     if ( _simplices.size() == 4 )
10279     {
10280       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10281       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10282       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10283     }
10284     else
10285     {
10286       double sumWeight = 0;
10287       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10288       for ( int i = 0; i < nb; ++i )
10289       {
10290         int iFrom = i + 2;
10291         int iTo   = i + _simplices.size() - 1;
10292         for ( int j = iFrom; j < iTo; ++j )
10293         {
10294           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10295           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10296           sumWeight += w;
10297           newPos += w * ( uv[i]+uv[i2] );
10298         }
10299       }
10300       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10301     }
10302   }
10303   else
10304   {
10305     // Laplacian smooth
10306     for ( size_t i = 0; i < _simplices.size(); ++i )
10307       newPos += uv[i];
10308     newPos /= _simplices.size();
10309   }
10310
10311   // count quality metrics (orientation) of triangles around the node
10312   int nbOkBefore = 0;
10313   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10314   for ( size_t i = 0; i < _simplices.size(); ++i )
10315     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10316
10317   int nbOkAfter = 0;
10318   for ( size_t i = 0; i < _simplices.size(); ++i )
10319     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10320
10321   if ( nbOkAfter < nbOkBefore )
10322   {
10323     nbBad += _simplices.size() - nbOkBefore;
10324     return false;
10325   }
10326
10327   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10328   pos->SetUParameter( newPos.X() );
10329   pos->SetVParameter( newPos.Y() );
10330
10331 #ifdef __myDEBUG
10332   set3D = true;
10333 #endif
10334   if ( set3D )
10335   {
10336     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10337     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10338     dumpMove( _node );
10339   }
10340
10341   nbBad += _simplices.size() - nbOkAfter;
10342   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10343 }
10344
10345 //================================================================================
10346 /*!
10347  * \brief Computes new UV using angle based smoothing technic
10348  */
10349 //================================================================================
10350
10351 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10352                                      const gp_XY&   uvToFix,
10353                                      const double   refSign)
10354 {
10355   uv.push_back( uv.front() );
10356
10357   vector< gp_XY >  edgeDir ( uv.size() );
10358   vector< double > edgeSize( uv.size() );
10359   for ( size_t i = 1; i < edgeDir.size(); ++i )
10360   {
10361     edgeDir [i-1] = uv[i] - uv[i-1];
10362     edgeSize[i-1] = edgeDir[i-1].Modulus();
10363     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10364       edgeDir[i-1].SetX( 100 );
10365     else
10366       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10367   }
10368   edgeDir.back()  = edgeDir.front();
10369   edgeSize.back() = edgeSize.front();
10370
10371   gp_XY  newPos(0,0);
10372   //int    nbEdges = 0;
10373   double sumSize = 0;
10374   for ( size_t i = 1; i < edgeDir.size(); ++i )
10375   {
10376     if ( edgeDir[i-1].X() > 1. ) continue;
10377     int i1 = i-1;
10378     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10379     if ( i == edgeDir.size() ) break;
10380     gp_XY p = uv[i];
10381     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10382     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10383     gp_XY bisec = norm1 + norm2;
10384     double bisecSize = bisec.Modulus();
10385     if ( bisecSize < numeric_limits<double>::min() )
10386     {
10387       bisec = -edgeDir[i1] + edgeDir[i];
10388       bisecSize = bisec.Modulus();
10389     }
10390     bisec /= bisecSize;
10391
10392     gp_XY  dirToN  = uvToFix - p;
10393     double distToN = dirToN.Modulus();
10394     if ( bisec * dirToN < 0 )
10395       distToN = -distToN;
10396
10397     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10398     //++nbEdges;
10399     sumSize += edgeSize[i1] + edgeSize[i];
10400   }
10401   newPos /= /*nbEdges * */sumSize;
10402   return newPos;
10403 }
10404
10405 //================================================================================
10406 /*!
10407  * \brief Delete _SolidData
10408  */
10409 //================================================================================
10410
10411 _SolidData::~_SolidData()
10412 {
10413   TNode2Edge::iterator n2e = _n2eMap.begin();
10414   for ( ; n2e != _n2eMap.end(); ++n2e )
10415   {
10416     _LayerEdge* & e = n2e->second;
10417     if ( e )
10418     {
10419       delete e->_curvature;
10420       if ( e->_2neibors )
10421         delete e->_2neibors->_plnNorm;
10422       delete e->_2neibors;
10423     }
10424     delete e;
10425     e = 0;
10426   }
10427   _n2eMap.clear();
10428
10429   delete _helper;
10430   _helper = 0;
10431 }
10432
10433 //================================================================================
10434 /*!
10435  * \brief Keep a _LayerEdge inflated along the EDGE
10436  */
10437 //================================================================================
10438
10439 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10440                            _EdgesOnShape&      eos,
10441                            SMESH_MesherHelper& helper )
10442 {
10443   // init
10444   if ( _nodes.empty() )
10445   {
10446     _edges[0] = _edges[1] = 0;
10447     _done = false;
10448   }
10449   // check _LayerEdge
10450   if ( e == _edges[0] || e == _edges[1] )
10451     return;
10452   if ( eos.SWOLType() != TopAbs_EDGE )
10453     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10454   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10455     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10456
10457   // store _LayerEdge
10458   _geomEdge = TopoDS::Edge( eos._sWOL );
10459   double f,l;
10460   BRep_Tool::Range( _geomEdge, f,l );
10461   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10462   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10463
10464   // Update _nodes
10465
10466   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10467   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10468
10469   if ( _nodes.empty() )
10470   {
10471     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10472     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10473       return;
10474     TopLoc_Location loc;
10475     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10476     GeomAdaptor_Curve aCurve(C, f,l);
10477     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10478
10479     int nbExpectNodes = eSubMesh->NbNodes();
10480     _initU  .reserve( nbExpectNodes );
10481     _normPar.reserve( nbExpectNodes );
10482     _nodes  .reserve( nbExpectNodes );
10483     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10484     while ( nIt->more() )
10485     {
10486       const SMDS_MeshNode* node = nIt->next();
10487       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10488            node == tgtNode0 || node == tgtNode1 )
10489         continue; // refinement nodes
10490       _nodes.push_back( node );
10491       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10492       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10493       _normPar.push_back(  len / totLen );
10494     }
10495   }
10496   else
10497   {
10498     // remove target node of the _LayerEdge from _nodes
10499     size_t nbFound = 0;
10500     for ( size_t i = 0; i < _nodes.size(); ++i )
10501       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10502         _nodes[i] = 0, nbFound++;
10503     if ( nbFound == _nodes.size() )
10504       _nodes.clear();
10505   }
10506 }
10507
10508 //================================================================================
10509 /*!
10510  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10511  */
10512 //================================================================================
10513
10514 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10515 {
10516   if ( _done || _nodes.empty())
10517     return;
10518   const _LayerEdge* e = _edges[0];
10519   if ( !e ) e = _edges[1];
10520   if ( !e ) return;
10521
10522   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10523             ( !_edges[1] || _edges[1]->_pos.empty() ));
10524
10525   double f,l;
10526   if ( set3D || _done )
10527   {
10528     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10529     GeomAdaptor_Curve aCurve(C, f,l);
10530
10531     if ( _edges[0] )
10532       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10533     if ( _edges[1] )
10534       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10535     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10536
10537     for ( size_t i = 0; i < _nodes.size(); ++i )
10538     {
10539       if ( !_nodes[i] ) continue;
10540       double len = totLen * _normPar[i];
10541       GCPnts_AbscissaPoint discret( aCurve, len, f );
10542       if ( !discret.IsDone() )
10543         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10544       double u = discret.Parameter();
10545       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10546       pos->SetUParameter( u );
10547       gp_Pnt p = C->Value( u );
10548       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10549     }
10550   }
10551   else
10552   {
10553     BRep_Tool::Range( _geomEdge, f,l );
10554     if ( _edges[0] )
10555       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10556     if ( _edges[1] )
10557       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10558     
10559     for ( size_t i = 0; i < _nodes.size(); ++i )
10560     {
10561       if ( !_nodes[i] ) continue;
10562       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10563       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10564       pos->SetUParameter( u );
10565     }
10566   }
10567 }
10568
10569 //================================================================================
10570 /*!
10571  * \brief Restore initial parameters of nodes on EDGE
10572  */
10573 //================================================================================
10574
10575 void _Shrinker1D::RestoreParams()
10576 {
10577   if ( _done )
10578     for ( size_t i = 0; i < _nodes.size(); ++i )
10579     {
10580       if ( !_nodes[i] ) continue;
10581       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10582       pos->SetUParameter( _initU[i] );
10583     }
10584   _done = false;
10585 }
10586
10587 //================================================================================
10588 /*!
10589  * \brief Replace source nodes by target nodes in shrinked mesh edges
10590  */
10591 //================================================================================
10592
10593 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10594 {
10595   const SMDS_MeshNode* nodes[3];
10596   for ( int i = 0; i < 2; ++i )
10597   {
10598     if ( !_edges[i] ) continue;
10599
10600     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10601     if ( !eSubMesh ) return;
10602     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10603     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10604     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10605     while ( eIt->more() )
10606     {
10607       const SMDS_MeshElement* e = eIt->next();
10608       if ( !eSubMesh->Contains( e ))
10609           continue;
10610       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10611       for ( int iN = 0; iN < e->NbNodes(); ++iN )
10612       {
10613         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10614         nodes[iN] = ( n == srcNode ? tgtNode : n );
10615       }
10616       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10617     }
10618   }
10619 }
10620
10621 //================================================================================
10622 /*!
10623  * \brief Creates 2D and 1D elements on boundaries of new prisms
10624  */
10625 //================================================================================
10626
10627 bool _ViscousBuilder::addBoundaryElements()
10628 {
10629   SMESH_MesherHelper helper( *_mesh );
10630
10631   vector< const SMDS_MeshNode* > faceNodes;
10632
10633   for ( size_t i = 0; i < _sdVec.size(); ++i )
10634   {
10635     _SolidData& data = _sdVec[i];
10636     TopTools_IndexedMapOfShape geomEdges;
10637     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10638     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10639     {
10640       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10641       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10642         continue;
10643
10644       // Get _LayerEdge's based on E
10645
10646       map< double, const SMDS_MeshNode* > u2nodes;
10647       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10648         continue;
10649
10650       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10651       TNode2Edge & n2eMap = data._n2eMap;
10652       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10653       {
10654         //check if 2D elements are needed on E
10655         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10656         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10657         ledges.push_back( n2e->second );
10658         u2n++;
10659         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10660           continue; // no layers on E
10661         ledges.push_back( n2eMap[ u2n->second ]);
10662
10663         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10664         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10665         int nbSharedPyram = 0;
10666         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10667         while ( vIt->more() )
10668         {
10669           const SMDS_MeshElement* v = vIt->next();
10670           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10671         }
10672         if ( nbSharedPyram > 1 )
10673           continue; // not free border of the pyramid
10674
10675         faceNodes.clear();
10676         faceNodes.push_back( ledges[0]->_nodes[0] );
10677         faceNodes.push_back( ledges[1]->_nodes[0] );
10678         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10679         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10680
10681         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10682           continue; // faces already created
10683       }
10684       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10685         ledges.push_back( n2eMap[ u2n->second ]);
10686
10687       // Find out orientation and type of face to create
10688
10689       bool reverse = false, isOnFace;
10690       
10691       map< TGeomID, TopoDS_Shape >::iterator e2f =
10692         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10693       TopoDS_Shape F;
10694       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10695       {
10696         F = e2f->second.Oriented( TopAbs_FORWARD );
10697         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
10698         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
10699           reverse = !reverse, F.Reverse();
10700         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
10701           reverse = !reverse;
10702       }
10703       else
10704       {
10705         // find FACE with layers sharing E
10706         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
10707         while ( fIt->more() && F.IsNull() )
10708         {
10709           const TopoDS_Shape* pF = fIt->next();
10710           if ( helper.IsSubShape( *pF, data._solid) &&
10711                !data._ignoreFaceIds.count( e2f->first ))
10712             F = *pF;
10713         }
10714       }
10715       // Find the sub-mesh to add new faces
10716       SMESHDS_SubMesh* sm = 0;
10717       if ( isOnFace )
10718         sm = getMeshDS()->MeshElements( F );
10719       else
10720         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
10721       if ( !sm )
10722         return error("error in addBoundaryElements()", data._index);
10723
10724       // Make faces
10725       const int dj1 = reverse ? 0 : 1;
10726       const int dj2 = reverse ? 1 : 0;
10727       for ( size_t j = 1; j < ledges.size(); ++j )
10728       {
10729         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
10730         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
10731         if ( nn1.size() == nn2.size() )
10732         {
10733           if ( isOnFace )
10734             for ( size_t z = 1; z < nn1.size(); ++z )
10735               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10736           else
10737             for ( size_t z = 1; z < nn1.size(); ++z )
10738               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
10739         }
10740         else if ( nn1.size() == 1 )
10741         {
10742           if ( isOnFace )
10743             for ( size_t z = 1; z < nn2.size(); ++z )
10744               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
10745           else
10746             for ( size_t z = 1; z < nn2.size(); ++z )
10747               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
10748         }
10749         else
10750         {
10751           if ( isOnFace )
10752             for ( size_t z = 1; z < nn1.size(); ++z )
10753               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
10754           else
10755             for ( size_t z = 1; z < nn1.size(); ++z )
10756               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
10757         }
10758       }
10759
10760       // Make edges
10761       for ( int isFirst = 0; isFirst < 2; ++isFirst )
10762       {
10763         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
10764         _EdgesOnShape* eos = data.GetShapeEdges( edge );
10765         if ( eos && eos->SWOLType() == TopAbs_EDGE )
10766         {
10767           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
10768           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
10769             continue;
10770           helper.SetSubShape( eos->_sWOL );
10771           helper.SetElementsOnShape( true );
10772           for ( size_t z = 1; z < nn.size(); ++z )
10773             helper.AddEdge( nn[z-1], nn[z] );
10774         }
10775       }
10776
10777     } // loop on EDGE's
10778   } // loop on _SolidData's
10779
10780   return true;
10781 }