Salome HOME
Patch modules/smesh.git for Doxygen typos/grammar + misc. typos
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
48
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
59 #include <ElCLib.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
85 #include <gp_Ax1.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
88 #include <gp_Vec.hxx>
89 #include <gp_XY.hxx>
90
91 #include <cmath>
92 #include <limits>
93 #include <list>
94 #include <queue>
95 #include <string>
96
97 #ifdef _DEBUG_
98 //#define __myDEBUG
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
101 #endif
102
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
106
107 using namespace std;
108
109 //================================================================================
110 namespace VISCOUS_3D
111 {
112   typedef int TGeomID;
113
114   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
115
116   const double theMinSmoothCosin = 0.1;
117   const double theSmoothThickToElemSizeRatio = 0.3;
118   const double theMinSmoothTriaAngle = 30;
119   const double theMinSmoothQuadAngle = 45;
120
121   // what part of thickness is allowed till intersection
122   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123   const double theThickToIntersection = 1.5;
124
125   bool needSmoothing( double cosin, double tgtThick, double elemSize )
126   {
127     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
128   }
129   double getSmoothingThickness( double cosin, double elemSize )
130   {
131     return theSmoothThickToElemSizeRatio * elemSize / cosin;
132   }
133
134   /*!
135    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
137    */
138   struct _MeshOfSolid : public SMESH_ProxyMesh,
139                         public SMESH_subMeshEventListenerData
140   {
141     bool                  _n2nMapComputed;
142     SMESH_ComputeErrorPtr _warning;
143
144     _MeshOfSolid( SMESH_Mesh* mesh)
145       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
146     {
147       SMESH_ProxyMesh::setMesh( *mesh );
148     }
149
150     // returns submesh for a geom face
151     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
152     {
153       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
155     }
156     void setNode2Node(const SMDS_MeshNode*                 srcNode,
157                       const SMDS_MeshNode*                 proxyNode,
158                       const SMESH_ProxyMesh::SubMesh* subMesh)
159     {
160       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
161     }
162   };
163   //--------------------------------------------------------------------------------
164   /*!
165    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166    * It is used to clear an inferior dim sub-meshes modified by viscous layers
167    */
168   class _ShrinkShapeListener : SMESH_subMeshEventListener
169   {
170     _ShrinkShapeListener()
171       : SMESH_subMeshEventListener(/*isDeletable=*/false,
172                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
173   public:
174     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175     virtual void ProcessEvent(const int                       event,
176                               const int                       eventType,
177                               SMESH_subMesh*                  solidSM,
178                               SMESH_subMeshEventListenerData* data,
179                               const SMESH_Hypothesis*         hyp)
180     {
181       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
182       {
183         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
184       }
185     }
186   };
187   //--------------------------------------------------------------------------------
188   /*!
189    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191    * delete the data as soon as it has been used
192    */
193   class _ViscousListener : SMESH_subMeshEventListener
194   {
195     _ViscousListener():
196       SMESH_subMeshEventListener(/*isDeletable=*/false,
197                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
198     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
199   public:
200     virtual void ProcessEvent(const int                       event,
201                               const int                       eventType,
202                               SMESH_subMesh*                  subMesh,
203                               SMESH_subMeshEventListenerData* data,
204                               const SMESH_Hypothesis*         hyp)
205     {
206       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
207           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
209       {
210         // delete SMESH_ProxyMesh containing temporary faces
211         subMesh->DeleteEventListener( this );
212       }
213     }
214     // Finds or creates proxy mesh of the solid
215     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
216                                       const TopoDS_Shape& solid,
217                                       bool                toCreate=false)
218     {
219       if ( !mesh ) return 0;
220       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222       if ( !data && toCreate )
223       {
224         data = new _MeshOfSolid(mesh);
225         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226         sm->SetEventListener( Get(), data, sm );
227       }
228       return data;
229     }
230     // Removes proxy mesh of the solid
231     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
232     {
233       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
234     }
235   };
236   
237   //================================================================================
238   /*!
239    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240    * the main shape when sub-mesh of the main shape is cleared,
241    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
242    * is cleared
243    */
244   //================================================================================
245
246   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
247   {
248     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249     SMESH_subMeshEventListenerData* data =
250       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
251     if ( data )
252     {
253       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254            data->mySubMeshes.end())
255         data->mySubMeshes.push_back( sub );
256     }
257     else
258     {
259       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
261     }
262   }
263   struct _SolidData;
264   //--------------------------------------------------------------------------------
265   /*!
266    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268    * The class is used to check validity of face or volumes around a smoothed node;
269    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
270    */
271   struct _Simplex
272   {
273     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275     _Simplex(const SMDS_MeshNode* nPrev=0,
276              const SMDS_MeshNode* nNext=0,
277              const SMDS_MeshNode* nOpp=0)
278       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
280     {
281       const double M[3][3] =
282         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285       vol = ( + M[0][0] * M[1][1] * M[2][2]
286               + M[0][1] * M[1][2] * M[2][0]
287               + M[0][2] * M[1][0] * M[2][1]
288               - M[0][0] * M[1][2] * M[2][1]
289               - M[0][1] * M[1][0] * M[2][2]
290               - M[0][2] * M[1][1] * M[2][0]);
291       return vol > 1e-100;
292     }
293     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
294     {
295       SMESH_TNodeXYZ pSrc( nSrc );
296       return IsForward( &pSrc, &pTgt, vol );
297     }
298     bool IsForward(const gp_XY&         tgtUV,
299                    const SMDS_MeshNode* smoothedNode,
300                    const TopoDS_Face&   face,
301                    SMESH_MesherHelper&  helper,
302                    const double         refSign) const
303     {
304       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
307       double d = v1 ^ v2;
308       return d*refSign > 1e-100;
309     }
310     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
311     {
312       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313       if ( !_nOpp ) // triangle
314       {
315         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316         double tp2 = tp.SquareMagnitude();
317         double pn2 = pn.SquareMagnitude();
318         double nt2 = nt.SquareMagnitude();
319
320         if ( tp2 < pn2 && tp2 < nt2 )
321           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322         else if ( pn2 < nt2 )
323           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
324         else
325           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
326
327         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329         return minAngle < theMaxCos2;
330       }
331       else // quadrangle
332       {
333         SMESH_TNodeXYZ pOpp( _nOpp );
334         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335         double tp2 = tp.SquareMagnitude();
336         double po2 = po.SquareMagnitude();
337         double on2 = on.SquareMagnitude();
338         double nt2 = nt.SquareMagnitude();
339         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
343
344         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346         return minAngle < theMaxCos2;
347       }
348     }
349     bool IsNeighbour(const _Simplex& other) const
350     {
351       return _nPrev == other._nNext || _nNext == other._nPrev;
352     }
353     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354     static void GetSimplices( const SMDS_MeshNode* node,
355                               vector<_Simplex>&   simplices,
356                               const set<TGeomID>& ingnoreShapes,
357                               const _SolidData*   dataToCheckOri = 0,
358                               const bool          toSort = false);
359     static void SortSimplices(vector<_Simplex>& simplices);
360   };
361   //--------------------------------------------------------------------------------
362   /*!
363    * Structure used to take into account surface curvature while smoothing
364    */
365   struct _Curvature
366   {
367     double   _r; // radius
368     double   _k; // factor to correct node smoothed position
369     double   _h2lenRatio; // avgNormProj / (2*avgDist)
370     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
371   public:
372     static _Curvature* New( double avgNormProj, double avgDist )
373     {
374       _Curvature* c = 0;
375       if ( fabs( avgNormProj / avgDist ) > 1./200 )
376       {
377         c = new _Curvature;
378         c->_r = avgDist * avgDist / avgNormProj;
379         c->_k = avgDist * avgDist / c->_r / c->_r;
380         //c->_k = avgNormProj / c->_r;
381         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
383
384         c->_uv.SetCoord( 0., 0. );
385       }
386       return c;
387     }
388     double lenDelta(double len) const { return _k * ( _r + len ); }
389     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
390   };
391   //--------------------------------------------------------------------------------
392
393   struct _2NearEdges;
394   struct _LayerEdge;
395   struct _EdgesOnShape;
396   struct _Smoother1D;
397   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
398
399   //--------------------------------------------------------------------------------
400   /*!
401    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402    * and a node of the most internal layer (_nodes.back())
403    */
404   struct _LayerEdge
405   {
406     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
407
408     vector< const SMDS_MeshNode*> _nodes;
409
410     gp_XYZ              _normal;    // to boundary of solid
411     vector<gp_XYZ>      _pos;       // points computed during inflation
412     double              _len;       // length achieved with the last inflation step
413     double              _maxLen;    // maximal possible length
414     double              _cosin;     // of angle (_normal ^ surface)
415     double              _minAngle;  // of _simplices
416     double              _lenFactor; // to compute _len taking _cosin into account
417     int                 _flags;
418
419     // simplices connected to the source node (_nodes[0]);
420     // used for smoothing and quality check of _LayerEdge's based on the FACE
421     vector<_Simplex>    _simplices;
422     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423     PSmooFun            _smooFunction; // smoothing function
424     _Curvature*         _curvature;
425     // data for smoothing of _LayerEdge's based on the EDGE
426     _2NearEdges*        _2neibors;
427
428     enum EFlags { TO_SMOOTH       = 0x0000001,
429                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
430                   SMOOTHED        = 0x0000004, // set by this->Smooth()
431                   DIFFICULT       = 0x0000008, // near concave VERTEX
432                   ON_CONCAVE_FACE = 0x0000010,
433                   BLOCKED         = 0x0000020, // not to inflate any more
434                   INTERSECTED     = 0x0000040, // close intersection with a face found
435                   NORMAL_UPDATED  = 0x0000080,
436                   MARKED          = 0x0000100, // local usage
437                   MULTI_NORMAL    = 0x0000200, // a normal is invisible by some of surrounding faces
438                   NEAR_BOUNDARY   = 0x0000400, // is near FACE boundary forcing smooth
439                   SMOOTHED_C1     = 0x0000800, // is on _eosC1
440                   DISTORTED       = 0x0001000, // was bad before smoothing
441                   RISKY_SWOL      = 0x0002000, // SWOL is parallel to a source FACE
442                   SHRUNK          = 0x0004000, // target node reached a tgt position while shrink()
443                   UNUSED_FLAG     = 0x0100000  // to add use flags after
444     };
445     bool Is   ( int flag ) const { return _flags & flag; }
446     void Set  ( int flag ) { _flags |= flag; }
447     void Unset( int flag ) { _flags &= ~flag; }
448     std::string DumpFlags() const; // debug
449
450     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
451     bool SetNewLength2d( Handle(Geom_Surface)& surface,
452                          const TopoDS_Face&    F,
453                          _EdgesOnShape&        eos,
454                          SMESH_MesherHelper&   helper );
455     void SetDataByNeighbors( const SMDS_MeshNode* n1,
456                              const SMDS_MeshNode* n2,
457                              const _EdgesOnShape& eos,
458                              SMESH_MesherHelper&  helper);
459     void Block( _SolidData& data );
460     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
461     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
462                             const TNode2Edge&     n2eMap);
463     void SmoothPos( const vector< double >& segLen, const double tol );
464     int  GetSmoothedPos( const double tol );
465     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
466     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
467     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
468     void SmoothWoCheck();
469     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
470                       const TopoDS_Face&             F,
471                       SMESH_MesherHelper&            helper);
472     void MoveNearConcaVer( const _EdgesOnShape*    eov,
473                            const _EdgesOnShape*    eos,
474                            const int               step,
475                            vector< _LayerEdge* > & badSmooEdges);
476     bool FindIntersection( SMESH_ElementSearcher&   searcher,
477                            double &                 distance,
478                            const double&            epsilon,
479                            _EdgesOnShape&           eos,
480                            const SMDS_MeshElement** face = 0);
481     bool SegTriaInter( const gp_Ax1&        lastSegment,
482                        const gp_XYZ&        p0,
483                        const gp_XYZ&        p1,
484                        const gp_XYZ&        p2,
485                        double&              dist,
486                        const double&        epsilon) const;
487     bool SegTriaInter( const gp_Ax1&        lastSegment,
488                        const SMDS_MeshNode* n0,
489                        const SMDS_MeshNode* n1,
490                        const SMDS_MeshNode* n2,
491                        double&              dist,
492                        const double&        epsilon) const
493     { return SegTriaInter( lastSegment,
494                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
495                            dist, epsilon );
496     }
497     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
498     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
499     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
500     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
501     bool   IsOnEdge() const { return _2neibors; }
502     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
503     void   SetCosin( double cosin );
504     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
505     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
506     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
507     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
508       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
509     }
510     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
511
512     gp_XYZ smoothLaplacian();
513     gp_XYZ smoothAngular();
514     gp_XYZ smoothLengthWeighted();
515     gp_XYZ smoothCentroidal();
516     gp_XYZ smoothNefPolygon();
517
518     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
519     static const int theNbSmooFuns = FUN_NB;
520     static PSmooFun _funs[theNbSmooFuns];
521     static const char* _funNames[theNbSmooFuns+1];
522     int smooFunID( PSmooFun fun=0) const;
523   };
524   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
525                                                             &_LayerEdge::smoothLengthWeighted,
526                                                             &_LayerEdge::smoothCentroidal,
527                                                             &_LayerEdge::smoothNefPolygon,
528                                                             &_LayerEdge::smoothAngular };
529   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
530                                                          "LengthWeighted",
531                                                          "Centroidal",
532                                                          "NefPolygon",
533                                                          "Angular",
534                                                          "None"};
535   struct _LayerEdgeCmp
536   {
537     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
538     {
539       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
540       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
541     }
542   };
543   //--------------------------------------------------------------------------------
544   /*!
545    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
546    */
547   struct _halfPlane
548   {
549     gp_XY _pos, _dir, _inNorm;
550     bool IsOut( const gp_XY p, const double tol ) const
551     {
552       return _inNorm * ( p - _pos ) < -tol;
553     }
554     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
555     {
556       //const double eps = 1e-10;
557       double D = _dir.Crossed( hp._dir );
558       if ( fabs(D) < std::numeric_limits<double>::min())
559         return false;
560       gp_XY vec21 = _pos - hp._pos; 
561       double u = hp._dir.Crossed( vec21 ) / D; 
562       intPnt = _pos + _dir * u;
563       return true;
564     }
565   };
566   //--------------------------------------------------------------------------------
567   /*!
568    * Structure used to smooth a _LayerEdge based on an EDGE.
569    */
570   struct _2NearEdges
571   {
572     double               _wgt  [2]; // weights of _nodes
573     _LayerEdge*          _edges[2];
574
575      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
576     gp_XYZ*              _plnNorm;
577
578     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
579     const SMDS_MeshNode* tgtNode(bool is2nd) {
580       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
581     }
582     const SMDS_MeshNode* srcNode(bool is2nd) {
583       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
584     }
585     void reverse() {
586       std::swap( _wgt  [0], _wgt  [1] );
587       std::swap( _edges[0], _edges[1] );
588     }
589     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
590       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
591     }
592     bool include( const _LayerEdge* e ) {
593       return ( _edges[0] == e || _edges[1] == e );
594     }
595   };
596
597
598   //--------------------------------------------------------------------------------
599   /*!
600    * \brief Layers parameters got by averaging several hypotheses
601    */
602   struct AverageHyp
603   {
604     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
605       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
606     {
607       Add( hyp );
608     }
609     void Add( const StdMeshers_ViscousLayers* hyp )
610     {
611       if ( hyp )
612       {
613         _nbHyps++;
614         _nbLayers       = hyp->GetNumberLayers();
615         //_thickness     += hyp->GetTotalThickness();
616         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
617         _stretchFactor += hyp->GetStretchFactor();
618         _method         = hyp->GetMethod();
619       }
620     }
621     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
622     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
623     int    GetNumberLayers()   const { return _nbLayers; }
624     int    GetMethod()         const { return _method; }
625
626     bool   UseSurfaceNormal()  const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   ToSmooth()          const
629     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
630     bool   IsOffsetMethod()    const
631     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
632
633   private:
634     int     _nbLayers, _nbHyps, _method;
635     double  _thickness, _stretchFactor;
636   };
637
638   //--------------------------------------------------------------------------------
639   /*!
640    * \brief _LayerEdge's on a shape and other shape data
641    */
642   struct _EdgesOnShape
643   {
644     vector< _LayerEdge* > _edges;
645
646     TopoDS_Shape          _shape;
647     TGeomID               _shapeID;
648     SMESH_subMesh *       _subMesh;
649     // face or edge w/o layer along or near which _edges are inflated
650     TopoDS_Shape          _sWOL;
651     bool                  _isRegularSWOL; // w/o singularities
652     // averaged StdMeshers_ViscousLayers parameters
653     AverageHyp            _hyp;
654     bool                  _toSmooth;
655     _Smoother1D*          _edgeSmoother;
656     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
657     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
658
659     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
660     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
661
662     Handle(ShapeAnalysis_Surface) _offsetSurf;
663     _LayerEdge*                   _edgeForOffset;
664
665     _SolidData*            _data; // parent SOLID
666
667     TopAbs_ShapeEnum ShapeType() const
668     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
669     TopAbs_ShapeEnum SWOLType() const
670     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
671     bool             HasC1( const _EdgesOnShape* other ) const
672     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
673     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
674     _SolidData&      GetData() const { return *_data; }
675
676     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
677   };
678
679   //--------------------------------------------------------------------------------
680   /*!
681    * \brief Convex FACE whose radius of curvature is less than the thickness of 
682    *        layers. It is used to detect distortion of prisms based on a convex
683    *        FACE and to update normals to enable further increasing the thickness
684    */
685   struct _ConvexFace
686   {
687     TopoDS_Face                     _face;
688
689     // edges whose _simplices are used to detect prism distortion
690     vector< _LayerEdge* >           _simplexTestEdges;
691
692     // map a sub-shape to _SolidData::_edgesOnShape
693     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
694
695     bool                            _normalsFixed;
696
697     bool GetCenterOfCurvature( _LayerEdge*         ledge,
698                                BRepLProp_SLProps&  surfProp,
699                                SMESH_MesherHelper& helper,
700                                gp_Pnt &            center ) const;
701     bool CheckPrisms() const;
702   };
703
704   //--------------------------------------------------------------------------------
705   /*!
706    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
707    *        at inflation up to the full thickness. A detected collision
708    *        is fixed in updateNormals()
709    */
710   struct _CollisionEdges
711   {
712     _LayerEdge*           _edge;
713     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
714     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
715     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
716   };
717
718   //--------------------------------------------------------------------------------
719   /*!
720    * \brief Data of a SOLID
721    */
722   struct _SolidData
723   {
724     typedef const StdMeshers_ViscousLayers* THyp;
725     TopoDS_Shape                    _solid;
726     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
727     TGeomID                         _index; // SOLID id
728     _MeshOfSolid*                   _proxyMesh;
729     list< THyp >                    _hyps;
730     list< TopoDS_Shape >            _hypShapes;
731     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
732     set< TGeomID >                  _reversedFaceIds;
733     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
734
735     double                          _stepSize, _stepSizeCoeff, _geomSize;
736     const SMDS_MeshNode*            _stepSizeNodes[2];
737
738     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
739
740     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
741     map< TGeomID, TNode2Edge* >     _s2neMap;
742     // _LayerEdge's with underlying shapes
743     vector< _EdgesOnShape >         _edgesOnShape;
744
745     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
746     //        layers and a FACE w/o layers
747     // value: the shape (FACE or EDGE) to shrink mesh on.
748     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
749     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
750
751     // Convex FACEs whose radius of curvature is less than the thickness of layers
752     map< TGeomID, _ConvexFace >      _convexFaces;
753
754     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
755     // the adjacent SOLID
756     set< TGeomID >                   _noShrinkShapes;
757
758     int                              _nbShapesToSmooth;
759
760     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
761
762     vector< _CollisionEdges >        _collisionEdges;
763     set< TGeomID >                   _concaveFaces;
764
765     double                           _maxThickness; // of all _hyps
766     double                           _minThickness; // of all _hyps
767
768     double                           _epsilon; // precision for SegTriaInter()
769
770     SMESH_MesherHelper*              _helper;
771
772     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
773                _MeshOfSolid*       m=0)
774       :_solid(s), _proxyMesh(m), _helper(0) {}
775     ~_SolidData();
776
777     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
778     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
779
780     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
781       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
782       return id2face == _convexFaces.end() ? 0 : & id2face->second;
783     }
784     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
785     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
786     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
787     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
788
789     SMESH_MesherHelper& GetHelper() const { return *_helper; }
790
791     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
792       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
793         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
794           _edgesOnShape[i]._edges[j]->Unset( flag );
795     }
796     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
797                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
798
799     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
800   };
801   //--------------------------------------------------------------------------------
802   /*!
803    * \brief Offset plane used in getNormalByOffset()
804    */
805   struct _OffsetPlane
806   {
807     gp_Pln _plane;
808     int    _faceIndex;
809     int    _faceIndexNext[2];
810     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
811     bool   _isLineOK[2];
812     _OffsetPlane() {
813       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
814     }
815     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
816                                     const TopoDS_Edge&   E,
817                                     const TopoDS_Vertex& V );
818     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
819     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
820   };
821   //--------------------------------------------------------------------------------
822   /*!
823    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
824    */
825   struct _CentralCurveOnEdge
826   {
827     bool                  _isDegenerated;
828     vector< gp_Pnt >      _curvaCenters;
829     vector< _LayerEdge* > _ledges;
830     vector< gp_XYZ >      _normals; // new normal for each of _ledges
831     vector< double >      _segLength2;
832
833     TopoDS_Edge           _edge;
834     TopoDS_Face           _adjFace;
835     bool                  _adjFaceToSmooth;
836
837     void Append( const gp_Pnt& center, _LayerEdge* ledge )
838     {
839       if ( _curvaCenters.size() > 0 )
840         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
841       _curvaCenters.push_back( center );
842       _ledges.push_back( ledge );
843       _normals.push_back( ledge->_normal );
844     }
845     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
846     void SetShapes( const TopoDS_Edge&  edge,
847                     const _ConvexFace&  convFace,
848                     _SolidData&         data,
849                     SMESH_MesherHelper& helper);
850   };
851   //--------------------------------------------------------------------------------
852   /*!
853    * \brief Data of node on a shrinked FACE
854    */
855   struct _SmoothNode
856   {
857     const SMDS_MeshNode*         _node;
858     vector<_Simplex>             _simplices; // for quality check
859
860     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
861
862     bool Smooth(int&                  badNb,
863                 Handle(Geom_Surface)& surface,
864                 SMESH_MesherHelper&   helper,
865                 const double          refSign,
866                 SmoothType            how,
867                 bool                  set3D);
868
869     gp_XY computeAngularPos(vector<gp_XY>& uv,
870                             const gp_XY&   uvToFix,
871                             const double   refSign );
872   };
873   //--------------------------------------------------------------------------------
874   /*!
875    * \brief Builder of viscous layers
876    */
877   class _ViscousBuilder
878   {
879   public:
880     _ViscousBuilder();
881     // does it's job
882     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
883                                   const TopoDS_Shape& shape);
884     // check validity of hypotheses
885     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
886                                            const TopoDS_Shape& shape );
887
888     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
889     void RestoreListeners();
890
891     // computes SMESH_ProxyMesh::SubMesh::_n2n;
892     bool MakeN2NMap( _MeshOfSolid* pm );
893
894   private:
895
896     bool findSolidsWithLayers();
897     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
898     bool findFacesWithLayers(const bool onlyWith=false);
899     void getIgnoreFaces(const TopoDS_Shape&             solid,
900                         const StdMeshers_ViscousLayers* hyp,
901                         const TopoDS_Shape&             hypShape,
902                         set<TGeomID>&                   ignoreFaces);
903     bool makeLayer(_SolidData& data);
904     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
905     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
906                       SMESH_MesherHelper& helper, _SolidData& data);
907     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
908                          const TopoDS_Face&   face,
909                          SMESH_MesherHelper&  helper,
910                          bool&                isOK,
911                          bool                 shiftInside=false);
912     bool getFaceNormalAtSingularity(const gp_XY&        uv,
913                                     const TopoDS_Face&  face,
914                                     SMESH_MesherHelper& helper,
915                                     gp_Dir&             normal );
916     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
917     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
918                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
919                               int                              nbFaces,
920                               bool                             lastNoOffset = false);
921     bool findNeiborsOnEdge(const _LayerEdge*     edge,
922                            const SMDS_MeshNode*& n1,
923                            const SMDS_MeshNode*& n2,
924                            _EdgesOnShape&        eos,
925                            _SolidData&           data);
926     void findSimplexTestEdges( _SolidData&                    data,
927                                vector< vector<_LayerEdge*> >& edgesByGeom);
928     void computeGeomSize( _SolidData& data );
929     bool findShapesToSmooth( _SolidData& data);
930     void limitStepSizeByCurvature( _SolidData&  data );
931     void limitStepSize( _SolidData&             data,
932                         const SMDS_MeshElement* face,
933                         const _LayerEdge*       maxCosinEdge );
934     void limitStepSize( _SolidData& data, const double minSize);
935     bool inflate(_SolidData& data);
936     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
937     int  invalidateBadSmooth( _SolidData&               data,
938                               SMESH_MesherHelper&       helper,
939                               vector< _LayerEdge* >&    badSmooEdges,
940                               vector< _EdgesOnShape* >& eosC1,
941                               const int                 infStep );
942     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
943     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
944                              vector< _EdgesOnShape* >& eosC1,
945                              int smooStep=0, bool moveAll=false );
946     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
947     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
948     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
949                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
950                                  SMESH_MesherHelper& helper );
951     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
952     bool updateNormalsOfConvexFaces( _SolidData&         data,
953                                      SMESH_MesherHelper& helper,
954                                      int                 stepNb );
955     void updateNormalsOfC1Vertices( _SolidData& data );
956     bool updateNormalsOfSmoothed( _SolidData&         data,
957                                   SMESH_MesherHelper& helper,
958                                   const int           nbSteps,
959                                   const double        stepSize );
960     bool isNewNormalOk( _SolidData&   data,
961                         _LayerEdge&   edge,
962                         const gp_XYZ& newNormal);
963     bool refine(_SolidData& data);
964     bool shrink(_SolidData& data);
965     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
966                               SMESH_MesherHelper& helper,
967                               const SMESHDS_SubMesh* faceSubMesh );
968     void restoreNoShrink( _LayerEdge& edge ) const;
969     void fixBadFaces(const TopoDS_Face&          F,
970                      SMESH_MesherHelper&         helper,
971                      const bool                  is2D,
972                      const int                   step,
973                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
974     bool addBoundaryElements(_SolidData& data);
975
976     bool error( const string& text, int solidID=-1 );
977     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
978
979     // debug
980     void makeGroupOfLE();
981
982     SMESH_Mesh*                _mesh;
983     SMESH_ComputeErrorPtr      _error;
984
985     vector<                    _SolidData >  _sdVec;
986     TopTools_IndexedMapOfShape _solids; // to find _SolidData by a solid
987     TopTools_MapOfShape        _shrinkedFaces;
988
989     int                        _tmpFaceID;
990   };
991   //--------------------------------------------------------------------------------
992   /*!
993    * \brief Shrinker of nodes on the EDGE
994    */
995   class _Shrinker1D
996   {
997     TopoDS_Edge                   _geomEdge;
998     vector<double>                _initU;
999     vector<double>                _normPar;
1000     vector<const SMDS_MeshNode*>  _nodes;
1001     const _LayerEdge*             _edges[2];
1002     bool                          _done;
1003   public:
1004     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1005     void Compute(bool set3D, SMESH_MesherHelper& helper);
1006     void RestoreParams();
1007     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1008     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1009     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1010     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1011     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1012     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1013   };
1014   //--------------------------------------------------------------------------------
1015   /*!
1016    * \brief Smoother of _LayerEdge's on EDGE.
1017    */
1018   struct _Smoother1D
1019   {
1020     struct OffPnt // point of the offsetted EDGE
1021     {
1022       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1023       double      _len;    // length reached at previous inflation step
1024       double      _param;  // on EDGE
1025       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1026       gp_XYZ      _edgeDir;// EDGE tangent at _param
1027       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1028     };
1029     vector< OffPnt >   _offPoints;
1030     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1031     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1032     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1033     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1034     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1035     _EdgesOnShape&     _eos;
1036     double             _curveLen; // length of the EDGE
1037
1038     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1039                                               _EdgesOnShape&      eos,
1040                                               SMESH_MesherHelper& helper);
1041
1042     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1043                  _EdgesOnShape&     eos )
1044       : _anaCurve( curveForSmooth ), _eos( eos )
1045     {
1046     }
1047     bool Perform(_SolidData&                    data,
1048                  Handle(ShapeAnalysis_Surface)& surface,
1049                  const TopoDS_Face&             F,
1050                  SMESH_MesherHelper&            helper )
1051     {
1052       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1053         prepare( data );
1054
1055       if ( isAnalytic() )
1056         return smoothAnalyticEdge( data, surface, F, helper );
1057       else
1058         return smoothComplexEdge ( data, surface, F, helper );
1059     }
1060     void prepare(_SolidData& data );
1061
1062     bool smoothAnalyticEdge( _SolidData&                    data,
1063                              Handle(ShapeAnalysis_Surface)& surface,
1064                              const TopoDS_Face&             F,
1065                              SMESH_MesherHelper&            helper);
1066
1067     bool smoothComplexEdge( _SolidData&                    data,
1068                             Handle(ShapeAnalysis_Surface)& surface,
1069                             const TopoDS_Face&             F,
1070                             SMESH_MesherHelper&            helper);
1071
1072     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1073                             const gp_XYZ&  edgeDir);
1074
1075     _LayerEdge* getLEdgeOnV( bool is2nd )
1076     {
1077       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1078     }
1079     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1080   };
1081   //--------------------------------------------------------------------------------
1082   /*!
1083    * \brief Class of temporary mesh face.
1084    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1085    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1086    */
1087   struct _TmpMeshFace : public SMDS_MeshElement
1088   {
1089     vector<const SMDS_MeshNode* > _nn;
1090     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1091                   int id, int faceID=-1, int idInFace=-1):
1092       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1093     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1094     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1095     virtual vtkIdType GetVtkType() const                      { return -1; }
1096     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1097     virtual SMDSAbs_GeometryType GetGeomType() const
1098     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1099     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1100     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1101   };
1102   //--------------------------------------------------------------------------------
1103   /*!
1104    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1105    */
1106   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1107   {
1108     _LayerEdge *_le1, *_le2;
1109     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1110       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1111     {
1112       _nn[0]=_le1->_nodes[0];
1113       _nn[1]=_le1->_nodes.back();
1114       _nn[2]=_le2->_nodes.back();
1115       _nn[3]=_le2->_nodes[0];
1116     }
1117     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1118     {
1119       SMESH_TNodeXYZ p0s( _nn[0] );
1120       SMESH_TNodeXYZ p0t( _nn[1] );
1121       SMESH_TNodeXYZ p1t( _nn[2] );
1122       SMESH_TNodeXYZ p1s( _nn[3] );
1123       gp_XYZ  v0 = p0t - p0s;
1124       gp_XYZ  v1 = p1t - p1s;
1125       gp_XYZ v01 = p1s - p0s;
1126       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1127       gp_XYZ   d = v01 ^ n;
1128       d.Normalize();
1129       return d;
1130     }
1131     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1132     {
1133       _nn[0]=le1->_nodes[0];
1134       _nn[1]=le1->_nodes.back();
1135       _nn[2]=le2->_nodes.back();
1136       _nn[3]=le2->_nodes[0];
1137       return GetDir();
1138     }
1139   };
1140   //--------------------------------------------------------------------------------
1141   /*!
1142    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1143    * \warning Location of a surface is ignored
1144    */
1145   struct _NodeCoordHelper
1146   {
1147     SMESH_MesherHelper&        _helper;
1148     const TopoDS_Face&         _face;
1149     Handle(Geom_Surface)       _surface;
1150     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1151
1152     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1153       : _helper( helper ), _face( F )
1154     {
1155       if ( is2D )
1156       {
1157         TopLoc_Location loc;
1158         _surface = BRep_Tool::Surface( _face, loc );
1159       }
1160       if ( _surface.IsNull() )
1161         _fun = & _NodeCoordHelper::direct;
1162       else
1163         _fun = & _NodeCoordHelper::byUV;
1164     }
1165     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1166
1167   private:
1168     gp_XYZ direct(const SMDS_MeshNode* n) const
1169     {
1170       return SMESH_TNodeXYZ( n );
1171     }
1172     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1173     {
1174       gp_XY uv = _helper.GetNodeUV( _face, n );
1175       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1176     }
1177   };
1178
1179   //================================================================================
1180   /*!
1181    * \brief Check angle between vectors 
1182    */
1183   //================================================================================
1184
1185   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1186   {
1187     double dot = v1 * v2; // cos * |v1| * |v2|
1188     double l1  = v1.SquareMagnitude();
1189     double l2  = v2.SquareMagnitude();
1190     return (( dot * cos >= 0 ) && 
1191             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1192   }
1193
1194 } // namespace VISCOUS_3D
1195
1196
1197
1198 //================================================================================
1199 // StdMeshers_ViscousLayers hypothesis
1200 //
1201 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1202   :SMESH_Hypothesis(hypId, studyId, gen),
1203    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1204    _method( SURF_OFFSET_SMOOTH )
1205 {
1206   _name = StdMeshers_ViscousLayers::GetHypType();
1207   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1210 {
1211   if ( faceIds != _shapeIds )
1212     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1213   if ( _isToIgnoreShapes != toIgnore )
1214     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1215 } // --------------------------------------------------------------------------------
1216 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1217 {
1218   if ( thickness != _thickness )
1219     _thickness = thickness, NotifySubMeshesHypothesisModification();
1220 } // --------------------------------------------------------------------------------
1221 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1222 {
1223   if ( _nbLayers != nb )
1224     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1225 } // --------------------------------------------------------------------------------
1226 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1227 {
1228   if ( _stretchFactor != factor )
1229     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1230 } // --------------------------------------------------------------------------------
1231 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1232 {
1233   if ( _method != method )
1234     _method = method, NotifySubMeshesHypothesisModification();
1235 } // --------------------------------------------------------------------------------
1236 SMESH_ProxyMesh::Ptr
1237 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1238                                   const TopoDS_Shape& theShape,
1239                                   const bool          toMakeN2NMap) const
1240 {
1241   using namespace VISCOUS_3D;
1242   _ViscousBuilder builder;
1243   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1244   if ( err && !err->IsOK() )
1245     return SMESH_ProxyMesh::Ptr();
1246
1247   vector<SMESH_ProxyMesh::Ptr> components;
1248   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1249   for ( ; exp.More(); exp.Next() )
1250   {
1251     if ( _MeshOfSolid* pm =
1252          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1253     {
1254       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1255         if ( !builder.MakeN2NMap( pm ))
1256           return SMESH_ProxyMesh::Ptr();
1257       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1258       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1259
1260       if ( pm->_warning && !pm->_warning->IsOK() )
1261       {
1262         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1263         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1264         if ( !smError || smError->IsOK() )
1265           smError = pm->_warning;
1266       }
1267     }
1268     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1269   }
1270   switch ( components.size() )
1271   {
1272   case 0: break;
1273
1274   case 1: return components[0];
1275
1276   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1277   }
1278   return SMESH_ProxyMesh::Ptr();
1279 } // --------------------------------------------------------------------------------
1280 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1281 {
1282   save << " " << _nbLayers
1283        << " " << _thickness
1284        << " " << _stretchFactor
1285        << " " << _shapeIds.size();
1286   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1287     save << " " << _shapeIds[i];
1288   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1289   save << " " << _method;
1290   return save;
1291 } // --------------------------------------------------------------------------------
1292 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1293 {
1294   int nbFaces, faceID, shapeToTreat, method;
1295   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1296   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1297     _shapeIds.push_back( faceID );
1298   if ( load >> shapeToTreat ) {
1299     _isToIgnoreShapes = !shapeToTreat;
1300     if ( load >> method )
1301       _method = (ExtrusionMethod) method;
1302   }
1303   else {
1304     _isToIgnoreShapes = true; // old behavior
1305   }
1306   return load;
1307 } // --------------------------------------------------------------------------------
1308 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1309                                                    const TopoDS_Shape& theShape)
1310 {
1311   // TODO
1312   return false;
1313 } // --------------------------------------------------------------------------------
1314 SMESH_ComputeErrorPtr
1315 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1316                                           const TopoDS_Shape&                  theShape,
1317                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1318 {
1319   VISCOUS_3D::_ViscousBuilder builder;
1320   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1321   if ( err && !err->IsOK() )
1322     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1323   else
1324     theStatus = SMESH_Hypothesis::HYP_OK;
1325
1326   return err;
1327 }
1328 // --------------------------------------------------------------------------------
1329 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1330 {
1331   bool isIn =
1332     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1333   return IsToIgnoreShapes() ? !isIn : isIn;
1334 }
1335 // END StdMeshers_ViscousLayers hypothesis
1336 //================================================================================
1337
1338 namespace VISCOUS_3D
1339 {
1340   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1341   {
1342     gp_Vec dir;
1343     double f,l;
1344     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1345     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1346     gp_Pnt p = BRep_Tool::Pnt( fromV );
1347     double distF = p.SquareDistance( c->Value( f ));
1348     double distL = p.SquareDistance( c->Value( l ));
1349     c->D1(( distF < distL ? f : l), p, dir );
1350     if ( distL < distF ) dir.Reverse();
1351     return dir.XYZ();
1352   }
1353   //--------------------------------------------------------------------------------
1354   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1355                      SMESH_MesherHelper& helper)
1356   {
1357     gp_Vec dir;
1358     double f,l; gp_Pnt p;
1359     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1360     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1361     double u = helper.GetNodeU( E, atNode );
1362     c->D1( u, p, dir );
1363     return dir.XYZ();
1364   }
1365   //--------------------------------------------------------------------------------
1366   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1367                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1368                      double* cosin=0);
1369   //--------------------------------------------------------------------------------
1370   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1371                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1372   {
1373     double f,l;
1374     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1375     if ( c.IsNull() )
1376     {
1377       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1378       return getFaceDir( F, v, node, helper, ok );
1379     }
1380     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1381     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1382     gp_Pnt p; gp_Vec du, dv, norm;
1383     surface->D1( uv.X(),uv.Y(), p, du,dv );
1384     norm = du ^ dv;
1385
1386     double u = helper.GetNodeU( fromE, node, 0, &ok );
1387     c->D1( u, p, du );
1388     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1389     if ( o == TopAbs_REVERSED )
1390       du.Reverse();
1391
1392     gp_Vec dir = norm ^ du;
1393
1394     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1395          helper.IsClosedEdge( fromE ))
1396     {
1397       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1398       else                        c->D1( f, p, dv );
1399       if ( o == TopAbs_REVERSED )
1400         dv.Reverse();
1401       gp_Vec dir2 = norm ^ dv;
1402       dir = dir.Normalized() + dir2.Normalized();
1403     }
1404     return dir.XYZ();
1405   }
1406   //--------------------------------------------------------------------------------
1407   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1408                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1409                      bool& ok, double* cosin)
1410   {
1411     TopoDS_Face faceFrw = F;
1412     faceFrw.Orientation( TopAbs_FORWARD );
1413     //double f,l; TopLoc_Location loc;
1414     TopoDS_Edge edges[2]; // sharing a vertex
1415     size_t nbEdges = 0;
1416     {
1417       TopoDS_Vertex VV[2];
1418       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1419       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1420       {
1421         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1422         if ( SMESH_Algo::isDegenerated( e )) continue;
1423         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1424         if ( VV[1].IsSame( fromV )) {
1425           nbEdges += edges[ 0 ].IsNull();
1426           edges[ 0 ] = e;
1427         }
1428         else if ( VV[0].IsSame( fromV )) {
1429           nbEdges += edges[ 1 ].IsNull();
1430           edges[ 1 ] = e;
1431         }
1432       }
1433     }
1434     gp_XYZ dir(0,0,0), edgeDir[2];
1435     if ( nbEdges == 2 )
1436     {
1437       // get dirs of edges going fromV
1438       ok = true;
1439       for ( size_t i = 0; i < nbEdges && ok; ++i )
1440       {
1441         edgeDir[i] = getEdgeDir( edges[i], fromV );
1442         double size2 = edgeDir[i].SquareModulus();
1443         if (( ok = size2 > numeric_limits<double>::min() ))
1444           edgeDir[i] /= sqrt( size2 );
1445       }
1446       if ( !ok ) return dir;
1447
1448       // get angle between the 2 edges
1449       gp_Vec faceNormal;
1450       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1451       if ( Abs( angle ) < 5 * M_PI/180 )
1452       {
1453         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1454       }
1455       else
1456       {
1457         dir = edgeDir[0] + edgeDir[1];
1458         if ( angle < 0 )
1459           dir.Reverse();
1460       }
1461       if ( cosin ) {
1462         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1463         *cosin = Cos( angle );
1464       }
1465     }
1466     else if ( nbEdges == 1 )
1467     {
1468       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1469       if ( cosin ) *cosin = 1.;
1470     }
1471     else
1472     {
1473       ok = false;
1474     }
1475
1476     return dir;
1477   }
1478
1479   //================================================================================
1480   /*!
1481    * \brief Finds concave VERTEXes of a FACE
1482    */
1483   //================================================================================
1484
1485   bool getConcaveVertices( const TopoDS_Face&  F,
1486                            SMESH_MesherHelper& helper,
1487                            set< TGeomID >*     vertices = 0)
1488   {
1489     // check angles at VERTEXes
1490     TError error;
1491     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1492     for ( size_t iW = 0; iW < wires.size(); ++iW )
1493     {
1494       const int nbEdges = wires[iW]->NbEdges();
1495       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1496         continue;
1497       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1498       {
1499         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1500         int iE2 = ( iE1 + 1 ) % nbEdges;
1501         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1502           iE2 = ( iE2 + 1 ) % nbEdges;
1503         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1504         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1505                                         wires[iW]->Edge( iE2 ), F, V );
1506         if ( angle < -5. * M_PI / 180. )
1507         {
1508           if ( !vertices )
1509             return true;
1510           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1511         }
1512       }
1513     }
1514     return vertices ? !vertices->empty() : false;
1515   }
1516
1517   //================================================================================
1518   /*!
1519    * \brief Returns true if a FACE is bound by a concave EDGE
1520    */
1521   //================================================================================
1522
1523   bool isConcave( const TopoDS_Face&  F,
1524                   SMESH_MesherHelper& helper,
1525                   set< TGeomID >*     vertices = 0 )
1526   {
1527     bool isConcv = false;
1528     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1529     //   return true;
1530     gp_Vec2d drv1, drv2;
1531     gp_Pnt2d p;
1532     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1533     for ( ; eExp.More(); eExp.Next() )
1534     {
1535       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1536       if ( SMESH_Algo::isDegenerated( E )) continue;
1537       // check if 2D curve is concave
1538       BRepAdaptor_Curve2d curve( E, F );
1539       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1540       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1541       curve.Intervals( intervals, GeomAbs_C2 );
1542       bool isConvex = true;
1543       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1544       {
1545         double u1 = intervals( i );
1546         double u2 = intervals( i+1 );
1547         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1548         double cross = drv1 ^ drv2;
1549         if ( E.Orientation() == TopAbs_REVERSED )
1550           cross = -cross;
1551         isConvex = ( cross > -1e-9 ); // 0.1 );
1552       }
1553       if ( !isConvex )
1554       {
1555         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1556         isConcv = true;
1557         if ( vertices )
1558           break;
1559         else
1560           return true;
1561       }
1562     }
1563
1564     // check angles at VERTEXes
1565     if ( getConcaveVertices( F, helper, vertices ))
1566       isConcv = true;
1567
1568     return isConcv;
1569   }
1570
1571   //================================================================================
1572   /*!
1573    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1574    *  \param [in] face - the mesh face to treat
1575    *  \param [in] nodeOnEdge - a node on the EDGE
1576    *  \param [out] faceSize - the computed distance
1577    *  \return bool - true if faceSize computed
1578    */
1579   //================================================================================
1580
1581   bool getDistFromEdge( const SMDS_MeshElement* face,
1582                         const SMDS_MeshNode*    nodeOnEdge,
1583                         double &                faceSize )
1584   {
1585     faceSize = Precision::Infinite();
1586     bool done = false;
1587
1588     int nbN  = face->NbCornerNodes();
1589     int iOnE = face->GetNodeIndex( nodeOnEdge );
1590     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1591                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1592     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1593                                       face->GetNode( iNext[1] ) };
1594     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1595     double segLen = -1.;
1596     // look for two neighbor not in-FACE nodes of face
1597     for ( int i = 0; i < 2; ++i )
1598     {
1599       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1600            nNext[i]->GetID() < nodeOnEdge->GetID() )
1601       {
1602         // look for an in-FACE node
1603         for ( int iN = 0; iN < nbN; ++iN )
1604         {
1605           if ( iN == iOnE || iN == iNext[i] )
1606             continue;
1607           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1608           gp_XYZ v = pInFace - segEnd;
1609           if ( segLen < 0 )
1610           {
1611             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1612             segLen = segVec.Modulus();
1613           }
1614           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1615           faceSize = Min( faceSize, distToSeg );
1616           done = true;
1617         }
1618         segLen = -1;
1619       }
1620     }
1621     return done;
1622   }
1623   //================================================================================
1624   /*!
1625    * \brief Return direction of axis or revolution of a surface
1626    */
1627   //================================================================================
1628
1629   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1630                           gp_Dir &                 axis )
1631   {
1632     switch ( surface.GetType() ) {
1633     case GeomAbs_Cone:
1634     {
1635       gp_Cone cone = surface.Cone();
1636       axis = cone.Axis().Direction();
1637       break;
1638     }
1639     case GeomAbs_Sphere:
1640     {
1641       gp_Sphere sphere = surface.Sphere();
1642       axis = sphere.Position().Direction();
1643       break;
1644     }
1645     case GeomAbs_SurfaceOfRevolution:
1646     {
1647       axis = surface.AxeOfRevolution().Direction();
1648       break;
1649     }
1650     //case GeomAbs_SurfaceOfExtrusion:
1651     case GeomAbs_OffsetSurface:
1652     {
1653       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1654       return getRovolutionAxis( base->Surface(), axis );
1655     }
1656     default: return false;
1657     }
1658     return true;
1659   }
1660
1661   //--------------------------------------------------------------------------------
1662   // DEBUG. Dump intermediate node positions into a python script
1663   // HOWTO use: run python commands written in a console to see
1664   //  construction steps of viscous layers
1665 #ifdef __myDEBUG
1666   ofstream* py;
1667   int       theNbPyFunc;
1668   struct PyDump {
1669     PyDump(SMESH_Mesh& m) {
1670       int tag = 3 + m.GetId();
1671       const char* fname = "/tmp/viscous.py";
1672       cout << "execfile('"<<fname<<"')"<<endl;
1673       py = new ofstream(fname);
1674       *py << "import SMESH" << endl
1675           << "from salome.smesh import smeshBuilder" << endl
1676           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1677           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1678           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1679       theNbPyFunc = 0;
1680     }
1681     void Finish() {
1682       if (py) {
1683         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1684           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1685         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1686           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1687       }
1688       delete py; py=0;
1689     }
1690     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1691   };
1692 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1693 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1694 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1695 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1696   void _dumpFunction(const string& fun, int ln)
1697   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1698   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1699   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1700                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1701   void _dumpCmd(const string& txt, int ln)
1702   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1703   void dumpFunctionEnd()
1704   { if (py) *py<< "  return"<< endl; }
1705   void dumpChangeNodes( const SMDS_MeshElement* f )
1706   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1707       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1708       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1709 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1710
1711 #else
1712
1713   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1714 #define dumpFunction(f) f
1715 #define dumpMove(n)
1716 #define dumpMoveComm(n,txt)
1717 #define dumpCmd(txt)
1718 #define dumpFunctionEnd()
1719 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1720 #define debugMsg( txt ) {}
1721
1722 #endif
1723 }
1724
1725 using namespace VISCOUS_3D;
1726
1727 //================================================================================
1728 /*!
1729  * \brief Constructor of _ViscousBuilder
1730  */
1731 //================================================================================
1732
1733 _ViscousBuilder::_ViscousBuilder()
1734 {
1735   _error = SMESH_ComputeError::New(COMPERR_OK);
1736   _tmpFaceID = 0;
1737 }
1738
1739 //================================================================================
1740 /*!
1741  * \brief Stores error description and returns false
1742  */
1743 //================================================================================
1744
1745 bool _ViscousBuilder::error(const string& text, int solidId )
1746 {
1747   const string prefix = string("Viscous layers builder: ");
1748   _error->myName    = COMPERR_ALGO_FAILED;
1749   _error->myComment = prefix + text;
1750   if ( _mesh )
1751   {
1752     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1753     if ( !sm && !_sdVec.empty() )
1754       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1755     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1756     {
1757       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1758       if ( smError && smError->myAlgo )
1759         _error->myAlgo = smError->myAlgo;
1760       smError = _error;
1761       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1762     }
1763     // set KO to all solids
1764     for ( size_t i = 0; i < _sdVec.size(); ++i )
1765     {
1766       if ( _sdVec[i]._index == solidId )
1767         continue;
1768       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1769       if ( !sm->IsEmpty() )
1770         continue;
1771       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1772       if ( !smError || smError->IsOK() )
1773       {
1774         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1775         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1776       }
1777     }
1778   }
1779   makeGroupOfLE(); // debug
1780
1781   return false;
1782 }
1783
1784 //================================================================================
1785 /*!
1786  * \brief At study restoration, restore event listeners used to clear an inferior
1787  *  dim sub-mesh modified by viscous layers
1788  */
1789 //================================================================================
1790
1791 void _ViscousBuilder::RestoreListeners()
1792 {
1793   // TODO
1794 }
1795
1796 //================================================================================
1797 /*!
1798  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1799  */
1800 //================================================================================
1801
1802 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1803 {
1804   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1805   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1806   for ( ; fExp.More(); fExp.Next() )
1807   {
1808     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1809     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1810
1811     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1812       continue;
1813     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1814       continue;
1815
1816     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1817       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1818
1819     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1820     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1821     while( prxIt->more() )
1822     {
1823       const SMDS_MeshElement* fSrc = srcIt->next();
1824       const SMDS_MeshElement* fPrx = prxIt->next();
1825       if ( fSrc->NbNodes() != fPrx->NbNodes())
1826         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1827       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1828         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1829     }
1830   }
1831   pm->_n2nMapComputed = true;
1832   return true;
1833 }
1834
1835 //================================================================================
1836 /*!
1837  * \brief Does its job
1838  */
1839 //================================================================================
1840
1841 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1842                                                const TopoDS_Shape& theShape)
1843 {
1844   _mesh = & theMesh;
1845
1846   // check if proxy mesh already computed
1847   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1848   if ( !exp.More() )
1849     return error("No SOLID's in theShape"), _error;
1850
1851   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1852     return SMESH_ComputeErrorPtr(); // everything already computed
1853
1854   PyDump debugDump( theMesh );
1855
1856   // TODO: ignore already computed SOLIDs 
1857   if ( !findSolidsWithLayers())
1858     return _error;
1859
1860   if ( !findFacesWithLayers() )
1861     return _error;
1862
1863   for ( size_t i = 0; i < _sdVec.size(); ++i )
1864   {
1865     size_t iSD = 0;
1866     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1867       if ( _sdVec[iSD]._before.IsEmpty() &&
1868            _sdVec[iSD]._n2eMap.empty() )
1869         break;
1870
1871     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1872       return _error;
1873
1874     if ( _sdVec[iSD]._n2eMap.size() == 0 )
1875       continue;
1876     
1877     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
1878       return _error;
1879
1880     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
1881       return _error;
1882
1883     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
1884       return _error;
1885
1886     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
1887
1888     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
1889     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
1890       _sdVec[iSD]._before.Remove( solid );
1891   }
1892
1893   makeGroupOfLE(); // debug
1894   debugDump.Finish();
1895
1896   return _error;
1897 }
1898
1899 //================================================================================
1900 /*!
1901  * \brief Check validity of hypotheses
1902  */
1903 //================================================================================
1904
1905 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1906                                                         const TopoDS_Shape& shape )
1907 {
1908   _mesh = & mesh;
1909
1910   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1911     return SMESH_ComputeErrorPtr(); // everything already computed
1912
1913
1914   findSolidsWithLayers();
1915   bool ok = findFacesWithLayers( true );
1916
1917   // remove _MeshOfSolid's of _SolidData's
1918   for ( size_t i = 0; i < _sdVec.size(); ++i )
1919     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1920
1921   if ( !ok )
1922     return _error;
1923
1924   return SMESH_ComputeErrorPtr();
1925 }
1926
1927 //================================================================================
1928 /*!
1929  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1930  */
1931 //================================================================================
1932
1933 bool _ViscousBuilder::findSolidsWithLayers()
1934 {
1935   // get all solids
1936   TopTools_IndexedMapOfShape allSolids;
1937   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1938   _sdVec.reserve( allSolids.Extent());
1939
1940   SMESH_HypoFilter filter;
1941   for ( int i = 1; i <= allSolids.Extent(); ++i )
1942   {
1943     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1944     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
1945     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
1946       continue; // solid is already meshed
1947     SMESH_Algo* algo = sm->GetAlgo();
1948     if ( !algo ) continue;
1949     // TODO: check if algo is hidden
1950     const list <const SMESHDS_Hypothesis *> & allHyps =
1951       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1952     _SolidData* soData = 0;
1953     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1954     const StdMeshers_ViscousLayers* viscHyp = 0;
1955     for ( ; hyp != allHyps.end(); ++hyp )
1956       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1957       {
1958         TopoDS_Shape hypShape;
1959         filter.Init( filter.Is( viscHyp ));
1960         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1961
1962         if ( !soData )
1963         {
1964           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1965                                                                     allSolids(i),
1966                                                                     /*toCreate=*/true);
1967           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1968           soData = & _sdVec.back();
1969           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1970           soData->_helper = new SMESH_MesherHelper( *_mesh );
1971           soData->_helper->SetSubShape( allSolids(i) );
1972           _solids.Add( allSolids(i) );
1973         }
1974         soData->_hyps.push_back( viscHyp );
1975         soData->_hypShapes.push_back( hypShape );
1976       }
1977   }
1978   if ( _sdVec.empty() )
1979     return error
1980       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1981
1982   return true;
1983 }
1984
1985 //================================================================================
1986 /*!
1987  * \brief Set a _SolidData to be computed before another
1988  */
1989 //================================================================================
1990
1991 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
1992 {
1993   // check possibility to set this order; get all solids before solidBefore
1994   TopTools_IndexedMapOfShape allSolidsBefore;
1995   allSolidsBefore.Add( solidBefore._solid );
1996   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
1997   {
1998     int iSD = _solids.FindIndex( allSolidsBefore(i) );
1999     if ( iSD )
2000     {
2001       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2002       for ( ; soIt.More(); soIt.Next() )
2003         allSolidsBefore.Add( soIt.Value() );
2004     }
2005   }
2006   if ( allSolidsBefore.Contains( solidAfter._solid ))
2007     return false;
2008
2009   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2010     solidAfter._before.Add( allSolidsBefore(i) );
2011
2012   return true;
2013 }
2014
2015 //================================================================================
2016 /*!
2017  * \brief
2018  */
2019 //================================================================================
2020
2021 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2022 {
2023   SMESH_MesherHelper helper( *_mesh );
2024   TopExp_Explorer exp;
2025
2026   // collect all faces-to-ignore defined by hyp
2027   for ( size_t i = 0; i < _sdVec.size(); ++i )
2028   {
2029     // get faces-to-ignore defined by each hyp
2030     typedef const StdMeshers_ViscousLayers* THyp;
2031     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2032     list< TFacesOfHyp > ignoreFacesOfHyps;
2033     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2034     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2035     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2036     {
2037       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2038       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2039     }
2040
2041     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2042     const int nbHyps = _sdVec[i]._hyps.size();
2043     if ( nbHyps > 1 )
2044     {
2045       // check if two hypotheses define different parameters for the same FACE
2046       list< TFacesOfHyp >::iterator igFacesOfHyp;
2047       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2048       {
2049         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2050         THyp hyp = 0;
2051         igFacesOfHyp = ignoreFacesOfHyps.begin();
2052         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2053           if ( ! igFacesOfHyp->first.count( faceID ))
2054           {
2055             if ( hyp )
2056               return error(SMESH_Comment("Several hypotheses define "
2057                                          "Viscous Layers on the face #") << faceID );
2058             hyp = igFacesOfHyp->second;
2059           }
2060         if ( hyp )
2061           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2062         else
2063           _sdVec[i]._ignoreFaceIds.insert( faceID );
2064       }
2065
2066       // check if two hypotheses define different number of viscous layers for
2067       // adjacent faces of a solid
2068       set< int > nbLayersSet;
2069       igFacesOfHyp = ignoreFacesOfHyps.begin();
2070       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2071       {
2072         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2073       }
2074       if ( nbLayersSet.size() > 1 )
2075       {
2076         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2077         {
2078           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2079           THyp hyp1 = 0, hyp2 = 0;
2080           while( const TopoDS_Shape* face = fIt->next() )
2081           {
2082             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2083             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2084             if ( f2h != _sdVec[i]._face2hyp.end() )
2085             {
2086               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2087             }
2088           }
2089           if ( hyp1 && hyp2 &&
2090                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2091           {
2092             return error("Two hypotheses define different number of "
2093                          "viscous layers on adjacent faces");
2094           }
2095         }
2096       }
2097     } // if ( nbHyps > 1 )
2098     else
2099     {
2100       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2101     }
2102   } // loop on _sdVec
2103
2104   if ( onlyWith ) // is called to check hypotheses compatibility only
2105     return true;
2106
2107   // fill _SolidData::_reversedFaceIds
2108   for ( size_t i = 0; i < _sdVec.size(); ++i )
2109   {
2110     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2111     for ( ; exp.More(); exp.Next() )
2112     {
2113       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2114       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2115       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2116           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2117           helper.IsReversedSubMesh( face ))
2118       {
2119         _sdVec[i]._reversedFaceIds.insert( faceID );
2120       }
2121     }
2122   }
2123
2124   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2125   TopTools_IndexedMapOfShape shapes;
2126   std::string structAlgoName = "Hexa_3D";
2127   for ( size_t i = 0; i < _sdVec.size(); ++i )
2128   {
2129     shapes.Clear();
2130     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2131     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2132     {
2133       const TopoDS_Shape& edge = shapes(iE);
2134       // find 2 FACEs sharing an EDGE
2135       TopoDS_Shape FF[2];
2136       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2137       while ( fIt->more())
2138       {
2139         const TopoDS_Shape* f = fIt->next();
2140         FF[ int( !FF[0].IsNull()) ] = *f;
2141       }
2142       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2143
2144       // check presence of layers on them
2145       int ignore[2];
2146       for ( int j = 0; j < 2; ++j )
2147         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2148       if ( ignore[0] == ignore[1] )
2149         continue; // nothing interesting
2150       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2151
2152       // add EDGE to maps
2153       if ( !fWOL.IsNull())
2154       {
2155         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2156         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2157       }
2158     }
2159   }
2160
2161   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2162
2163   for ( size_t i = 0; i < _sdVec.size(); ++i )
2164   {
2165     shapes.Clear();
2166     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2167     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2168     {
2169       const TopoDS_Shape& vertex = shapes(iV);
2170       // find faces WOL sharing the vertex
2171       vector< TopoDS_Shape > facesWOL;
2172       size_t totalNbFaces = 0;
2173       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2174       while ( fIt->more())
2175       {
2176         const TopoDS_Shape* f = fIt->next();
2177         totalNbFaces++;
2178         const int fID = getMeshDS()->ShapeToIndex( *f );
2179         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2180           facesWOL.push_back( *f );
2181       }
2182       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2183         continue; // no layers at this vertex or no WOL
2184       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2185       switch ( facesWOL.size() )
2186       {
2187       case 1:
2188       {
2189         helper.SetSubShape( facesWOL[0] );
2190         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2191         {
2192           TopoDS_Shape seamEdge;
2193           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2194           while ( eIt->more() && seamEdge.IsNull() )
2195           {
2196             const TopoDS_Shape* e = eIt->next();
2197             if ( helper.IsRealSeam( *e ) )
2198               seamEdge = *e;
2199           }
2200           if ( !seamEdge.IsNull() )
2201           {
2202             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2203             break;
2204           }
2205         }
2206         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2207         break;
2208       }
2209       case 2:
2210       {
2211         // find an edge shared by 2 faces
2212         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2213         while ( eIt->more())
2214         {
2215           const TopoDS_Shape* e = eIt->next();
2216           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2217                helper.IsSubShape( *e, facesWOL[1]))
2218           {
2219             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2220           }
2221         }
2222         break;
2223       }
2224       default:
2225         return error("Not yet supported case", _sdVec[i]._index);
2226       }
2227     }
2228   }
2229
2230   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrinked since
2231   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2232   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2233   for ( size_t i = 0; i < _sdVec.size(); ++i )
2234   {
2235     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2236     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2237     {
2238       const TopoDS_Shape& fWOL = e2f->second;
2239       const TGeomID     edgeID = e2f->first;
2240       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2241       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2242       if ( edge.ShapeType() != TopAbs_EDGE )
2243         continue; // shrink shape is VERTEX
2244
2245       TopoDS_Shape solid;
2246       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2247       while ( soIt->more() && solid.IsNull() )
2248       {
2249         const TopoDS_Shape* so = soIt->next();
2250         if ( !so->IsSame( _sdVec[i]._solid ))
2251           solid = *so;
2252       }
2253       if ( solid.IsNull() )
2254         continue;
2255
2256       bool noShrinkE = false;
2257       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2258       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2259       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2260       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2261       {
2262         // the adjacent SOLID has NO layers on fWOL;
2263         // shrink allowed if
2264         // - there are layers on the EDGE in the adjacent SOLID
2265         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2266         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2267         bool shrinkAllowed = (( hasWLAdj ) ||
2268                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2269         noShrinkE = !shrinkAllowed;
2270       }
2271       else if ( iSolid < _sdVec.size() )
2272       {
2273         // the adjacent SOLID has layers on fWOL;
2274         // check if SOLID's mesh is unstructured and then try to set it
2275         // to be computed after the i-th solid
2276         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2277           noShrinkE = true; // don't shrink fWOL
2278       }
2279       else
2280       {
2281         // the adjacent SOLID has NO layers at all
2282         noShrinkE = isStructured;
2283       }
2284
2285       if ( noShrinkE )
2286       {
2287         _sdVec[i]._noShrinkShapes.insert( edgeID );
2288
2289         // check if there is a collision with to-shrink-from EDGEs in iSolid
2290         // if ( iSolid < _sdVec.size() )
2291         // {
2292         //   shapes.Clear();
2293         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2294         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2295         //   {
2296         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2297         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2298         //     if ( eID == edgeID ||
2299         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2300         //          _sdVec[i]._noShrinkShapes.count( eID ))
2301         //       continue;
2302         //     for ( int is1st = 0; is1st < 2; ++is1st )
2303         //     {
2304         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2305         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2306         //       {
2307         //         return error("No way to make a conformal mesh with "
2308         //                      "the given set of faces with layers", _sdVec[i]._index);
2309         //       }
2310         //     }
2311         //   }
2312         // }
2313       }
2314
2315       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2316       // _shrinkShape2Shape is different in the adjacent SOLID
2317       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2318       {
2319         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2320         bool noShrinkV = false;
2321
2322         if ( iSolid < _sdVec.size() )
2323         {
2324           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2325           {
2326             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2327             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2328             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2329             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2330               noShrinkV = ( i2S->second.ShapeType() == TopAbs_EDGE || isStructured );
2331             else
2332               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2333           }
2334           else
2335           {
2336             noShrinkV = noShrinkE;
2337           }
2338         }
2339         else
2340         {
2341           // the adjacent SOLID has NO layers at all
2342           noShrinkV = ( isStructured ||
2343                         _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2344         }
2345         if ( noShrinkV )
2346           _sdVec[i]._noShrinkShapes.insert( vID );
2347       }
2348
2349     } // loop on _sdVec[i]._shrinkShape2Shape
2350   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2351
2352
2353     // add FACEs of other SOLIDs to _ignoreFaceIds
2354   for ( size_t i = 0; i < _sdVec.size(); ++i )
2355   {
2356     shapes.Clear();
2357     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2358
2359     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2360     {
2361       if ( !shapes.Contains( exp.Current() ))
2362         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2363     }
2364   }
2365
2366   return true;
2367 }
2368
2369 //================================================================================
2370 /*!
2371  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2372  */
2373 //================================================================================
2374
2375 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2376                                      const StdMeshers_ViscousLayers* hyp,
2377                                      const TopoDS_Shape&             hypShape,
2378                                      set<TGeomID>&                   ignoreFaceIds)
2379 {
2380   TopExp_Explorer exp;
2381
2382   vector<TGeomID> ids = hyp->GetBndShapes();
2383   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2384   {
2385     for ( size_t ii = 0; ii < ids.size(); ++ii )
2386     {
2387       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2388       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2389         ignoreFaceIds.insert( ids[ii] );
2390     }
2391   }
2392   else // FACEs with layers are given
2393   {
2394     exp.Init( solid, TopAbs_FACE );
2395     for ( ; exp.More(); exp.Next() )
2396     {
2397       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2398       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2399         ignoreFaceIds.insert( faceInd );
2400     }
2401   }
2402
2403   // ignore internal FACEs if inlets and outlets are specified
2404   if ( hyp->IsToIgnoreShapes() )
2405   {
2406     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2407     TopExp::MapShapesAndAncestors( hypShape,
2408                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2409
2410     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2411     {
2412       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2413       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2414         continue;
2415
2416       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2417       if ( nbSolids > 1 )
2418         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2419     }
2420   }
2421 }
2422
2423 //================================================================================
2424 /*!
2425  * \brief Create the inner surface of the viscous layer and prepare data for infation
2426  */
2427 //================================================================================
2428
2429 bool _ViscousBuilder::makeLayer(_SolidData& data)
2430 {
2431   // get all sub-shapes to make layers on
2432   set<TGeomID> subIds, faceIds;
2433   subIds = data._noShrinkShapes;
2434   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2435   for ( ; exp.More(); exp.Next() )
2436   {
2437     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2438     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2439       faceIds.insert( fSubM->GetId() );
2440   }
2441
2442   // make a map to find new nodes on sub-shapes shared with other SOLID
2443   map< TGeomID, TNode2Edge* >::iterator s2ne;
2444   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2445   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2446   {
2447     TGeomID shapeInd = s2s->first;
2448     for ( size_t i = 0; i < _sdVec.size(); ++i )
2449     {
2450       if ( _sdVec[i]._index == data._index ) continue;
2451       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2452       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2453            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2454       {
2455         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2456         break;
2457       }
2458     }
2459   }
2460
2461   // Create temporary faces and _LayerEdge's
2462
2463   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2464
2465   data._stepSize = Precision::Infinite();
2466   data._stepSizeNodes[0] = 0;
2467
2468   SMESH_MesherHelper helper( *_mesh );
2469   helper.SetSubShape( data._solid );
2470   helper.SetElementsOnShape( true );
2471
2472   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2473   TNode2Edge::iterator n2e2;
2474
2475   // collect _LayerEdge's of shapes they are based on
2476   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2477   const int nbShapes = getMeshDS()->MaxShapeIndex();
2478   edgesByGeom.resize( nbShapes+1 );
2479
2480   // set data of _EdgesOnShape's
2481   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2482   {
2483     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2484     while ( smIt->more() )
2485     {
2486       sm = smIt->next();
2487       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2488            !faceIds.count( sm->GetId() ))
2489         continue;
2490       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2491     }
2492   }
2493   // make _LayerEdge's
2494   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2495   {
2496     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2497     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2498     SMESH_ProxyMesh::SubMesh* proxySub =
2499       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2500
2501     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2502     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2503
2504     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2505     while ( eIt->more() )
2506     {
2507       const SMDS_MeshElement* face = eIt->next();
2508       double          faceMaxCosin = -1;
2509       _LayerEdge*     maxCosinEdge = 0;
2510       int             nbDegenNodes = 0;
2511
2512       newNodes.resize( face->NbCornerNodes() );
2513       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2514       {
2515         const SMDS_MeshNode* n = face->GetNode( i );
2516         const int      shapeID = n->getshapeId();
2517         const bool onDegenShap = helper.IsDegenShape( shapeID );
2518         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2519         if ( onDegenShap )
2520         {
2521           if ( onDegenEdge )
2522           {
2523             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2524             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2525             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2526             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2527               n = vN;
2528               nbDegenNodes++;
2529             }
2530           }
2531           else
2532           {
2533             nbDegenNodes++;
2534           }
2535         }
2536         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2537         if ( !(*n2e).second )
2538         {
2539           // add a _LayerEdge
2540           _LayerEdge* edge = new _LayerEdge();
2541           edge->_nodes.push_back( n );
2542           n2e->second = edge;
2543           edgesByGeom[ shapeID ]._edges.push_back( edge );
2544           const bool noShrink = data._noShrinkShapes.count( shapeID );
2545
2546           SMESH_TNodeXYZ xyz( n );
2547
2548           // set edge data or find already refined _LayerEdge and get data from it
2549           if (( !noShrink                                                     ) &&
2550               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2551               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2552               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2553           {
2554             _LayerEdge* foundEdge = (*n2e2).second;
2555             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2556             foundEdge->_pos.push_back( lastPos );
2557             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2558             const_cast< SMDS_MeshNode* >
2559               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2560           }
2561           else
2562           {
2563             if ( !noShrink )
2564             {
2565               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2566             }
2567             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2568               return false;
2569
2570             if ( edge->_nodes.size() < 2 )
2571               edge->Block( data );
2572               //data._noShrinkShapes.insert( shapeID );
2573           }
2574           dumpMove(edge->_nodes.back());
2575
2576           if ( edge->_cosin > faceMaxCosin )
2577           {
2578             faceMaxCosin = edge->_cosin;
2579             maxCosinEdge = edge;
2580           }
2581         }
2582         newNodes[ i ] = n2e->second->_nodes.back();
2583
2584         if ( onDegenEdge )
2585           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2586       }
2587       if ( newNodes.size() - nbDegenNodes < 2 )
2588         continue;
2589
2590       // create a temporary face
2591       const SMDS_MeshElement* newFace =
2592         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2593       proxySub->AddElement( newFace );
2594
2595       // compute inflation step size by min size of element on a convex surface
2596       if ( faceMaxCosin > theMinSmoothCosin )
2597         limitStepSize( data, face, maxCosinEdge );
2598
2599     } // loop on 2D elements on a FACE
2600   } // loop on FACEs of a SOLID to create _LayerEdge's
2601
2602
2603   // Set _LayerEdge::_neibors
2604   TNode2Edge::iterator n2e;
2605   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2606   {
2607     _EdgesOnShape& eos = data._edgesOnShape[iS];
2608     for ( size_t i = 0; i < eos._edges.size(); ++i )
2609     {
2610       _LayerEdge* edge = eos._edges[i];
2611       TIDSortedNodeSet nearNodes;
2612       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2613       while ( fIt->more() )
2614       {
2615         const SMDS_MeshElement* f = fIt->next();
2616         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2617           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2618       }
2619       nearNodes.erase( edge->_nodes[0] );
2620       edge->_neibors.reserve( nearNodes.size() );
2621       TIDSortedNodeSet::iterator node = nearNodes.begin();
2622       for ( ; node != nearNodes.end(); ++node )
2623         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2624           edge->_neibors.push_back( n2e->second );
2625     }
2626   }
2627
2628   data._epsilon = 1e-7;
2629   if ( data._stepSize < 1. )
2630     data._epsilon *= data._stepSize;
2631
2632   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2633     return false;
2634
2635   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2636   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2637
2638   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2639   const SMDS_MeshNode* nn[2];
2640   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2641   {
2642     _EdgesOnShape& eos = data._edgesOnShape[iS];
2643     for ( size_t i = 0; i < eos._edges.size(); ++i )
2644     {
2645       _LayerEdge* edge = eos._edges[i];
2646       if ( edge->IsOnEdge() )
2647       {
2648         // get neighbor nodes
2649         bool hasData = ( edge->_2neibors->_edges[0] );
2650         if ( hasData ) // _LayerEdge is a copy of another one
2651         {
2652           nn[0] = edge->_2neibors->srcNode(0);
2653           nn[1] = edge->_2neibors->srcNode(1);
2654         }
2655         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2656         {
2657           return false;
2658         }
2659         // set neighbor _LayerEdge's
2660         for ( int j = 0; j < 2; ++j )
2661         {
2662           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2663             return error("_LayerEdge not found by src node", data._index);
2664           edge->_2neibors->_edges[j] = n2e->second;
2665         }
2666         if ( !hasData )
2667           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2668       }
2669
2670       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2671       {
2672         _Simplex& s = edge->_simplices[j];
2673         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2674         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2675       }
2676
2677       // For an _LayerEdge on a degenerated EDGE, copy some data from
2678       // a corresponding _LayerEdge on a VERTEX
2679       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2680       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2681       {
2682         // Generally we should not get here
2683         if ( eos.ShapeType() != TopAbs_EDGE )
2684           continue;
2685         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2686         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2687         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2688           continue;
2689         const _LayerEdge* vEdge = n2e->second;
2690         edge->_normal    = vEdge->_normal;
2691         edge->_lenFactor = vEdge->_lenFactor;
2692         edge->_cosin     = vEdge->_cosin;
2693       }
2694
2695     } // loop on data._edgesOnShape._edges
2696   } // loop on data._edgesOnShape
2697
2698   // fix _LayerEdge::_2neibors on EDGEs to smooth
2699   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2700   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2701   //   if ( !e2c->second.IsNull() )
2702   //   {
2703   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2704   //       data.Sort2NeiborsOnEdge( eos->_edges );
2705   //   }
2706
2707   dumpFunctionEnd();
2708   return true;
2709 }
2710
2711 //================================================================================
2712 /*!
2713  * \brief Compute inflation step size by min size of element on a convex surface
2714  */
2715 //================================================================================
2716
2717 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2718                                      const SMDS_MeshElement* face,
2719                                      const _LayerEdge*       maxCosinEdge )
2720 {
2721   int iN = 0;
2722   double minSize = 10 * data._stepSize;
2723   const int nbNodes = face->NbCornerNodes();
2724   for ( int i = 0; i < nbNodes; ++i )
2725   {
2726     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2727     const SMDS_MeshNode*  curN = face->GetNode( i );
2728     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2729          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2730     {
2731       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2732       if ( dist < minSize )
2733         minSize = dist, iN = i;
2734     }
2735   }
2736   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2737   if ( newStep < data._stepSize )
2738   {
2739     data._stepSize = newStep;
2740     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2741     data._stepSizeNodes[0] = face->GetNode( iN );
2742     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2743   }
2744 }
2745
2746 //================================================================================
2747 /*!
2748  * \brief Compute inflation step size by min size of element on a convex surface
2749  */
2750 //================================================================================
2751
2752 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2753 {
2754   if ( minSize < data._stepSize )
2755   {
2756     data._stepSize = minSize;
2757     if ( data._stepSizeNodes[0] )
2758     {
2759       double dist =
2760         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2761       data._stepSizeCoeff = data._stepSize / dist;
2762     }
2763   }
2764 }
2765
2766 //================================================================================
2767 /*!
2768  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2769  */
2770 //================================================================================
2771
2772 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2773 {
2774   SMESH_MesherHelper helper( *_mesh );
2775
2776   const int nbTestPnt = 5; // on a FACE sub-shape
2777
2778   BRepLProp_SLProps surfProp( 2, 1e-6 );
2779   data._convexFaces.clear();
2780
2781   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2782   {
2783     _EdgesOnShape& eof = data._edgesOnShape[iS];
2784     if ( eof.ShapeType() != TopAbs_FACE ||
2785          data._ignoreFaceIds.count( eof._shapeID ))
2786       continue;
2787
2788     TopoDS_Face        F = TopoDS::Face( eof._shape );
2789     SMESH_subMesh *   sm = eof._subMesh;
2790     const TGeomID faceID = eof._shapeID;
2791
2792     BRepAdaptor_Surface surface( F, false );
2793     surfProp.SetSurface( surface );
2794
2795     bool isTooCurved = false;
2796
2797     _ConvexFace cnvFace;
2798     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2799     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2800     while ( smIt->more() )
2801     {
2802       sm = smIt->next();
2803       const TGeomID subID = sm->GetId();
2804       // find _LayerEdge's of a sub-shape
2805       _EdgesOnShape* eos;
2806       if (( eos = data.GetShapeEdges( subID )))
2807         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2808       else
2809         continue;
2810       // check concavity and curvature and limit data._stepSize
2811       const double minCurvature =
2812         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2813       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2814       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2815       {
2816         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2817         surfProp.SetParameters( uv.X(), uv.Y() );
2818         if ( !surfProp.IsCurvatureDefined() )
2819           continue;
2820         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2821         {
2822           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2823           isTooCurved = true;
2824         }
2825         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2826         {
2827           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2828           isTooCurved = true;
2829         }
2830       }
2831     } // loop on sub-shapes of the FACE
2832
2833     if ( !isTooCurved ) continue;
2834
2835     _ConvexFace & convFace =
2836       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2837
2838     convFace._face = F;
2839     convFace._normalsFixed = false;
2840
2841     // skip a closed surface (data._convexFaces is useful anyway)
2842     bool isClosedF = false;
2843     helper.SetSubShape( F );
2844     if ( helper.HasRealSeam() )
2845     {
2846       // in the closed surface there must be a closed EDGE
2847       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2848         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2849     }
2850     if ( isClosedF )
2851     {
2852       // limit _LayerEdge::_maxLen on the FACE
2853       const double minCurvature =
2854         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2855       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2856       if ( id2eos != cnvFace._subIdToEOS.end() )
2857       {
2858         _EdgesOnShape& eos = * id2eos->second;
2859         for ( size_t i = 0; i < eos._edges.size(); ++i )
2860         {
2861           _LayerEdge* ledge = eos._edges[ i ];
2862           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2863           surfProp.SetParameters( uv.X(), uv.Y() );
2864           if ( !surfProp.IsCurvatureDefined() )
2865             continue;
2866
2867           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2868             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2869
2870           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2871             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2872         }
2873       }
2874       continue;
2875     }
2876
2877     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2878     // prism distortion.
2879     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2880     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2881     {
2882       // there are _LayerEdge's on the FACE it-self;
2883       // select _LayerEdge's near EDGEs
2884       _EdgesOnShape& eos = * id2eos->second;
2885       for ( size_t i = 0; i < eos._edges.size(); ++i )
2886       {
2887         _LayerEdge* ledge = eos._edges[ i ];
2888         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2889           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2890           {
2891             convFace._simplexTestEdges.push_back( ledge );
2892             break;
2893           }
2894       }
2895     }
2896     else
2897     {
2898       // where there are no _LayerEdge's on a _ConvexFace,
2899       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2900       // so that collision of viscous internal faces is not detected by check of
2901       // intersection of _LayerEdge's with the viscous internal faces.
2902
2903       set< const SMDS_MeshNode* > usedNodes;
2904
2905       // look for _LayerEdge's with null _sWOL
2906       id2eos = convFace._subIdToEOS.begin();
2907       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2908       {
2909         _EdgesOnShape& eos = * id2eos->second;
2910         if ( !eos._sWOL.IsNull() )
2911           continue;
2912         for ( size_t i = 0; i < eos._edges.size(); ++i )
2913         {
2914           _LayerEdge* ledge = eos._edges[ i ];
2915           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2916           if ( !usedNodes.insert( srcNode ).second ) continue;
2917
2918           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2919           {
2920             usedNodes.insert( ledge->_simplices[i]._nPrev );
2921             usedNodes.insert( ledge->_simplices[i]._nNext );
2922           }
2923           convFace._simplexTestEdges.push_back( ledge );
2924         }
2925       }
2926     }
2927   } // loop on FACEs of data._solid
2928 }
2929
2930 //================================================================================
2931 /*!
2932  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2933  */
2934 //================================================================================
2935
2936 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2937 {
2938   // define allowed thickness
2939   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2940
2941   data._maxThickness = 0;
2942   data._minThickness = 1e100;
2943   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2944   for ( ; hyp != data._hyps.end(); ++hyp )
2945   {
2946     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2947     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2948   }
2949   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2950
2951   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2952   // boundary inclined to the shape at a sharp angle
2953
2954   //list< TGeomID > shapesToSmooth;
2955   TopTools_MapOfShape edgesOfSmooFaces;
2956
2957   SMESH_MesherHelper helper( *_mesh );
2958   bool ok = true;
2959
2960   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2961   data._nbShapesToSmooth = 0;
2962
2963   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2964   {
2965     _EdgesOnShape& eos = edgesByGeom[iS];
2966     eos._toSmooth = false;
2967     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2968       continue;
2969
2970     double tgtThick = eos._hyp.GetTotalThickness();
2971     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2972     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2973     {
2974       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2975       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2976       if ( eE.empty() ) continue;
2977
2978       double faceSize;
2979       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2980         if ( eE[i]->_cosin > theMinSmoothCosin )
2981         {
2982           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2983           while ( fIt->more() && !eos._toSmooth )
2984           {
2985             const SMDS_MeshElement* face = fIt->next();
2986             if ( face->getshapeId() == eos._shapeID &&
2987                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2988             {
2989               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2990             }
2991           }
2992         }
2993     }
2994     if ( eos._toSmooth )
2995     {
2996       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2997         edgesOfSmooFaces.Add( eExp.Current() );
2998
2999       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3000     }
3001     data._nbShapesToSmooth += eos._toSmooth;
3002
3003   }  // check FACEs
3004
3005   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3006   {
3007     _EdgesOnShape& eos = edgesByGeom[iS];
3008     eos._edgeSmoother = NULL;
3009     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3010     if ( !eos._hyp.ToSmooth() ) continue;
3011
3012     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3013     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3014       continue;
3015
3016     double tgtThick = eos._hyp.GetTotalThickness();
3017     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3018     {
3019       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3020       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3021       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3022       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3023       double angle    = eDir.Angle( eV[0]->_normal );
3024       double cosin    = Cos( angle );
3025       double cosinAbs = Abs( cosin );
3026       if ( cosinAbs > theMinSmoothCosin )
3027       {
3028         // always smooth analytic EDGEs
3029         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3030         eos._toSmooth = ! curve.IsNull();
3031
3032         // compare tgtThick with the length of an end segment
3033         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3034         while ( eIt->more() && !eos._toSmooth )
3035         {
3036           const SMDS_MeshElement* endSeg = eIt->next();
3037           if ( endSeg->getshapeId() == (int) iS )
3038           {
3039             double segLen =
3040               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
3041             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
3042           }
3043         }
3044         if ( eos._toSmooth )
3045         {
3046           eos._edgeSmoother = new _Smoother1D( curve, eos );
3047
3048           for ( size_t i = 0; i < eos._edges.size(); ++i )
3049             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3050         }
3051       }
3052     }
3053     data._nbShapesToSmooth += eos._toSmooth;
3054
3055   } // check EDGEs
3056
3057   // Reset _cosin if no smooth is allowed by the user
3058   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3059   {
3060     _EdgesOnShape& eos = edgesByGeom[iS];
3061     if ( eos._edges.empty() ) continue;
3062
3063     if ( !eos._hyp.ToSmooth() )
3064       for ( size_t i = 0; i < eos._edges.size(); ++i )
3065         eos._edges[i]->SetCosin( 0 );
3066   }
3067
3068
3069   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
3070
3071   TopTools_MapOfShape c1VV;
3072
3073   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3074   {
3075     _EdgesOnShape& eos = edgesByGeom[iS];
3076     if ( eos._edges.empty() ||
3077          eos.ShapeType() != TopAbs_FACE ||
3078          !eos._toSmooth )
3079       continue;
3080
3081     // check EDGEs of a FACE
3082     TopTools_MapOfShape checkedEE, allVV;
3083     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3084     while ( !smQueue.empty() )
3085     {
3086       SMESH_subMesh* sm = smQueue.front();
3087       smQueue.pop_front();
3088       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3089       while ( smIt->more() )
3090       {
3091         sm = smIt->next();
3092         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3093           allVV.Add( sm->GetSubShape() );
3094         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3095              !checkedEE.Add( sm->GetSubShape() ))
3096           continue;
3097
3098         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3099         vector<_LayerEdge*>& eE = eoe->_edges;
3100         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3101           continue;
3102
3103         bool isC1 = true; // check continuity along an EDGE
3104         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3105           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3106         if ( !isC1 )
3107           continue;
3108
3109         // check that mesh faces are C1 as well
3110         {
3111           gp_XYZ norm1, norm2;
3112           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3113           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3114           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3115             continue;
3116           while ( fIt->more() && isC1 )
3117             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3118                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3119           if ( !isC1 )
3120             continue;
3121         }
3122
3123         // add the EDGE and an adjacent FACE to _eosC1
3124         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3125         while ( const TopoDS_Shape* face = fIt->next() )
3126         {
3127           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3128           if ( !eof ) continue; // other solid
3129           if ( !eos.HasC1( eoe ))
3130           {
3131             eos._eosC1.push_back( eoe );
3132             eoe->_toSmooth = false;
3133             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3134           }
3135           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3136           {
3137             eos._eosC1.push_back( eof );
3138             eof->_toSmooth = false;
3139             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3140             smQueue.push_back( eof->_subMesh );
3141           }
3142         }
3143       }
3144     }
3145     if ( eos._eosC1.empty() )
3146       continue;
3147
3148     // check VERTEXes of C1 FACEs
3149     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3150     for ( ; vIt.More(); vIt.Next() )
3151     {
3152       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3153       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3154         continue;
3155
3156       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3157       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3158       while ( const TopoDS_Shape* face = fIt->next() )
3159       {
3160         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3161         if ( !eof ) continue; // other solid
3162         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3163         if ( !isC1 )
3164           break;
3165       }
3166       if ( isC1 )
3167       {
3168         eos._eosC1.push_back( eov );
3169         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3170         c1VV.Add( eov->_shape );
3171       }
3172     }
3173
3174   } // fill _eosC1 of FACEs
3175
3176
3177   // Find C1 EDGEs
3178
3179   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3180
3181   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3182   {
3183     _EdgesOnShape& eov = edgesByGeom[iS];
3184     if ( eov._edges.empty() ||
3185          eov.ShapeType() != TopAbs_VERTEX ||
3186          c1VV.Contains( eov._shape ))
3187       continue;
3188     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3189
3190     // get directions of surrounding EDGEs
3191     dirOfEdges.clear();
3192     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3193     while ( const TopoDS_Shape* e = fIt->next() )
3194     {
3195       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3196       if ( !eoe ) continue; // other solid
3197       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3198       if ( !Precision::IsInfinite( eDir.X() ))
3199         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3200     }
3201
3202     // find EDGEs with C1 directions
3203     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3204       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3205         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3206         {
3207           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3208           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3209           if ( isC1 )
3210           {
3211             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3212             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3213             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3214             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3215             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3216             dirOfEdges[i].first = 0;
3217             dirOfEdges[j].first = 0;
3218           }
3219         }
3220   } // fill _eosC1 of VERTEXes
3221
3222
3223
3224   return ok;
3225 }
3226
3227 //================================================================================
3228 /*!
3229  * \brief initialize data of _EdgesOnShape
3230  */
3231 //================================================================================
3232
3233 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3234                                     SMESH_subMesh* sm,
3235                                     _SolidData&    data )
3236 {
3237   if ( !eos._shape.IsNull() ||
3238        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3239     return;
3240
3241   SMESH_MesherHelper helper( *_mesh );
3242
3243   eos._subMesh = sm;
3244   eos._shapeID = sm->GetId();
3245   eos._shape   = sm->GetSubShape();
3246   if ( eos.ShapeType() == TopAbs_FACE )
3247     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3248   eos._toSmooth = false;
3249   eos._data = &data;
3250
3251   // set _SWOL
3252   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3253     data._shrinkShape2Shape.find( eos._shapeID );
3254   if ( s2s != data._shrinkShape2Shape.end() )
3255     eos._sWOL = s2s->second;
3256
3257   eos._isRegularSWOL = true;
3258   if ( eos.SWOLType() == TopAbs_FACE )
3259   {
3260     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3261     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3262     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3263   }
3264
3265   // set _hyp
3266   if ( data._hyps.size() == 1 )
3267   {
3268     eos._hyp = data._hyps.back();
3269   }
3270   else
3271   {
3272     // compute average StdMeshers_ViscousLayers parameters
3273     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3274     if ( eos.ShapeType() == TopAbs_FACE )
3275     {
3276       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3277         eos._hyp = f2hyp->second;
3278     }
3279     else
3280     {
3281       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3282       while ( const TopoDS_Shape* face = fIt->next() )
3283       {
3284         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3285         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3286           eos._hyp.Add( f2hyp->second );
3287       }
3288     }
3289   }
3290
3291   // set _faceNormals
3292   if ( ! eos._hyp.UseSurfaceNormal() )
3293   {
3294     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3295     {
3296       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3297       eos._faceNormals.resize( smDS->NbElements() );
3298
3299       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3300       for ( int iF = 0; eIt->more(); ++iF )
3301       {
3302         const SMDS_MeshElement* face = eIt->next();
3303         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3304           eos._faceNormals[iF].SetCoord( 0,0,0 );
3305       }
3306
3307       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3308         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3309           eos._faceNormals[iF].Reverse();
3310     }
3311     else // find EOS of adjacent FACEs
3312     {
3313       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3314       while ( const TopoDS_Shape* face = fIt->next() )
3315       {
3316         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3317         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3318         if ( eos._faceEOS.back()->_shape.IsNull() )
3319           // avoid using uninitialised _shapeID in GetNormal()
3320           eos._faceEOS.back()->_shapeID = faceID;
3321       }
3322     }
3323   }
3324 }
3325
3326 //================================================================================
3327 /*!
3328  * \brief Returns normal of a face
3329  */
3330 //================================================================================
3331
3332 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3333 {
3334   bool ok = false;
3335   const _EdgesOnShape* eos = 0;
3336
3337   if ( face->getshapeId() == _shapeID )
3338   {
3339     eos = this;
3340   }
3341   else
3342   {
3343     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3344       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3345         eos = _faceEOS[ iF ];
3346   }
3347
3348   if (( eos ) &&
3349       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3350   {
3351     norm = eos->_faceNormals[ face->getIdInShape() ];
3352   }
3353   else if ( !eos )
3354   {
3355     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3356               << " on _shape #" << _shapeID );
3357   }
3358   return ok;
3359 }
3360
3361
3362 //================================================================================
3363 /*!
3364  * \brief Set data of _LayerEdge needed for smoothing
3365  */
3366 //================================================================================
3367
3368 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3369                                   _EdgesOnShape&      eos,
3370                                   SMESH_MesherHelper& helper,
3371                                   _SolidData&         data)
3372 {
3373   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3374
3375   edge._len       = 0;
3376   edge._maxLen    = Precision::Infinite();
3377   edge._minAngle  = 0;
3378   edge._2neibors  = 0;
3379   edge._curvature = 0;
3380   edge._flags     = 0;
3381
3382   // --------------------------
3383   // Compute _normal and _cosin
3384   // --------------------------
3385
3386   edge._cosin     = 0;
3387   edge._lenFactor = 1.;
3388   edge._normal.SetCoord(0,0,0);
3389   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3390
3391   int totalNbFaces = 0;
3392   TopoDS_Face F;
3393   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3394   gp_Vec geomNorm;
3395   bool normOK = true;
3396
3397   const bool onShrinkShape = !eos._sWOL.IsNull();
3398   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3399                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3400
3401   // get geom FACEs the node lies on
3402   //if ( useGeometry )
3403   {
3404     set<TGeomID> faceIds;
3405     if  ( eos.ShapeType() == TopAbs_FACE )
3406     {
3407       faceIds.insert( eos._shapeID );
3408     }
3409     else
3410     {
3411       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3412       while ( fIt->more() )
3413         faceIds.insert( fIt->next()->getshapeId() );
3414     }
3415     set<TGeomID>::iterator id = faceIds.begin();
3416     for ( ; id != faceIds.end(); ++id )
3417     {
3418       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3419       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3420         continue;
3421       F = TopoDS::Face( s );
3422       face2Norm[ totalNbFaces ].first = F;
3423       totalNbFaces++;
3424     }
3425   }
3426
3427   // find _normal
3428   if ( useGeometry )
3429   {
3430     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3431                       eos.SWOLType()  == TopAbs_FACE  &&
3432                       totalNbFaces > 1 );
3433
3434     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3435     {
3436       if ( eos.SWOLType() == TopAbs_EDGE )
3437       {
3438         // inflate from VERTEX along EDGE
3439         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3440       }
3441       else if ( eos.ShapeType() == TopAbs_VERTEX )
3442       {
3443         // inflate from VERTEX along FACE
3444         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3445                                    node, helper, normOK, &edge._cosin);
3446       }
3447       else
3448       {
3449         // inflate from EDGE along FACE
3450         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3451                                    node, helper, normOK);
3452       }
3453     }
3454     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3455     {
3456       if ( fromVonF )
3457         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3458
3459       int nbOkNorms = 0;
3460       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3461       {
3462         F = face2Norm[ iF ].first;
3463         geomNorm = getFaceNormal( node, F, helper, normOK );
3464         if ( !normOK ) continue;
3465         nbOkNorms++;
3466
3467         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3468           geomNorm.Reverse();
3469         face2Norm[ iF ].second = geomNorm.XYZ();
3470         edge._normal += geomNorm.XYZ();
3471       }
3472       if ( nbOkNorms == 0 )
3473         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3474
3475       if ( totalNbFaces >= 3 )
3476       {
3477         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3478       }
3479
3480       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3481       {
3482         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3483         edge._normal.SetCoord( 0,0,0 );
3484         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3485         {
3486           const TopoDS_Face& F = face2Norm[iF].first;
3487           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3488           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3489             geomNorm.Reverse();
3490           if ( normOK )
3491             face2Norm[ iF ].second = geomNorm.XYZ();
3492           edge._normal += face2Norm[ iF ].second;
3493         }
3494       }
3495     }
3496   }
3497   else // !useGeometry - get _normal using surrounding mesh faces
3498   {
3499     edge._normal = getWeigthedNormal( &edge );
3500
3501     // set<TGeomID> faceIds;
3502     //
3503     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3504     // while ( fIt->more() )
3505     // {
3506     //   const SMDS_MeshElement* face = fIt->next();
3507     //   if ( eos.GetNormal( face, geomNorm ))
3508     //   {
3509     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3510     //       continue; // use only one mesh face on FACE
3511     //     edge._normal += geomNorm.XYZ();
3512     //     totalNbFaces++;
3513     //   }
3514     // }
3515   }
3516
3517   // compute _cosin
3518   //if ( eos._hyp.UseSurfaceNormal() )
3519   {
3520     switch ( eos.ShapeType() )
3521     {
3522     case TopAbs_FACE: {
3523       edge._cosin = 0;
3524       break;
3525     }
3526     case TopAbs_EDGE: {
3527       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3528       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3529       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3530       edge._cosin      = Cos( angle );
3531       break;
3532     }
3533     case TopAbs_VERTEX: {
3534       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3535       {
3536         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3537         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3538         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3539         edge._cosin      = Cos( angle );
3540         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3541           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3542           {
3543             F = face2Norm[ iF ].first;
3544             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3545             if ( normOK ) {
3546               double angle = inFaceDir.Angle( edge._normal );
3547               double cosin = Cos( angle );
3548               if ( Abs( cosin ) > Abs( edge._cosin ))
3549                 edge._cosin = cosin;
3550             }
3551           }
3552       }
3553       break;
3554     }
3555     default:
3556       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3557     }
3558   }
3559
3560   double normSize = edge._normal.SquareModulus();
3561   if ( normSize < numeric_limits<double>::min() )
3562     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3563
3564   edge._normal /= sqrt( normSize );
3565
3566   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3567   {
3568     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3569     edge._nodes.resize( 1 );
3570     edge._normal.SetCoord( 0,0,0 );
3571     edge._maxLen = 0;
3572   }
3573
3574   // Set the rest data
3575   // --------------------
3576
3577   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3578
3579   if ( onShrinkShape )
3580   {
3581     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3582     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3583       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3584
3585     // set initial position which is parameters on _sWOL in this case
3586     if ( eos.SWOLType() == TopAbs_EDGE )
3587     {
3588       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3589       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3590       if ( edge._nodes.size() > 1 )
3591         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3592     }
3593     else // eos.SWOLType() == TopAbs_FACE
3594     {
3595       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3596       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3597       if ( edge._nodes.size() > 1 )
3598         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3599     }
3600
3601     if ( edge._nodes.size() > 1 )
3602     {
3603       // check if an angle between a FACE with layers and SWOL is sharp,
3604       // else the edge should not inflate
3605       F.Nullify();
3606       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3607         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3608           F = face2Norm[iF].first;
3609       if ( !F.IsNull())
3610       {
3611         geomNorm = getFaceNormal( node, F, helper, normOK );
3612         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3613           geomNorm.Reverse(); // inside the SOLID
3614         if ( geomNorm * edge._normal < -0.001 )
3615         {
3616           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3617           edge._nodes.resize( 1 );
3618         }
3619         else if ( edge._lenFactor > 3 )
3620         {
3621           edge._lenFactor = 2;
3622           edge.Set( _LayerEdge::RISKY_SWOL );
3623         }
3624       }
3625     }
3626   }
3627   else
3628   {
3629     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3630
3631     if ( eos.ShapeType() == TopAbs_FACE )
3632     {
3633       double angle;
3634       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3635       {
3636         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3637         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3638       }
3639     }
3640   }
3641
3642   // Set neighbor nodes for a _LayerEdge based on EDGE
3643
3644   if ( eos.ShapeType() == TopAbs_EDGE /*||
3645        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3646   {
3647     edge._2neibors = new _2NearEdges;
3648     // target nodes instead of source ones will be set later
3649   }
3650
3651   return true;
3652 }
3653
3654 //================================================================================
3655 /*!
3656  * \brief Return normal to a FACE at a node
3657  *  \param [in] n - node
3658  *  \param [in] face - FACE
3659  *  \param [in] helper - helper
3660  *  \param [out] isOK - true or false
3661  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3662  *  \return gp_XYZ - normal
3663  */
3664 //================================================================================
3665
3666 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3667                                       const TopoDS_Face&   face,
3668                                       SMESH_MesherHelper&  helper,
3669                                       bool&                isOK,
3670                                       bool                 shiftInside)
3671 {
3672   gp_XY uv;
3673   if ( shiftInside )
3674   {
3675     // get a shifted position
3676     gp_Pnt p = SMESH_TNodeXYZ( node );
3677     gp_XYZ shift( 0,0,0 );
3678     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3679     switch ( S.ShapeType() ) {
3680     case TopAbs_VERTEX:
3681     {
3682       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3683       break;
3684     }
3685     case TopAbs_EDGE:
3686     {
3687       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3688       break;
3689     }
3690     default:
3691       isOK = false;
3692     }
3693     if ( isOK )
3694       shift.Normalize();
3695     p.Translate( shift * 1e-5 );
3696
3697     TopLoc_Location loc;
3698     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3699
3700     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3701     
3702     projector.Perform( p );
3703     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3704     {
3705       isOK = false;
3706       return p.XYZ();
3707     }
3708     Quantity_Parameter U,V;
3709     projector.LowerDistanceParameters(U,V);
3710     uv.SetCoord( U,V );
3711   }
3712   else
3713   {
3714     uv = helper.GetNodeUV( face, node, 0, &isOK );
3715   }
3716
3717   gp_Dir normal;
3718   isOK = false;
3719
3720   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3721
3722   if ( !shiftInside &&
3723        helper.IsDegenShape( node->getshapeId() ) &&
3724        getFaceNormalAtSingularity( uv, face, helper, normal ))
3725   {
3726     isOK = true;
3727     return normal.XYZ();
3728   }
3729
3730   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3731   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3732
3733   if ( pointKind == IMPOSSIBLE &&
3734        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3735   {
3736     // probably NormEstim() failed due to a too high tolerance
3737     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3738     isOK = ( pointKind < IMPOSSIBLE );
3739   }
3740   if ( pointKind < IMPOSSIBLE )
3741   {
3742     if ( pointKind != REGULAR &&
3743          !shiftInside &&
3744          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3745     {
3746       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3747       if ( normShift * normal.XYZ() < 0. )
3748         normal = normShift;
3749     }
3750     isOK = true;
3751   }
3752
3753   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3754   {
3755     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3756
3757     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3758     while ( fIt->more() )
3759     {
3760       const SMDS_MeshElement* f = fIt->next();
3761       if ( f->getshapeId() == faceID )
3762       {
3763         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3764         if ( isOK )
3765         {
3766           TopoDS_Face ff = face;
3767           ff.Orientation( TopAbs_FORWARD );
3768           if ( helper.IsReversedSubMesh( ff ))
3769             normal.Reverse();
3770           break;
3771         }
3772       }
3773     }
3774   }
3775   return normal.XYZ();
3776 }
3777
3778 //================================================================================
3779 /*!
3780  * \brief Try to get normal at a singularity of a surface basing on it's nature
3781  */
3782 //================================================================================
3783
3784 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3785                                                   const TopoDS_Face&  face,
3786                                                   SMESH_MesherHelper& helper,
3787                                                   gp_Dir&             normal )
3788 {
3789   BRepAdaptor_Surface surface( face );
3790   gp_Dir axis;
3791   if ( !getRovolutionAxis( surface, axis ))
3792     return false;
3793
3794   double f,l, d, du, dv;
3795   f = surface.FirstUParameter();
3796   l = surface.LastUParameter();
3797   d = ( uv.X() - f ) / ( l - f );
3798   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3799   f = surface.FirstVParameter();
3800   l = surface.LastVParameter();
3801   d = ( uv.Y() - f ) / ( l - f );
3802   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3803
3804   gp_Dir refDir;
3805   gp_Pnt2d testUV = uv;
3806   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3807   double tol = 1e-5;
3808   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3809   for ( int iLoop = 0; true ; ++iLoop )
3810   {
3811     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3812     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3813       break;
3814     if ( iLoop > 20 )
3815       return false;
3816     tol /= 10.;
3817   }
3818
3819   if ( axis * refDir < 0. )
3820     axis.Reverse();
3821
3822   normal = axis;
3823
3824   return true;
3825 }
3826
3827 //================================================================================
3828 /*!
3829  * \brief Return a normal at a node weighted with angles taken by faces
3830  */
3831 //================================================================================
3832
3833 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3834 {
3835   const SMDS_MeshNode* n = edge->_nodes[0];
3836
3837   gp_XYZ resNorm(0,0,0);
3838   SMESH_TNodeXYZ p0( n ), pP, pN;
3839   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3840   {
3841     pP.Set( edge->_simplices[i]._nPrev );
3842     pN.Set( edge->_simplices[i]._nNext );
3843     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3844     double l0P = v0P.SquareMagnitude();
3845     double l0N = v0N.SquareMagnitude();
3846     double lPN = vPN.SquareMagnitude();
3847     if ( l0P < std::numeric_limits<double>::min() ||
3848          l0N < std::numeric_limits<double>::min() ||
3849          lPN < std::numeric_limits<double>::min() )
3850       continue;
3851     double lNorm = norm.SquareMagnitude();
3852     double  sin2 = lNorm / l0P / l0N;
3853     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3854
3855     double weight = sin2 * angle / lPN;
3856     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3857   }
3858
3859   return resNorm;
3860 }
3861
3862 //================================================================================
3863 /*!
3864  * \brief Return a normal at a node by getting a common point of offset planes
3865  *        defined by the FACE normals
3866  */
3867 //================================================================================
3868
3869 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3870                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3871                                            int                              nbFaces,
3872                                            bool                             lastNoOffset)
3873 {
3874   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3875
3876   gp_XYZ resNorm(0,0,0);
3877   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3878   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3879   {
3880     for ( int i = 0; i < nbFaces; ++i )
3881       resNorm += f2Normal[i].second;
3882     return resNorm;
3883   }
3884
3885   // prepare _OffsetPlane's
3886   vector< _OffsetPlane > pln( nbFaces );
3887   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3888   {
3889     pln[i]._faceIndex = i;
3890     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3891   }
3892   if ( lastNoOffset )
3893   {
3894     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3895     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3896   }
3897
3898   // intersect neighboring OffsetPlane's
3899   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3900   while ( const TopoDS_Shape* edge = edgeIt->next() )
3901   {
3902     int f1 = -1, f2 = -1;
3903     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3904       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3905         (( f1 < 0 ) ? f1 : f2 ) = i;
3906
3907     if ( f2 >= 0 )
3908       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3909   }
3910
3911   // get a common point
3912   gp_XYZ commonPnt( 0, 0, 0 );
3913   int nbPoints = 0;
3914   bool isPointFound;
3915   for ( int i = 0; i < nbFaces; ++i )
3916   {
3917     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3918     nbPoints  += isPointFound;
3919   }
3920   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3921   if ( nbPoints == 0 )
3922     return wgtNorm;
3923
3924   commonPnt /= nbPoints;
3925   resNorm = commonPnt - p0;
3926   if ( lastNoOffset )
3927     return resNorm;
3928
3929   // choose the best among resNorm and wgtNorm
3930   resNorm.Normalize();
3931   wgtNorm.Normalize();
3932   double resMinDot = std::numeric_limits<double>::max();
3933   double wgtMinDot = std::numeric_limits<double>::max();
3934   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3935   {
3936     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3937     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3938   }
3939
3940   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3941   {
3942     edge->Set( _LayerEdge::MULTI_NORMAL );
3943   }
3944
3945   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3946 }
3947
3948 //================================================================================
3949 /*!
3950  * \brief Compute line of intersection of 2 planes
3951  */
3952 //================================================================================
3953
3954 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3955                                             const TopoDS_Edge&   E,
3956                                             const TopoDS_Vertex& V )
3957 {
3958   int iNext = bool( _faceIndexNext[0] >= 0 );
3959   _faceIndexNext[ iNext ] = pln._faceIndex;
3960
3961   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3962   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3963
3964   gp_XYZ lineDir = n1 ^ n2;
3965
3966   double x = Abs( lineDir.X() );
3967   double y = Abs( lineDir.Y() );
3968   double z = Abs( lineDir.Z() );
3969
3970   int cooMax; // max coordinate
3971   if (x > y) {
3972     if (x > z) cooMax = 1;
3973     else       cooMax = 3;
3974   }
3975   else {
3976     if (y > z) cooMax = 2;
3977     else       cooMax = 3;
3978   }
3979
3980   gp_Pnt linePos;
3981   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3982   {
3983     // parallel planes - intersection is an offset of the common EDGE
3984     gp_Pnt p = BRep_Tool::Pnt( V );
3985     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3986     lineDir  = getEdgeDir( E, V );
3987   }
3988   else
3989   {
3990     // the constants in the 2 plane equations
3991     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3992     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3993
3994     switch ( cooMax ) {
3995     case 1:
3996       linePos.SetX(  0 );
3997       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3998       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3999       break;
4000     case 2:
4001       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4002       linePos.SetY(  0 );
4003       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4004       break;
4005     case 3:
4006       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4007       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4008       linePos.SetZ(  0 );
4009     }
4010   }
4011   gp_Lin& line = _lines[ iNext ];
4012   line.SetDirection( lineDir );
4013   line.SetLocation ( linePos );
4014
4015   _isLineOK[ iNext ] = true;
4016
4017
4018   iNext = bool( pln._faceIndexNext[0] >= 0 );
4019   pln._lines        [ iNext ] = line;
4020   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4021   pln._isLineOK     [ iNext ] = true;
4022 }
4023
4024 //================================================================================
4025 /*!
4026  * \brief Computes intersection point of two _lines
4027  */
4028 //================================================================================
4029
4030 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4031                                     const TopoDS_Vertex & V) const
4032 {
4033   gp_XYZ p( 0,0,0 );
4034   isFound = false;
4035
4036   if ( NbLines() == 2 )
4037   {
4038     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4039     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4040     if ( Abs( dot01 ) > 0.05 )
4041     {
4042       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4043       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4044       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4045       isFound = true;
4046     }
4047     else
4048     {
4049       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4050       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4051       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4052       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4053       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4054       isFound = true;
4055     }
4056   }
4057
4058   return p;
4059 }
4060
4061 //================================================================================
4062 /*!
4063  * \brief Find 2 neigbor nodes of a node on EDGE
4064  */
4065 //================================================================================
4066
4067 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4068                                         const SMDS_MeshNode*& n1,
4069                                         const SMDS_MeshNode*& n2,
4070                                         _EdgesOnShape&        eos,
4071                                         _SolidData&           data)
4072 {
4073   const SMDS_MeshNode* node = edge->_nodes[0];
4074   const int        shapeInd = eos._shapeID;
4075   SMESHDS_SubMesh*   edgeSM = 0;
4076   if ( eos.ShapeType() == TopAbs_EDGE )
4077   {
4078     edgeSM = eos._subMesh->GetSubMeshDS();
4079     if ( !edgeSM || edgeSM->NbElements() == 0 )
4080       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4081   }
4082   int iN = 0;
4083   n2 = 0;
4084   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4085   while ( eIt->more() && !n2 )
4086   {
4087     const SMDS_MeshElement* e = eIt->next();
4088     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4089     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4090     if ( edgeSM )
4091     {
4092       if (!edgeSM->Contains(e)) continue;
4093     }
4094     else
4095     {
4096       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4097       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4098     }
4099     ( iN++ ? n2 : n1 ) = nNeibor;
4100   }
4101   if ( !n2 )
4102     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4103   return true;
4104 }
4105
4106 //================================================================================
4107 /*!
4108  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4109  */
4110 //================================================================================
4111
4112 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4113                                      const SMDS_MeshNode* n2,
4114                                      const _EdgesOnShape& eos,
4115                                      SMESH_MesherHelper&  helper)
4116 {
4117   if ( eos.ShapeType() != TopAbs_EDGE )
4118     return;
4119
4120   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4121   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4122   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4123
4124   // Set _curvature
4125
4126   double      sumLen = vec1.Modulus() + vec2.Modulus();
4127   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4128   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4129   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4130   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4131   if ( _curvature ) delete _curvature;
4132   _curvature = _Curvature::New( avgNormProj, avgLen );
4133   // if ( _curvature )
4134   //   debugMsg( _nodes[0]->GetID()
4135   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4136   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4137   //             << _curvature->lenDelta(0) );
4138
4139   // Set _plnNorm
4140
4141   if ( eos._sWOL.IsNull() )
4142   {
4143     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4144     // if ( SMESH_Algo::isDegenerated( E ))
4145     //   return;
4146     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4147     gp_XYZ plnNorm = dirE ^ _normal;
4148     double proj0   = plnNorm * vec1;
4149     double proj1   = plnNorm * vec2;
4150     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4151     {
4152       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4153       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4154     }
4155   }
4156 }
4157
4158 //================================================================================
4159 /*!
4160  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4161  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4162  */
4163 //================================================================================
4164
4165 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4166                          _EdgesOnShape&      eos,
4167                          SMESH_MesherHelper& helper )
4168 {
4169   _nodes     = other._nodes;
4170   _normal    = other._normal;
4171   _len       = 0;
4172   _lenFactor = other._lenFactor;
4173   _cosin     = other._cosin;
4174   _2neibors  = other._2neibors;
4175   _curvature = 0; std::swap( _curvature, other._curvature );
4176   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4177
4178   gp_XYZ lastPos( 0,0,0 );
4179   if ( eos.SWOLType() == TopAbs_EDGE )
4180   {
4181     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4182     _pos.push_back( gp_XYZ( u, 0, 0));
4183
4184     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4185     lastPos.SetX( u );
4186   }
4187   else // TopAbs_FACE
4188   {
4189     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4190     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4191
4192     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4193     lastPos.SetX( uv.X() );
4194     lastPos.SetY( uv.Y() );
4195   }
4196   return lastPos;
4197 }
4198
4199 //================================================================================
4200 /*!
4201  * \brief Set _cosin and _lenFactor
4202  */
4203 //================================================================================
4204
4205 void _LayerEdge::SetCosin( double cosin )
4206 {
4207   _cosin = cosin;
4208   cosin = Abs( _cosin );
4209   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4210   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4211 }
4212
4213 //================================================================================
4214 /*!
4215  * \brief Check if another _LayerEdge is a neighbor on EDGE
4216  */
4217 //================================================================================
4218
4219 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4220 {
4221   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4222           ( edge->_2neibors && edge->_2neibors->include( this )));
4223 }
4224
4225 //================================================================================
4226 /*!
4227  * \brief Fills a vector<_Simplex > 
4228  */
4229 //================================================================================
4230
4231 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4232                              vector<_Simplex>&    simplices,
4233                              const set<TGeomID>&  ingnoreShapes,
4234                              const _SolidData*    dataToCheckOri,
4235                              const bool           toSort)
4236 {
4237   simplices.clear();
4238   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4239   while ( fIt->more() )
4240   {
4241     const SMDS_MeshElement* f = fIt->next();
4242     const TGeomID    shapeInd = f->getshapeId();
4243     if ( ingnoreShapes.count( shapeInd )) continue;
4244     const int nbNodes = f->NbCornerNodes();
4245     const int  srcInd = f->GetNodeIndex( node );
4246     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4247     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4248     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4249     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4250       std::swap( nPrev, nNext );
4251     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4252   }
4253
4254   if ( toSort )
4255     SortSimplices( simplices );
4256 }
4257
4258 //================================================================================
4259 /*!
4260  * \brief Set neighbor simplices side by side
4261  */
4262 //================================================================================
4263
4264 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4265 {
4266   vector<_Simplex> sortedSimplices( simplices.size() );
4267   sortedSimplices[0] = simplices[0];
4268   size_t nbFound = 0;
4269   for ( size_t i = 1; i < simplices.size(); ++i )
4270   {
4271     for ( size_t j = 1; j < simplices.size(); ++j )
4272       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4273       {
4274         sortedSimplices[i] = simplices[j];
4275         nbFound++;
4276         break;
4277       }
4278   }
4279   if ( nbFound == simplices.size() - 1 )
4280     simplices.swap( sortedSimplices );
4281 }
4282
4283 //================================================================================
4284 /*!
4285  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4286  */
4287 //================================================================================
4288
4289 void _ViscousBuilder::makeGroupOfLE()
4290 {
4291 #ifdef _DEBUG_
4292   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4293   {
4294     if ( _sdVec[i]._n2eMap.empty() ) continue;
4295
4296     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4297     TNode2Edge::iterator n2e;
4298     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4299     {
4300       _LayerEdge* le = n2e->second;
4301       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4302       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4303       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4304       if ( le ) {
4305         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4306                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4307       }
4308     }
4309     dumpFunctionEnd();
4310
4311     dumpFunction( SMESH_Comment("makeNormals") << i );
4312     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4313     {
4314       _LayerEdge* edge = n2e->second;
4315       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4316       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4317       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4318               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4319     }
4320     dumpFunctionEnd();
4321
4322     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4323     dumpCmd( "faceId1 = mesh.NbElements()" );
4324     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4325     for ( ; fExp.More(); fExp.Next() )
4326     {
4327       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4328       {
4329         if ( sm->NbElements() == 0 ) continue;
4330         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4331         while ( fIt->more())
4332         {
4333           const SMDS_MeshElement* e = fIt->next();
4334           SMESH_Comment cmd("mesh.AddFace([");
4335           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4336             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4337           dumpCmd( cmd );
4338         }
4339       }
4340     }
4341     dumpCmd( "faceId2 = mesh.NbElements()" );
4342     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4343              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4344              << "'%s-%s' % (faceId1+1, faceId2))");
4345     dumpFunctionEnd();
4346   }
4347 #endif
4348 }
4349
4350 //================================================================================
4351 /*!
4352  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4353  */
4354 //================================================================================
4355
4356 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4357 {
4358   data._geomSize = Precision::Infinite();
4359   double intersecDist;
4360   const SMDS_MeshElement* face;
4361   SMESH_MesherHelper helper( *_mesh );
4362
4363   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4364     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4365                                            data._proxyMesh->GetFaces( data._solid )));
4366
4367   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4368   {
4369     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4370     if ( eos._edges.empty() )
4371       continue;
4372     // get neighbor faces intersection with which should not be considered since
4373     // collisions are avoided by means of smoothing
4374     set< TGeomID > neighborFaces;
4375     if ( eos._hyp.ToSmooth() )
4376     {
4377       SMESH_subMeshIteratorPtr subIt =
4378         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4379       while ( subIt->more() )
4380       {
4381         SMESH_subMesh* sm = subIt->next();
4382         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4383         while ( const TopoDS_Shape* face = fIt->next() )
4384           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4385       }
4386     }
4387     // find intersections
4388     double thinkness = eos._hyp.GetTotalThickness();
4389     for ( size_t i = 0; i < eos._edges.size(); ++i )
4390     {
4391       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4392       eos._edges[i]->_maxLen = thinkness;
4393       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4394       if ( intersecDist > 0 && face )
4395       {
4396         data._geomSize = Min( data._geomSize, intersecDist );
4397         if ( !neighborFaces.count( face->getshapeId() ))
4398           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4399       }
4400     }
4401   }
4402 }
4403
4404 //================================================================================
4405 /*!
4406  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4407  */
4408 //================================================================================
4409
4410 bool _ViscousBuilder::inflate(_SolidData& data)
4411 {
4412   SMESH_MesherHelper helper( *_mesh );
4413
4414   // Limit inflation step size by geometry size found by itersecting
4415   // normals of _LayerEdge's with mesh faces
4416   if ( data._stepSize > 0.3 * data._geomSize )
4417     limitStepSize( data, 0.3 * data._geomSize );
4418
4419   const double tgtThick = data._maxThickness;
4420   if ( data._stepSize > data._minThickness )
4421     limitStepSize( data, data._minThickness );
4422
4423   if ( data._stepSize < 1. )
4424     data._epsilon = data._stepSize * 1e-7;
4425
4426   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4427
4428   findCollisionEdges( data, helper );
4429
4430   limitMaxLenByCurvature( data, helper );
4431
4432   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4433   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4434     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4435          data._edgesOnShape[i]._edges.size() > 0 &&
4436          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4437     {
4438       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4439       data._edgesOnShape[i]._edges[0]->Block( data );
4440     }
4441
4442   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4443
4444   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4445   int nbSteps = 0, nbRepeats = 0;
4446   while ( avgThick < 0.99 )
4447   {
4448     // new target length
4449     double prevThick = curThick;
4450     curThick += data._stepSize;
4451     if ( curThick > tgtThick )
4452     {
4453       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4454       nbRepeats++;
4455     }
4456
4457     double stepSize = curThick - prevThick;
4458     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4459
4460     // Elongate _LayerEdge's
4461     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4462     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4463     {
4464       _EdgesOnShape& eos = data._edgesOnShape[iS];
4465       if ( eos._edges.empty() ) continue;
4466
4467       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4468       for ( size_t i = 0; i < eos._edges.size(); ++i )
4469       {
4470         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4471       }
4472     }
4473     dumpFunctionEnd();
4474
4475     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4476       return false;
4477
4478     // Improve and check quality
4479     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4480     {
4481       if ( nbSteps > 0 )
4482       {
4483 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4484         debugMsg("NOT INVALIDATED STEP!");
4485         return error("Smoothing failed", data._index);
4486 #endif
4487         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4488         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4489         {
4490           _EdgesOnShape& eos = data._edgesOnShape[iS];
4491           for ( size_t i = 0; i < eos._edges.size(); ++i )
4492             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4493         }
4494         dumpFunctionEnd();
4495       }
4496       break; // no more inflating possible
4497     }
4498     nbSteps++;
4499
4500     // Evaluate achieved thickness
4501     avgThick = 0;
4502     int nbActiveEdges = 0;
4503     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4504     {
4505       _EdgesOnShape& eos = data._edgesOnShape[iS];
4506       if ( eos._edges.empty() ) continue;
4507
4508       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4509       for ( size_t i = 0; i < eos._edges.size(); ++i )
4510       {
4511         if ( eos._edges[i]->_nodes.size() > 1 )
4512           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4513         else
4514           avgThick    += shapeTgtThick;
4515         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4516       }
4517     }
4518     avgThick /= data._n2eMap.size();
4519     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4520
4521 #ifdef BLOCK_INFLATION
4522     if ( nbActiveEdges == 0 )
4523     {
4524       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4525       break;
4526     }
4527 #else
4528     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4529     {
4530       debugMsg( "-- Stop inflation since "
4531                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4532                 << tgtThick * avgThick << " ) * " << safeFactor );
4533       break;
4534     }
4535 #endif
4536     // new step size
4537     limitStepSize( data, 0.25 * distToIntersection );
4538     if ( data._stepSizeNodes[0] )
4539       data._stepSize = data._stepSizeCoeff *
4540         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4541
4542   } // while ( avgThick < 0.99 )
4543
4544   if ( nbSteps == 0 )
4545     return error("failed at the very first inflation step", data._index);
4546
4547   if ( avgThick < 0.99 )
4548   {
4549     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4550     {
4551       data._proxyMesh->_warning.reset
4552         ( new SMESH_ComputeError (COMPERR_WARNING,
4553                                   SMESH_Comment("Thickness ") << tgtThick <<
4554                                   " of viscous layers not reached,"
4555                                   " average reached thickness is " << avgThick*tgtThick));
4556     }
4557   }
4558
4559   // Restore position of src nodes moved by inflation on _noShrinkShapes
4560   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4561   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4562   {
4563     _EdgesOnShape& eos = data._edgesOnShape[iS];
4564     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4565       for ( size_t i = 0; i < eos._edges.size(); ++i )
4566       {
4567         restoreNoShrink( *eos._edges[ i ] );
4568       }
4569   }
4570   dumpFunctionEnd();
4571
4572   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4573 }
4574
4575 //================================================================================
4576 /*!
4577  * \brief Improve quality of layer inner surface and check intersection
4578  */
4579 //================================================================================
4580
4581 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4582                                      const int   infStep,
4583                                      double &    distToIntersection)
4584 {
4585   if ( data._nbShapesToSmooth == 0 )
4586     return true; // no shapes needing smoothing
4587
4588   bool moved, improved;
4589   double vol;
4590   vector< _LayerEdge* >    movedEdges, badEdges;
4591   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4592   vector< bool >           isConcaveFace;
4593
4594   SMESH_MesherHelper helper(*_mesh);
4595   Handle(ShapeAnalysis_Surface) surface;
4596   TopoDS_Face F;
4597
4598   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4599   {
4600     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4601
4602     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4603     {
4604       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4605       if ( !eos._toSmooth ||
4606            eos.ShapeType() != shapeType ||
4607            eos._edges.empty() )
4608         continue;
4609
4610       // already smoothed?
4611       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4612       // if ( !toSmooth ) continue;
4613
4614       if ( !eos._hyp.ToSmooth() )
4615       {
4616         // smooth disabled by the user; check validy only
4617         if ( !isFace ) continue;
4618         badEdges.clear();
4619         for ( size_t i = 0; i < eos._edges.size(); ++i )
4620         {
4621           _LayerEdge* edge = eos._edges[i];
4622           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4623             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4624             {
4625               // debugMsg( "-- Stop inflation. Bad simplex ("
4626               //           << " "<< edge->_nodes[0]->GetID()
4627               //           << " "<< edge->_nodes.back()->GetID()
4628               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4629               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4630               // return false;
4631               badEdges.push_back( edge );
4632             }
4633         }
4634         if ( !badEdges.empty() )
4635         {
4636           eosC1.resize(1);
4637           eosC1[0] = &eos;
4638           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4639           if ( nbBad > 0 )
4640             return false;
4641         }
4642         continue; // goto the next EDGE or FACE
4643       }
4644
4645       // prepare data
4646       if ( eos.SWOLType() == TopAbs_FACE )
4647       {
4648         if ( !F.IsSame( eos._sWOL )) {
4649           F = TopoDS::Face( eos._sWOL );
4650           helper.SetSubShape( F );
4651           surface = helper.GetSurface( F );
4652         }
4653       }
4654       else
4655       {
4656         F.Nullify(); surface.Nullify();
4657       }
4658       const TGeomID sInd = eos._shapeID;
4659
4660       // perform smoothing
4661
4662       if ( eos.ShapeType() == TopAbs_EDGE )
4663       {
4664         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4665
4666         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4667         {
4668           // smooth on EDGE's (normally we should not get here)
4669           int step = 0;
4670           do {
4671             moved = false;
4672             for ( size_t i = 0; i < eos._edges.size(); ++i )
4673             {
4674               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4675             }
4676             dumpCmd( SMESH_Comment("# end step ")<<step);
4677           }
4678           while ( moved && step++ < 5 );
4679         }
4680         dumpFunctionEnd();
4681       }
4682
4683       else // smooth on FACE
4684       {
4685         eosC1.clear();
4686         eosC1.push_back( & eos );
4687         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4688
4689         movedEdges.clear();
4690         isConcaveFace.resize( eosC1.size() );
4691         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4692         {
4693           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4694           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4695           for ( size_t i = 0; i < edges.size(); ++i )
4696             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4697                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4698               movedEdges.push_back( edges[i] );
4699
4700           makeOffsetSurface( *eosC1[ iEOS ], helper );
4701         }
4702
4703         int step = 0, stepLimit = 5, nbBad = 0;
4704         while (( ++step <= stepLimit ) || improved )
4705         {
4706           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4707                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4708           int oldBadNb = nbBad;
4709           badEdges.clear();
4710
4711 #ifdef INCREMENTAL_SMOOTH
4712           bool findBest = false; // ( step == stepLimit );
4713           for ( size_t i = 0; i < movedEdges.size(); ++i )
4714           {
4715             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4716             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4717               badEdges.push_back( movedEdges[i] );
4718           }
4719 #else
4720           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4721           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4722           {
4723             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4724             for ( size_t i = 0; i < edges.size(); ++i )
4725             {
4726               edges[i]->Unset( _LayerEdge::SMOOTHED );
4727               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4728                 badEdges.push_back( eos._edges[i] );
4729             }
4730           }
4731 #endif
4732           nbBad = badEdges.size();
4733
4734           if ( nbBad > 0 )
4735             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4736
4737           if ( !badEdges.empty() && step >= stepLimit / 2 )
4738           {
4739             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4740               stepLimit = 9;
4741
4742             // resolve hard smoothing situation around concave VERTEXes
4743             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4744             {
4745               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4746               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4747                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4748                                                          step, badEdges );
4749             }
4750             // look for the best smooth of _LayerEdge's neighboring badEdges
4751             nbBad = 0;
4752             for ( size_t i = 0; i < badEdges.size(); ++i )
4753             {
4754               _LayerEdge* ledge = badEdges[i];
4755               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4756               {
4757                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4758                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4759               }
4760               ledge->Unset( _LayerEdge::SMOOTHED );
4761               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4762             }
4763             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4764           }
4765
4766           if ( nbBad == oldBadNb  &&
4767                nbBad > 0 &&
4768                step < stepLimit ) // smooth w/o chech of validity
4769           {
4770             dumpFunctionEnd();
4771             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4772                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4773             for ( size_t i = 0; i < movedEdges.size(); ++i )
4774             {
4775               movedEdges[i]->SmoothWoCheck();
4776             }
4777             if ( stepLimit < 9 )
4778               stepLimit++;
4779           }
4780
4781           improved = ( nbBad < oldBadNb );
4782
4783           dumpFunctionEnd();
4784
4785           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4786             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4787             {
4788               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4789             }
4790
4791         } // smoothing steps
4792
4793         // project -- to prevent intersections or fix bad simplices
4794         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4795         {
4796           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4797             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4798         }
4799
4800         //if ( !badEdges.empty() )
4801         {
4802           badEdges.clear();
4803           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4804           {
4805             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4806             {
4807               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4808
4809               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4810               edge->CheckNeiborsOnBoundary( & badEdges );
4811               if (( nbBad > 0 ) ||
4812                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4813               {
4814                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4815                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4816                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4817                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4818                   {
4819                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4820                              << " "<< tgtXYZ._node->GetID()
4821                              << " "<< edge->_simplices[j]._nPrev->GetID()
4822                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4823                     badEdges.push_back( edge );
4824                     break;
4825                   }
4826               }
4827             }
4828           }
4829
4830           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4831           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4832
4833           if ( nbBad > 0 )
4834             return false;
4835         }
4836
4837       } // // smooth on FACE's
4838     } // loop on shapes
4839   } // smooth on [ EDGEs, FACEs ]
4840
4841   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4842   eosC1.resize(1);
4843   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4844   {
4845     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4846     if ( eos.ShapeType() == TopAbs_FACE ||
4847          eos._edges.empty() ||
4848          !eos._sWOL.IsNull() )
4849       continue;
4850
4851     badEdges.clear();
4852     for ( size_t i = 0; i < eos._edges.size(); ++i )
4853     {
4854       _LayerEdge*      edge = eos._edges[i];
4855       if ( edge->_nodes.size() < 2 ) continue;
4856       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4857       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4858       //const gp_XYZ& prevXYZ = edge->PrevPos();
4859       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4860         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4861         {
4862           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4863                    << " "<< tgtXYZ._node->GetID()
4864                    << " "<< edge->_simplices[j]._nPrev->GetID()
4865                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4866           badEdges.push_back( edge );
4867           break;
4868         }
4869     }
4870
4871     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4872     eosC1[0] = &eos;
4873     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4874     if ( nbBad > 0 )
4875       return false;
4876   }
4877
4878
4879   // Check if the last segments of _LayerEdge intersects 2D elements;
4880   // checked elements are either temporary faces or faces on surfaces w/o the layers
4881
4882   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4883     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4884                                            data._proxyMesh->GetFaces( data._solid )) );
4885
4886 #ifdef BLOCK_INFLATION
4887   const bool toBlockInfaltion = true;
4888 #else
4889   const bool toBlockInfaltion = false;
4890 #endif
4891   distToIntersection = Precision::Infinite();
4892   double dist;
4893   const SMDS_MeshElement* intFace = 0;
4894   const SMDS_MeshElement* closestFace = 0;
4895   _LayerEdge* le = 0;
4896   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4897   {
4898     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4899     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4900       continue;
4901     for ( size_t i = 0; i < eos._edges.size(); ++i )
4902     {
4903       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4904            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4905         continue;
4906       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4907       {
4908         return false;
4909         // commented due to "Illegal hash-positionPosition" error in NETGEN
4910         // on Debian60 on viscous_layers_01/B2 case
4911         // Collision; try to deflate _LayerEdge's causing it
4912         // badEdges.clear();
4913         // badEdges.push_back( eos._edges[i] );
4914         // eosC1[0] = & eos;
4915         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4916         // if ( nbBad > 0 )
4917         //   return false;
4918
4919         // badEdges.clear();
4920         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4921         // {
4922         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4923         //   {
4924         //     const SMDS_MeshElement* srcFace =
4925         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4926         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4927         //     while ( nIt->more() )
4928         //     {
4929         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4930         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4931         //       if ( n2e != data._n2eMap.end() )
4932         //         badEdges.push_back( n2e->second );
4933         //     }
4934         //     eosC1[0] = eof;
4935         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4936         //     if ( nbBad > 0 )
4937         //       return false;
4938         //   }
4939         // }
4940         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4941         //   return false;
4942         // else
4943         //   continue;
4944       }
4945       if ( !intFace )
4946       {
4947         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4948         debugMsg( msg );
4949         continue;
4950       }
4951
4952       const bool isShorterDist = ( distToIntersection > dist );
4953       if ( toBlockInfaltion || isShorterDist )
4954       {
4955         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4956         // lying on this _ConvexFace
4957         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4958           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4959             continue;
4960
4961         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4962         // ( avoid limiting the thickness on the case of issue 22576)
4963         if ( intFace->getshapeId() == eos._shapeID  )
4964           continue;
4965
4966         // ignore intersection with intFace of an adjacent FACE
4967         if ( dist > 0 )
4968         {
4969           bool toIgnore = false;
4970           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4971           {
4972             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4973             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4974             {
4975               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4976               for ( ; !toIgnore && edge.More(); edge.Next() )
4977                 // is adjacent - has a common EDGE
4978                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4979
4980               if ( toIgnore ) // check angle between normals
4981               {
4982                 gp_XYZ normal;
4983                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4984                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4985               }
4986             }
4987           }
4988           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4989           {
4990             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4991             {
4992               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4993               toIgnore = ( nInd >= 0 );
4994             }
4995           }
4996           if ( toIgnore )
4997             continue;
4998         }
4999
5000         // intersection not ignored
5001
5002         if ( toBlockInfaltion &&
5003              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5004         {
5005           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5006           eos._edges[i]->Block( data );                  // not to inflate
5007
5008           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5009           {
5010             // block _LayerEdge's, on top of which intFace is
5011             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5012             {
5013               const SMDS_MeshElement* srcFace =
5014                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5015               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5016               while ( nIt->more() )
5017               {
5018                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5019                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5020                 if ( n2e != data._n2eMap.end() )
5021                   n2e->second->Block( data );
5022               }
5023             }
5024           }
5025         }
5026
5027         if ( isShorterDist )
5028         {
5029           distToIntersection = dist;
5030           le = eos._edges[i];
5031           closestFace = intFace;
5032         }
5033
5034       } // if ( toBlockInfaltion || isShorterDist )
5035     } // loop on eos._edges
5036   } // loop on data._edgesOnShape
5037
5038   if ( closestFace && le )
5039   {
5040 #ifdef __myDEBUG
5041     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5042     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5043          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5044          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5045          << ") distance = " << distToIntersection<< endl;
5046 #endif
5047   }
5048
5049   return true;
5050 }
5051
5052 //================================================================================
5053 /*!
5054  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5055  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5056  *  \return int - resulting nb of bad _LayerEdge's
5057  */
5058 //================================================================================
5059
5060 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5061                                           SMESH_MesherHelper&       helper,
5062                                           vector< _LayerEdge* >&    badSmooEdges,
5063                                           vector< _EdgesOnShape* >& eosC1,
5064                                           const int                 infStep )
5065 {
5066   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5067
5068   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5069
5070   enum {
5071     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5072     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5073     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5074   };
5075   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5076
5077   double vol;
5078   bool haveInvalidated = true;
5079   while ( haveInvalidated )
5080   {
5081     haveInvalidated = false;
5082     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5083     {
5084       _LayerEdge*   edge = badSmooEdges[i];
5085       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5086       edge->Set( ADDED );
5087       bool invalidated = false;
5088       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5089       {
5090         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5091         edge->Block( data );
5092         edge->Set( INVALIDATED );
5093         edge->Unset( TO_INVALIDATE );
5094         invalidated = true;
5095         haveInvalidated = true;
5096       }
5097
5098       // look for _LayerEdge's of bad _simplices
5099       int nbBad = 0;
5100       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5101       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5102       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5103       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5104       {
5105         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5106             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5107           continue;
5108
5109         bool isBad = true;
5110         _LayerEdge* ee[2] = { 0,0 };
5111         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5112           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5113             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5114
5115         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5116         while ( maxNbSteps > edge->NbSteps() && isBad )
5117         {
5118           --maxNbSteps;
5119           for ( int iE = 0; iE < 2; ++iE )
5120           {
5121             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5122                  ee[ iE ]->NbSteps() > 1 )
5123             {
5124               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5125               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5126               ee[ iE ]->Block( data );
5127               ee[ iE ]->Set( INVALIDATED );
5128               haveInvalidated = true;
5129             }
5130           }
5131           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5132               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5133             isBad = false;
5134         }
5135         nbBad += isBad;
5136         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5137         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5138         ee[0]->Set( ADDED );
5139         ee[1]->Set( ADDED );
5140         if ( isBad )
5141         {
5142           ee[0]->Set( TO_INVALIDATE );
5143           ee[1]->Set( TO_INVALIDATE );
5144         }
5145       }
5146
5147       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5148       {
5149         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5150         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5151         edge->Block( data );
5152         edge->Set( INVALIDATED );
5153         edge->Unset( TO_INVALIDATE );
5154         haveInvalidated = true;
5155       }
5156     } // loop on badSmooEdges
5157   } // while ( haveInvalidated )
5158
5159   // re-smooth on analytical EDGEs
5160   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5161   {
5162     _LayerEdge* edge = badSmooEdges[i];
5163     if ( !edge->Is( INVALIDATED )) continue;
5164
5165     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5166     if ( eos->ShapeType() == TopAbs_VERTEX )
5167     {
5168       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5169       while ( const TopoDS_Shape* e = eIt->next() )
5170         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5171           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5172           {
5173             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5174             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5175             //   F       = TopoDS::Face( eoe->_sWOL );
5176             //   surface = helper.GetSurface( F );
5177             // }
5178             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5179             eoe->_edgeSmoother->_anaCurve.Nullify();
5180           }
5181     }
5182   }
5183
5184
5185   // check result of invalidation
5186
5187   int nbBad = 0;
5188   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5189   {
5190     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5191     {
5192       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5193       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5194       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5195       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5196       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5197         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5198         {
5199           ++nbBad;
5200           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5201                    << " "<< tgtXYZ._node->GetID()
5202                    << " "<< edge->_simplices[j]._nPrev->GetID()
5203                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5204         }
5205     }
5206   }
5207   dumpFunctionEnd();
5208
5209   return nbBad;
5210 }
5211
5212 //================================================================================
5213 /*!
5214  * \brief Create an offset surface
5215  */
5216 //================================================================================
5217
5218 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5219 {
5220   if ( eos._offsetSurf.IsNull() ||
5221        eos._edgeForOffset == 0 ||
5222        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5223     return;
5224
5225   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5226
5227   // find offset
5228   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5229   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5230   double offset = baseSurface->Gap();
5231
5232   eos._offsetSurf.Nullify();
5233
5234   try
5235   {
5236     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5237     if ( !offsetMaker.IsDone() ) return;
5238
5239     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5240     if ( !fExp.More() ) return;
5241
5242     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5243     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5244     if ( surf.IsNull() ) return;
5245
5246     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5247   }
5248   catch ( Standard_Failure )
5249   {
5250   }
5251 }
5252
5253 //================================================================================
5254 /*!
5255  * \brief Put nodes of a curved FACE to its offset surface
5256  */
5257 //================================================================================
5258
5259 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5260                                           int                       infStep,
5261                                           vector< _EdgesOnShape* >& eosC1,
5262                                           int                       smooStep,
5263                                           bool                      moveAll )
5264 {
5265   _EdgesOnShape * eof = & eos;
5266   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5267   {
5268     eof = 0;
5269     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5270     {
5271       if ( eosC1[i]->_offsetSurf.IsNull() ||
5272            eosC1[i]->ShapeType() != TopAbs_FACE ||
5273            eosC1[i]->_edgeForOffset == 0 ||
5274            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5275         continue;
5276       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5277         eof = eosC1[i];
5278     }
5279   }
5280   if ( !eof ||
5281        eof->_offsetSurf.IsNull() ||
5282        eof->ShapeType() != TopAbs_FACE ||
5283        eof->_edgeForOffset == 0 ||
5284        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5285     return;
5286
5287   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5288   for ( size_t i = 0; i < eos._edges.size(); ++i )
5289   {
5290     _LayerEdge* edge = eos._edges[i];
5291     edge->Unset( _LayerEdge::MARKED );
5292     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5293       continue;
5294     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5295         continue;
5296
5297     int nbBlockedAround = 0;
5298     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5299       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5300     if ( nbBlockedAround > 1 )
5301       continue;
5302
5303     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5304     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5305     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5306     edge->_curvature->_uv = uv;
5307     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5308
5309     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5310     gp_XYZ prevP = edge->PrevCheckPos();
5311     bool      ok = true;
5312     if ( !moveAll )
5313       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5314       {
5315         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5316       }
5317     if ( ok )
5318     {
5319       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5320       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5321       edge->_pos.back() = newP;
5322
5323       edge->Set( _LayerEdge::MARKED );
5324     }
5325   }
5326
5327 #ifdef _DEBUG_
5328   // dumpMove() for debug
5329   size_t i = 0;
5330   for ( ; i < eos._edges.size(); ++i )
5331     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5332       break;
5333   if ( i < eos._edges.size() )
5334   {
5335     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5336                  << "_InfStep" << infStep << "_" << smooStep );
5337     for ( ; i < eos._edges.size(); ++i )
5338     {
5339       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5340         dumpMove( eos._edges[i]->_nodes.back() );
5341     }
5342     dumpFunctionEnd();
5343   }
5344 #endif
5345 }
5346
5347 //================================================================================
5348 /*!
5349  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5350  *        _LayerEdge's to be in a consequent order
5351  */
5352 //================================================================================
5353
5354 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5355                                                 _EdgesOnShape&      eos,
5356                                                 SMESH_MesherHelper& helper)
5357 {
5358   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5359
5360   TopLoc_Location loc; double f,l;
5361
5362   Handle(Geom_Line)   line;
5363   Handle(Geom_Circle) circle;
5364   bool isLine, isCirc;
5365   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5366   {
5367     // check if the EDGE is a line
5368     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5369     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5370       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5371
5372     line   = Handle(Geom_Line)::DownCast( curve );
5373     circle = Handle(Geom_Circle)::DownCast( curve );
5374     isLine = (!line.IsNull());
5375     isCirc = (!circle.IsNull());
5376
5377     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5378     {
5379       isLine = SMESH_Algo::IsStraight( E );
5380
5381       if ( isLine )
5382         line = new Geom_Line( gp::OX() ); // only type does matter
5383     }
5384     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5385     {
5386       // TODO
5387     }
5388   }
5389   else //////////////////////////////////////////////////////////////////////// 2D case
5390   {
5391     if ( !eos._isRegularSWOL ) // 23190
5392       return NULL;
5393
5394     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5395
5396     // check if the EDGE is a line
5397     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5398     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5399       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5400
5401     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5402     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5403     isLine = (!line2d.IsNull());
5404     isCirc = (!circle2d.IsNull());
5405
5406     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5407     {
5408       Bnd_B2d bndBox;
5409       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5410       while ( nIt->more() )
5411         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5412       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5413
5414       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5415       for ( int i = 0; i < 2 && !isLine; ++i )
5416         isLine = ( size.Coord( i+1 ) <= lineTol );
5417     }
5418     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5419     {
5420       // TODO
5421     }
5422     if ( isLine )
5423     {
5424       line = new Geom_Line( gp::OX() ); // only type does matter
5425     }
5426     else if ( isCirc )
5427     {
5428       gp_Pnt2d p = circle2d->Location();
5429       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5430       circle = new Geom_Circle( ax, 1.); // only center position does matter
5431     }
5432   }
5433
5434   if ( isLine )
5435     return line;
5436   if ( isCirc )
5437     return circle;
5438
5439   return Handle(Geom_Curve)();
5440 }
5441
5442 //================================================================================
5443 /*!
5444  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5445  */
5446 //================================================================================
5447
5448 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5449                                       Handle(ShapeAnalysis_Surface)& surface,
5450                                       const TopoDS_Face&             F,
5451                                       SMESH_MesherHelper&            helper)
5452 {
5453   if ( !isAnalytic() ) return false;
5454
5455   const size_t iFrom = 0, iTo = _eos._edges.size();
5456
5457   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5458   {
5459     if ( F.IsNull() ) // 3D
5460     {
5461       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5462       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5463       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5464       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5465       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5466       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5467       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5468       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5469                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5470                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5471                          vLE1->Is( _LayerEdge::BLOCKED ));
5472       for ( size_t i = iFrom; i < iTo; ++i )
5473       {
5474         _LayerEdge*       edge = _eos._edges[i];
5475         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5476         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5477
5478         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5479         {
5480           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5481           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5482                             lineDir * ( curPos - pSrc0 ));
5483           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5484         }
5485         if ( edge->Is( _LayerEdge::BLOCKED ))
5486         {
5487           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5488           double curThick = pSrc.SquareDistance( tgtNode );
5489           double newThink = ( pSrc - newPos ).SquareModulus();
5490           if ( newThink > curThick )
5491             continue;
5492         }
5493         edge->_pos.back() = newPos;
5494         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5495         dumpMove( tgtNode );
5496       }
5497     }
5498     else // 2D
5499     {
5500       _LayerEdge* e0 = getLEdgeOnV( 0 );
5501       _LayerEdge* e1 = getLEdgeOnV( 1 );
5502       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5503       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5504       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5505       {
5506         int iPeriodic = helper.GetPeriodicIndex();
5507         if ( iPeriodic == 1 || iPeriodic == 2 )
5508         {
5509           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5510           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5511             std::swap( uv0, uv1 );
5512         }
5513       }
5514       const gp_XY rangeUV = uv1 - uv0;
5515       for ( size_t i = iFrom; i < iTo; ++i )
5516       {
5517         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5518         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5519         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5520
5521         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5522         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5523         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5524         dumpMove( tgtNode );
5525
5526         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5527         pos->SetUParameter( newUV.X() );
5528         pos->SetVParameter( newUV.Y() );
5529       }
5530     }
5531     return true;
5532   }
5533
5534   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5535   {
5536     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5537     gp_Pnt center3D = circle->Location();
5538
5539     if ( F.IsNull() ) // 3D
5540     {
5541       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5542         return true; // closed EDGE - nothing to do
5543
5544       // circle is a real curve of EDGE
5545       gp_Circ circ = circle->Circ();
5546
5547       // new center is shifted along its axis
5548       const gp_Dir& axis = circ.Axis().Direction();
5549       _LayerEdge*     e0 = getLEdgeOnV(0);
5550       _LayerEdge*     e1 = getLEdgeOnV(1);
5551       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5552       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5553       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5554       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5555       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5556
5557       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5558
5559       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5560       gp_Circ newCirc( newAxis, newRadius );
5561       gp_Vec  vecC1  ( newCenter, p1 );
5562
5563       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5564       if ( uLast < 0 )
5565         uLast += 2 * M_PI;
5566       
5567       for ( size_t i = iFrom; i < iTo; ++i )
5568       {
5569         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5570         double u = uLast * _leParams[i];
5571         gp_Pnt p = ElCLib::Value( u, newCirc );
5572         _eos._edges[i]->_pos.back() = p.XYZ();
5573
5574         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5575         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5576         dumpMove( tgtNode );
5577       }
5578       return true;
5579     }
5580     else // 2D
5581     {
5582       const gp_XY center( center3D.X(), center3D.Y() );
5583
5584       _LayerEdge* e0 = getLEdgeOnV(0);
5585       _LayerEdge* eM = _eos._edges[ 0 ];
5586       _LayerEdge* e1 = getLEdgeOnV(1);
5587       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5588       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5589       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5590       gp_Vec2d vec0( center, uv0 );
5591       gp_Vec2d vecM( center, uvM );
5592       gp_Vec2d vec1( center, uv1 );
5593       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5594       double uMidl = vec0.Angle( vecM );
5595       if ( uLast * uMidl <= 0. )
5596         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5597       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5598
5599       gp_Ax2d   axis( center, vec0 );
5600       gp_Circ2d circ( axis, radius );
5601       for ( size_t i = iFrom; i < iTo; ++i )
5602       {
5603         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5604         double    newU = uLast * _leParams[i];
5605         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5606         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5607
5608         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5609         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5610         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5611         dumpMove( tgtNode );
5612
5613         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5614         pos->SetUParameter( newUV.X() );
5615         pos->SetVParameter( newUV.Y() );
5616       }
5617     }
5618     return true;
5619   }
5620
5621   return false;
5622 }
5623
5624 //================================================================================
5625 /*!
5626  * \brief smooth _LayerEdge's on a an EDGE
5627  */
5628 //================================================================================
5629
5630 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5631                                      Handle(ShapeAnalysis_Surface)& surface,
5632                                      const TopoDS_Face&             F,
5633                                      SMESH_MesherHelper&            helper)
5634 {
5635   if ( _offPoints.empty() )
5636     return false;
5637
5638   // move _offPoints along normals of _LayerEdge's
5639
5640   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5641   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5642     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5643   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5644     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5645   _leOnV[0]._len = e[0]->_len;
5646   _leOnV[1]._len = e[1]->_len;
5647   for ( size_t i = 0; i < _offPoints.size(); i++ )
5648   {
5649     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5650     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5651     const double w0 = _offPoints[i]._2edges._wgt[0];
5652     const double w1 = _offPoints[i]._2edges._wgt[1];
5653     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5654     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5655     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5656     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5657          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5658       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5659
5660     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5661     _offPoints[i]._len  = avgLen;
5662   }
5663
5664   double fTol = 0;
5665   if ( !surface.IsNull() ) // project _offPoints to the FACE
5666   {
5667     fTol = 100 * BRep_Tool::Tolerance( F );
5668     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5669
5670     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5671     //if ( surface->Gap() < 0.5 * segLen )
5672       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5673
5674     for ( size_t i = 1; i < _offPoints.size(); ++i )
5675     {
5676       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5677       //if ( surface->Gap() < 0.5 * segLen )
5678         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5679     }
5680   }
5681
5682   // project tgt nodes of extreme _LayerEdge's to the offset segments
5683
5684   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5685   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5686
5687   gp_Pnt pExtreme[2], pProj[2];
5688   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5689   {
5690     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5691     int  i = _iSeg[ is2nd ];
5692     int di = is2nd ? -1 : +1;
5693     bool projected = false;
5694     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5695     int nbWorse = 0;
5696     do {
5697       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5698       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5699       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5700       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5701       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5702       if ( dist < distMin || projected )
5703       {
5704         _iSeg[ is2nd ] = i;
5705         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5706         distMin = dist;
5707       }
5708       else if ( dist > distPrev )
5709       {
5710         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5711           break;
5712       }
5713       distPrev = dist;
5714       i += di;
5715     }
5716     while ( !projected &&
5717             i >= 0 && i+1 < (int)_offPoints.size() );
5718
5719     if ( !projected )
5720     {
5721       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5722       {
5723         _iSeg[0] = 0;
5724         _iSeg[1] = _offPoints.size()-2;
5725         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5726         return false;
5727       }
5728     }
5729   }
5730   if ( _iSeg[0] > _iSeg[1] )
5731   {
5732     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5733     return false;
5734   }
5735
5736   // adjust length of extreme LE (test viscous_layers_01/B7)
5737   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5738   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5739   double d0 = vDiv0.Magnitude();
5740   double d1 = vDiv1.Magnitude();
5741   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5742   else                                   e[0]->_len -= d0;
5743   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5744   else                                   e[1]->_len -= d1;
5745
5746   // compute normalized length of the offset segments located between the projections
5747
5748   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5749   vector< double > len( nbSeg + 1 );
5750   len[ iSeg++ ] = 0;
5751   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5752   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5753   {
5754     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5755   }
5756   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5757
5758   // d0 *= e[0]->_lenFactor;
5759   // d1 *= e[1]->_lenFactor;
5760   double fullLen = len.back() - d0 - d1;
5761   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5762     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5763
5764   // temporary replace extreme _offPoints by pExtreme
5765   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5766                    _offPoints[ _iSeg[1]+1 ]._xyz };
5767   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5768   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5769
5770   // distribute tgt nodes of _LayerEdge's between the projections
5771
5772   iSeg = 0;
5773   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5774   {
5775     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5776     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5777       iSeg++;
5778     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5779     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5780                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5781
5782     if ( surface.IsNull() )
5783     {
5784       _eos._edges[i]->_pos.back() = p;
5785     }
5786     else // project a new node position to a FACE
5787     {
5788       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5789       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5790
5791       p = surface->Value( uv2 ).XYZ();
5792       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5793     }
5794     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5795     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5796     dumpMove( tgtNode );
5797   }
5798
5799   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5800   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5801
5802   return true;
5803 }
5804
5805 //================================================================================
5806 /*!
5807  * \brief Prepare for smoothing
5808  */
5809 //================================================================================
5810
5811 void _Smoother1D::prepare(_SolidData& data)
5812 {
5813   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5814   _curveLen = SMESH_Algo::EdgeLength( E );
5815
5816   // sort _LayerEdge's by position on the EDGE
5817   data.SortOnEdge( E, _eos._edges );
5818
5819   // compute normalized param of _eos._edges on EDGE
5820   _leParams.resize( _eos._edges.size() + 1 );
5821   {
5822     double curLen;
5823     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5824     _leParams[0] = 0;
5825     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5826     {
5827       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5828       curLen         = p.Distance( pPrev );
5829       _leParams[i+1] = _leParams[i] + curLen;
5830       pPrev          = p;
5831     }
5832     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5833     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5834       _leParams[i] = _leParams[i+1] / fullLen;
5835   }
5836
5837   if ( isAnalytic() )
5838     return;
5839
5840   // divide E to have offset segments with low deflection
5841   BRepAdaptor_Curve c3dAdaptor( E );
5842   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5843   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5844   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5845   if ( discret.NbPoints() <= 2 )
5846   {
5847     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5848     return;
5849   }
5850
5851   const double u0 = c3dAdaptor.FirstParameter();
5852   gp_Pnt p; gp_Vec tangent;
5853   _offPoints.resize( discret.NbPoints() );
5854   for ( size_t i = 0; i < _offPoints.size(); i++ )
5855   {
5856     double u = discret.Parameter( i+1 );
5857     c3dAdaptor.D1( u, p, tangent );
5858     _offPoints[i]._xyz     = p.XYZ();
5859     _offPoints[i]._edgeDir = tangent.XYZ();
5860     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5861   }
5862
5863   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5864
5865   // set _2edges
5866   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5867   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5868   _2NearEdges tmp2edges;
5869   tmp2edges._edges[1] = _eos._edges[0];
5870   _leOnV[0]._2neibors = & tmp2edges;
5871   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5872   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5873   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5874   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5875   {
5876     // find _LayerEdge's located before and after an offset point
5877     // (_eos._edges[ iLE ] is next after ePrev)
5878     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5879       ePrev = _eos._edges[ iLE++ ];
5880     eNext = ePrev->_2neibors->_edges[1];
5881
5882     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5883     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5884     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5885     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5886   }
5887
5888   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5889   for ( size_t i = 0; i < _offPoints.size(); i++ )
5890     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5891       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5892     else break;
5893   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5894     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5895       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5896     else break;
5897
5898   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5899
5900   int iLBO = _offPoints.size() - 2; // last but one
5901
5902   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5903   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5904
5905   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5906   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5907   _leOnV[ 0 ]._len = 0;
5908   _leOnV[ 1 ]._len = 0;
5909   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5910   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5911
5912   _iSeg[0] = 0;
5913   _iSeg[1] = _offPoints.size()-2;
5914
5915   // initialize OffPnt::_len
5916   for ( size_t i = 0; i < _offPoints.size(); ++i )
5917     _offPoints[i]._len = 0;
5918
5919   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5920   {
5921     _leOnV[0]._len = leOnV[0]->_len;
5922     _leOnV[1]._len = leOnV[1]->_len;
5923     for ( size_t i = 0; i < _offPoints.size(); i++ )
5924     {
5925       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5926       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5927       const double w0 = _offPoints[i]._2edges._wgt[0];
5928       const double w1 = _offPoints[i]._2edges._wgt[1];
5929       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5930       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5931                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5932       _offPoints[i]._xyz = avgXYZ;
5933       _offPoints[i]._len = avgLen;
5934     }
5935   }
5936 }
5937
5938 //================================================================================
5939 /*!
5940  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5941  */
5942 //================================================================================
5943
5944 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5945                                      const gp_XYZ&  edgeDir)
5946 {
5947   gp_XYZ cross = normal ^ edgeDir;
5948   gp_XYZ  norm = edgeDir ^ cross;
5949   double  size = norm.Modulus();
5950
5951   return norm / size;
5952 }
5953
5954 //================================================================================
5955 /*!
5956  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5957  */
5958 //================================================================================
5959
5960 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5961                              vector< _LayerEdge* >& edges)
5962 {
5963   map< double, _LayerEdge* > u2edge;
5964   for ( size_t i = 0; i < edges.size(); ++i )
5965     u2edge.insert( u2edge.end(),
5966                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5967
5968   ASSERT( u2edge.size() == edges.size() );
5969   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5970   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5971     edges[i] = u2e->second;
5972
5973   Sort2NeiborsOnEdge( edges );
5974 }
5975
5976 //================================================================================
5977 /*!
5978  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5979  */
5980 //================================================================================
5981
5982 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5983 {
5984   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5985
5986   for ( size_t i = 0; i < edges.size()-1; ++i )
5987     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5988       edges[i]->_2neibors->reverse();
5989
5990   const size_t iLast = edges.size() - 1;
5991   if ( edges.size() > 1 &&
5992        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5993     edges[iLast]->_2neibors->reverse();
5994 }
5995
5996 //================================================================================
5997 /*!
5998  * \brief Return _EdgesOnShape* corresponding to the shape
5999  */
6000 //================================================================================
6001
6002 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6003 {
6004   if ( shapeID < (int)_edgesOnShape.size() &&
6005        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6006     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6007
6008   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6009     if ( _edgesOnShape[i]._shapeID == shapeID )
6010       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6011
6012   return 0;
6013 }
6014
6015 //================================================================================
6016 /*!
6017  * \brief Return _EdgesOnShape* corresponding to the shape
6018  */
6019 //================================================================================
6020
6021 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6022 {
6023   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6024   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6025 }
6026
6027 //================================================================================
6028 /*!
6029  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6030  */
6031 //================================================================================
6032
6033 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6034 {
6035   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6036
6037   set< TGeomID > vertices;
6038   TopoDS_Face F;
6039   if ( eos->ShapeType() == TopAbs_FACE )
6040   {
6041     // check FACE concavity and get concave VERTEXes
6042     F = TopoDS::Face( eos->_shape );
6043     if ( isConcave( F, helper, &vertices ))
6044       _concaveFaces.insert( eos->_shapeID );
6045
6046     // set eos._eosConcaVer
6047     eos->_eosConcaVer.clear();
6048     eos->_eosConcaVer.reserve( vertices.size() );
6049     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6050     {
6051       _EdgesOnShape* eov = GetShapeEdges( *v );
6052       if ( eov && eov->_edges.size() == 1 )
6053       {
6054         eos->_eosConcaVer.push_back( eov );
6055         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6056           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6057       }
6058     }
6059
6060     // SetSmooLen() to _LayerEdge's on FACE
6061     for ( size_t i = 0; i < eos->_edges.size(); ++i )
6062     {
6063       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6064     }
6065     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6066     while ( smIt->more() ) // loop on sub-shapes of the FACE
6067     {
6068       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6069       if ( !eoe ) continue;
6070
6071       vector<_LayerEdge*>& eE = eoe->_edges;
6072       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6073       {
6074         if ( eE[iE]->_cosin <= theMinSmoothCosin )
6075           continue;
6076
6077         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6078         while ( segIt->more() )
6079         {
6080           const SMDS_MeshElement* seg = segIt->next();
6081           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6082             continue;
6083           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6084             continue; // not to check a seg twice
6085           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6086           {
6087             _LayerEdge* eN = eE[iE]->_neibors[iN];
6088             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6089               continue;
6090             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6091             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6092             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6093             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6094           }
6095         }
6096       }
6097     }
6098   } // if ( eos->ShapeType() == TopAbs_FACE )
6099
6100   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6101   {
6102     eos->_edges[i]->_smooFunction = 0;
6103     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6104   }
6105   bool isCurved = false;
6106   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6107   {
6108     _LayerEdge* edge = eos->_edges[i];
6109
6110     // get simplices sorted
6111     _Simplex::SortSimplices( edge->_simplices );
6112
6113     // smoothing function
6114     edge->ChooseSmooFunction( vertices, _n2eMap );
6115
6116     // set _curvature
6117     double avgNormProj = 0, avgLen = 0;
6118     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6119     {
6120       _Simplex& s = edge->_simplices[iS];
6121
6122       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6123       avgNormProj += edge->_normal * vec;
6124       avgLen      += vec.Modulus();
6125       if ( substituteSrcNodes )
6126       {
6127         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6128         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6129       }
6130     }
6131     avgNormProj /= edge->_simplices.size();
6132     avgLen      /= edge->_simplices.size();
6133     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6134     {
6135       isCurved = true;
6136       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6137       if ( !fPos )
6138         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6139           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6140       if ( fPos )
6141         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6142     }
6143   }
6144
6145   // prepare for putOnOffsetSurface()
6146   if (( eos->ShapeType() == TopAbs_FACE ) &&
6147       ( isCurved || !eos->_eosConcaVer.empty() ))
6148   {
6149     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6150     eos->_edgeForOffset = 0;
6151
6152     double maxCosin = -1;
6153     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6154     {
6155       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6156       if ( !eoe || eoe->_edges.empty() ) continue;
6157
6158       vector<_LayerEdge*>& eE = eoe->_edges;
6159       _LayerEdge* e = eE[ eE.size() / 2 ];
6160       if ( e->_cosin > maxCosin )
6161       {
6162         eos->_edgeForOffset = e;
6163         maxCosin = e->_cosin;
6164       }
6165     }
6166   }
6167 }
6168
6169 //================================================================================
6170 /*!
6171  * \brief Add faces for smoothing
6172  */
6173 //================================================================================
6174
6175 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6176                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6177 {
6178   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6179   for ( ; eos != eosToSmooth.end(); ++eos )
6180   {
6181     if ( !*eos || (*eos)->_toSmooth ) continue;
6182
6183     (*eos)->_toSmooth = true;
6184
6185     if ( (*eos)->ShapeType() == TopAbs_FACE )
6186     {
6187       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6188       (*eos)->_toSmooth = true;
6189     }
6190   }
6191
6192   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6193   if ( edgesNoAnaSmooth )
6194     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6195     {
6196       if ( (*eos)->_edgeSmoother )
6197         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6198     }
6199 }
6200
6201 //================================================================================
6202 /*!
6203  * \brief Limit _LayerEdge::_maxLen according to local curvature
6204  */
6205 //================================================================================
6206
6207 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6208 {
6209   // find intersection of neighbor _LayerEdge's to limit _maxLen
6210   // according to local curvature (IPAL52648)
6211
6212   // This method must be called after findCollisionEdges() where _LayerEdge's
6213   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6214
6215   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6216   {
6217     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6218     if ( eosI._edges.empty() ) continue;
6219     if ( !eosI._hyp.ToSmooth() )
6220     {
6221       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6222       {
6223         _LayerEdge* eI = eosI._edges[i];
6224         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6225         {
6226           _LayerEdge* eN = eI->_neibors[iN];
6227           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6228           {
6229             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6230             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6231           }
6232         }
6233       }
6234     }
6235     else if ( eosI.ShapeType() == TopAbs_EDGE )
6236     {
6237       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6238       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6239
6240       _LayerEdge* e0 = eosI._edges[0];
6241       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6242       {
6243         _LayerEdge* eI = eosI._edges[i];
6244         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6245         e0 = eI;
6246       }
6247     }
6248   }
6249 }
6250
6251 //================================================================================
6252 /*!
6253  * \brief Limit _LayerEdge::_maxLen according to local curvature
6254  */
6255 //================================================================================
6256
6257 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6258                                               _LayerEdge*         e2,
6259                                               _EdgesOnShape&      eos1,
6260                                               _EdgesOnShape&      eos2,
6261                                               SMESH_MesherHelper& helper )
6262 {
6263   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6264   double norSize = plnNorm.SquareModulus();
6265   if ( norSize < std::numeric_limits<double>::min() )
6266     return; // parallel normals
6267
6268   // find closest points of skew _LayerEdge's
6269   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6270   gp_XYZ dir12 = src2 - src1;
6271   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6272   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6273   double  dot1 = perp2 * e1->_normal;
6274   double  dot2 = perp1 * e2->_normal;
6275   double    u1 =   ( perp2 * dir12 ) / dot1;
6276   double    u2 = - ( perp1 * dir12 ) / dot2;
6277   if ( u1 > 0 && u2 > 0 )
6278   {
6279     double ovl = ( u1 * e1->_normal * dir12 -
6280                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6281     if ( ovl > theSmoothThickToElemSizeRatio )
6282     {    
6283       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6284       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6285     }
6286   }
6287 }
6288
6289 //================================================================================
6290 /*!
6291  * \brief Fill data._collisionEdges
6292  */
6293 //================================================================================
6294
6295 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6296 {
6297   data._collisionEdges.clear();
6298
6299   // set the full thickness of the layers to LEs
6300   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6301   {
6302     _EdgesOnShape& eos = data._edgesOnShape[iS];
6303     if ( eos._edges.empty() ) continue;
6304     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6305
6306     for ( size_t i = 0; i < eos._edges.size(); ++i )
6307     {
6308       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6309       double maxLen = eos._edges[i]->_maxLen;
6310       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6311       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6312       eos._edges[i]->_maxLen = maxLen;
6313     }
6314   }
6315
6316   // make temporary quadrangles got by extrusion of
6317   // mesh edges along _LayerEdge._normal's
6318
6319   vector< const SMDS_MeshElement* > tmpFaces;
6320
6321   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6322   {
6323     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6324     if ( eos.ShapeType() != TopAbs_EDGE )
6325       continue;
6326     if ( eos._edges.empty() )
6327     {
6328       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6329       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6330       while ( smIt->more() )
6331         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6332           if ( eov->_edges.size() == 1 )
6333             edge[ bool( edge[0]) ] = eov->_edges[0];
6334
6335       if ( edge[1] )
6336       {
6337         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6338         tmpFaces.push_back( f );
6339       }
6340     }
6341     for ( size_t i = 0; i < eos._edges.size(); ++i )
6342     {
6343       _LayerEdge* edge = eos._edges[i];
6344       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6345       {
6346         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6347         if ( src2->GetPosition()->GetDim() > 0 &&
6348              src2->GetID() < edge->_nodes[0]->GetID() )
6349           continue; // avoid using same segment twice
6350
6351         // a _LayerEdge containg tgt2
6352         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6353
6354         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6355         tmpFaces.push_back( f );
6356       }
6357     }
6358   }
6359
6360   // Find _LayerEdge's intersecting tmpFaces.
6361
6362   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6363                                                             tmpFaces.end()));
6364   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6365     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6366
6367   double dist1, dist2, segLen, eps = 0.5;
6368   _CollisionEdges collEdges;
6369   vector< const SMDS_MeshElement* > suspectFaces;
6370   const double angle45 = Cos( 45. * M_PI / 180. );
6371
6372   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6373   {
6374     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6375     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6376       continue;
6377     // find sub-shapes whose VL can influence VL on eos
6378     set< TGeomID > neighborShapes;
6379     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6380     while ( const TopoDS_Shape* face = fIt->next() )
6381     {
6382       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6383       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6384       {
6385         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6386         while ( subIt->more() )
6387           neighborShapes.insert( subIt->next()->GetId() );
6388       }
6389     }
6390     if ( eos.ShapeType() == TopAbs_VERTEX )
6391     {
6392       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6393       while ( const TopoDS_Shape* edge = eIt->next() )
6394         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6395     }
6396     // find intersecting _LayerEdge's
6397     for ( size_t i = 0; i < eos._edges.size(); ++i )
6398     {
6399       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6400       _LayerEdge*   edge = eos._edges[i];
6401       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6402       segLen *= 1.2;
6403
6404       gp_Vec eSegDir0, eSegDir1;
6405       if ( edge->IsOnEdge() )
6406       {
6407         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6408         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6409         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6410       }
6411       suspectFaces.clear();
6412       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6413                                      SMDSAbs_Face, suspectFaces );
6414       collEdges._intEdges.clear();
6415       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6416       {
6417         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6418         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6419         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6420         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6421         if ( edge->IsOnEdge() ) {
6422           if ( edge->_2neibors->include( f->_le1 ) ||
6423                edge->_2neibors->include( f->_le2 )) continue;
6424         }
6425         else {
6426           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6427               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6428         }
6429         dist1 = dist2 = Precision::Infinite();
6430         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6431           dist1 = Precision::Infinite();
6432         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6433           dist2 = Precision::Infinite();
6434         if (( dist1 > segLen ) && ( dist2 > segLen ))
6435           continue;
6436
6437         if ( edge->IsOnEdge() )
6438         {
6439           // skip perpendicular EDGEs
6440           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6441           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6442                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6443                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6444                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6445           if ( !isParallel )
6446             continue;
6447         }
6448
6449         // either limit inflation of edges or remember them for updating _normal
6450         // double dot = edge->_normal * f->GetDir();
6451         // if ( dot > 0.1 )
6452         {
6453           collEdges._intEdges.push_back( f->_le1 );
6454           collEdges._intEdges.push_back( f->_le2 );
6455         }
6456         // else
6457         // {
6458         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6459         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6460         // }
6461       }
6462
6463       if ( !collEdges._intEdges.empty() )
6464       {
6465         collEdges._edge = edge;
6466         data._collisionEdges.push_back( collEdges );
6467       }
6468     }
6469   }
6470
6471   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6472     delete tmpFaces[i];
6473
6474   // restore the zero thickness
6475   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6476   {
6477     _EdgesOnShape& eos = data._edgesOnShape[iS];
6478     if ( eos._edges.empty() ) continue;
6479     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6480
6481     for ( size_t i = 0; i < eos._edges.size(); ++i )
6482     {
6483       eos._edges[i]->InvalidateStep( 1, eos );
6484       eos._edges[i]->_len = 0;
6485     }
6486   }
6487 }
6488
6489 //================================================================================
6490 /*!
6491  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6492  * _LayerEdge's on neighbor EDGE's
6493  */
6494 //================================================================================
6495
6496 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6497                                      SMESH_MesherHelper& helper,
6498                                      int                 stepNb,
6499                                      double              stepSize)
6500 {
6501   updateNormalsOfC1Vertices( data );
6502
6503   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6504     return false;
6505
6506   // map to store new _normal and _cosin for each intersected edge
6507   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6508   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6509   _LayerEdge zeroEdge;
6510   zeroEdge._normal.SetCoord( 0,0,0 );
6511   zeroEdge._maxLen = Precision::Infinite();
6512   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6513
6514   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6515
6516   double segLen, dist1, dist2, dist;
6517   vector< pair< _LayerEdge*, double > > intEdgesDist;
6518   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6519
6520   for ( int iter = 0; iter < 5; ++iter )
6521   {
6522     edge2newEdge.clear();
6523
6524     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6525     {
6526       _CollisionEdges& ce = data._collisionEdges[iE];
6527       _LayerEdge*   edge1 = ce._edge;
6528       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6529       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6530       if ( !eos1 ) continue;
6531
6532       // detect intersections
6533       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6534       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6535       double     eps = 0.5;
6536       intEdgesDist.clear();
6537       double minIntDist = Precision::Infinite();
6538       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6539       {
6540         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6541              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6542              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6543           continue;
6544         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6545         double fact = ( 1.1 + dot * dot );
6546         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6547         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6548         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6549         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6550         dist1 = dist2 = Precision::Infinite();
6551         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6552              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6553           continue;
6554         dist = dist1;
6555         if ( dist > testLen || dist <= 0 )
6556         {
6557           dist = dist2;
6558           if ( dist > testLen || dist <= 0 )
6559             continue;
6560         }
6561         // choose a closest edge
6562         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6563         double d1 = intP.SquareDistance( pSrc0 );
6564         double d2 = intP.SquareDistance( pSrc1 );
6565         int iClose = i + ( d2 < d1 );
6566         _LayerEdge* edge2 = ce._intEdges[iClose];
6567         edge2->Unset( _LayerEdge::MARKED );
6568
6569         // choose a closest edge among neighbors
6570         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6571         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6572         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6573         {
6574           _LayerEdge * edgeJ = intEdgesDist[j].first;
6575           if ( edge2->IsNeiborOnEdge( edgeJ ))
6576           {
6577             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6578             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6579           }
6580         }
6581         intEdgesDist.push_back( make_pair( edge2, dist ));
6582         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6583         // {
6584         //   iClose = i + !( d2 < d1 );
6585         //   intEdges.push_back( ce._intEdges[iClose] );
6586         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6587         // }
6588         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6589       }
6590
6591       //ce._edge = 0;
6592
6593       // compute new _normals
6594       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6595       {
6596         _LayerEdge* edge2    = intEdgesDist[i].first;
6597         double       distWgt = edge1->_len / intEdgesDist[i].second;
6598         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6599         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6600         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6601         edge2->Set( _LayerEdge::MARKED );
6602
6603         // get a new normal
6604         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6605
6606         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6607         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6608         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6609         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6610         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6611         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6612         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6613         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6614         newNormal.Normalize();
6615
6616         // get new cosin
6617         double newCos;
6618         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6619         if ( cos1 < theMinSmoothCosin )
6620         {
6621           newCos = cos2 * sgn1;
6622         }
6623         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6624         {
6625           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6626         }
6627         else
6628         {
6629           newCos = edge1->_cosin;
6630         }
6631
6632         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6633         e2neIt->second._normal += distWgt * newNormal;
6634         e2neIt->second._cosin   = newCos;
6635         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6636         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6637           e2neIt->second._normal += dir2;
6638         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6639         e2neIt->second._normal += distWgt * newNormal;
6640         e2neIt->second._cosin   = edge2->_cosin;
6641         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6642           e2neIt->second._normal += dir1;
6643       }
6644     }
6645
6646     if ( edge2newEdge.empty() )
6647       break; //return true;
6648
6649     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6650
6651     // Update data of edges depending on a new _normal
6652
6653     data.UnmarkEdges();
6654     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6655     {
6656       _LayerEdge*    edge = e2neIt->first;
6657       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6658       _LayerEdge& newEdge = e2neIt->second;
6659       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6660
6661       // Check if a new _normal is OK:
6662       newEdge._normal.Normalize();
6663       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6664       {
6665         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6666         {
6667           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6668           edge->_maxLen = newEdge._maxLen;
6669           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6670         }
6671         continue; // the new _normal is bad
6672       }
6673       // the new _normal is OK
6674
6675       // find shapes that need smoothing due to change of _normal
6676       if ( edge->_cosin   < theMinSmoothCosin &&
6677            newEdge._cosin > theMinSmoothCosin )
6678       {
6679         if ( eos->_sWOL.IsNull() )
6680         {
6681           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6682           while ( fIt->more() )
6683             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6684         }
6685         else // edge inflates along a FACE
6686         {
6687           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6688           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
6689           while ( const TopoDS_Shape* E = eIt->next() )
6690           {
6691             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6692             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6693             if ( angle < M_PI / 2 )
6694               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6695           }
6696         }
6697       }
6698
6699       double len = edge->_len;
6700       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6701       edge->SetNormal( newEdge._normal );
6702       edge->SetCosin( newEdge._cosin );
6703       edge->SetNewLength( len, *eos, helper );
6704       edge->Set( _LayerEdge::MARKED );
6705       edge->Set( _LayerEdge::NORMAL_UPDATED );
6706       edgesNoAnaSmooth.insert( eos );
6707     }
6708
6709     // Update normals and other dependent data of not intersecting _LayerEdge's
6710     // neighboring the intersecting ones
6711
6712     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6713     {
6714       _LayerEdge*   edge1 = e2neIt->first;
6715       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6716       if ( !edge1->Is( _LayerEdge::MARKED ))
6717         continue;
6718
6719       if ( edge1->IsOnEdge() )
6720       {
6721         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6722         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6723         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6724       }
6725
6726       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6727         continue;
6728       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6729       {
6730         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6731         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6732           continue; // j-th neighbor is also intersected
6733         _LayerEdge* prevEdge = edge1;
6734         const int nbSteps = 10;
6735         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6736         {
6737           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6738                neighbor->Is( _LayerEdge::MARKED ))
6739             break;
6740           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6741           if ( !eos ) continue;
6742           _LayerEdge* nextEdge = neighbor;
6743           if ( neighbor->_2neibors )
6744           {
6745             int iNext = 0;
6746             nextEdge = neighbor->_2neibors->_edges[iNext];
6747             if ( nextEdge == prevEdge )
6748               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6749           }
6750           double r = double(step-1)/nbSteps/(iter+1);
6751           if ( !nextEdge->_2neibors )
6752             r = Min( r, 0.5 );
6753
6754           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6755           newNorm.Normalize();
6756           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6757             break;
6758
6759           double len = neighbor->_len;
6760           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6761           neighbor->SetNormal( newNorm );
6762           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6763           if ( neighbor->_2neibors )
6764             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6765           neighbor->SetNewLength( len, *eos, helper );
6766           neighbor->Set( _LayerEdge::MARKED );
6767           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6768           edgesNoAnaSmooth.insert( eos );
6769
6770           if ( !neighbor->_2neibors )
6771             break; // neighbor is on VERTEX
6772
6773           // goto the next neighbor
6774           prevEdge = neighbor;
6775           neighbor = nextEdge;
6776         }
6777       }
6778     }
6779     dumpFunctionEnd();
6780   } // iterations
6781
6782   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6783
6784   return true;
6785 }
6786
6787 //================================================================================
6788 /*!
6789  * \brief Check if a new normal is OK
6790  */
6791 //================================================================================
6792
6793 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6794                                      _LayerEdge&   edge,
6795                                      const gp_XYZ& newNormal)
6796 {
6797   // check a min angle between the newNormal and surrounding faces
6798   vector<_Simplex> simplices;
6799   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6800   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6801   double newMinDot = 1, curMinDot = 1;
6802   for ( size_t i = 0; i < simplices.size(); ++i )
6803   {
6804     n1.Set( simplices[i]._nPrev );
6805     n2.Set( simplices[i]._nNext );
6806     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6807     double normLen2 = normFace.SquareModulus();
6808     if ( normLen2 < std::numeric_limits<double>::min() )
6809       continue;
6810     normFace /= Sqrt( normLen2 );
6811     newMinDot = Min( newNormal    * normFace, newMinDot );
6812     curMinDot = Min( edge._normal * normFace, curMinDot );
6813   }
6814   bool ok = true;
6815   if ( newMinDot < 0.5 )
6816   {
6817     ok = ( newMinDot >= curMinDot * 0.9 );
6818     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6819     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6820     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6821   }
6822
6823   return ok;
6824 }
6825
6826 //================================================================================
6827 /*!
6828  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6829  */
6830 //================================================================================
6831
6832 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6833                                                SMESH_MesherHelper& helper,
6834                                                const int           nbSteps,
6835                                                const double        stepSize )
6836 {
6837   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6838     return true; // no shapes needing smoothing
6839
6840   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6841   {
6842     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6843     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6844          !eos._hyp.ToSmooth() ||
6845          eos.ShapeType() != TopAbs_FACE ||
6846          eos._edges.empty() )
6847       continue;
6848
6849     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6850     if ( !toSmooth ) continue;
6851
6852     for ( size_t i = 0; i < eos._edges.size(); ++i )
6853     {
6854       _LayerEdge* edge = eos._edges[i];
6855       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6856         continue;
6857       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6858         continue;
6859
6860       const gp_XYZ& pPrev = edge->PrevPos();
6861       const gp_XYZ& pLast = edge->_pos.back();
6862       gp_XYZ      stepVec = pLast - pPrev;
6863       double realStepSize = stepVec.Modulus();
6864       if ( realStepSize < numeric_limits<double>::min() )
6865         continue;
6866
6867       edge->_lenFactor = realStepSize / stepSize;
6868       edge->_normal    = stepVec / realStepSize;
6869       edge->Set( _LayerEdge::NORMAL_UPDATED );
6870     }
6871   }
6872
6873   return true;
6874 }
6875
6876 //================================================================================
6877 /*!
6878  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6879  */
6880 //================================================================================
6881
6882 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6883 {
6884   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6885   {
6886     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6887     if ( eov._eosC1.empty() ||
6888          eov.ShapeType() != TopAbs_VERTEX ||
6889          eov._edges.empty() )
6890       continue;
6891
6892     gp_XYZ newNorm   = eov._edges[0]->_normal;
6893     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6894     bool normChanged = false;
6895
6896     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6897     {
6898       _EdgesOnShape*   eoe = eov._eosC1[i];
6899       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6900       const double    eLen = SMESH_Algo::EdgeLength( e );
6901       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6902       if ( oppV.IsSame( eov._shape ))
6903         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6904       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6905       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6906       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6907
6908       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6909       if ( curThickOpp + curThick < eLen )
6910         continue;
6911
6912       double wgt = 2. * curThick / eLen;
6913       newNorm += wgt * eovOpp->_edges[0]->_normal;
6914       normChanged = true;
6915     }
6916     if ( normChanged )
6917     {
6918       eov._edges[0]->SetNormal( newNorm.Normalized() );
6919       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6920     }
6921   }
6922 }
6923
6924 //================================================================================
6925 /*!
6926  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6927  */
6928 //================================================================================
6929
6930 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6931                                                   SMESH_MesherHelper& helper,
6932                                                   int                 stepNb )
6933 {
6934   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6935   bool isOK;
6936
6937   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6938   for ( ; id2face != data._convexFaces.end(); ++id2face )
6939   {
6940     _ConvexFace & convFace = (*id2face).second;
6941     if ( convFace._normalsFixed )
6942       continue; // already fixed
6943     if ( convFace.CheckPrisms() )
6944       continue; // nothing to fix
6945
6946     convFace._normalsFixed = true;
6947
6948     BRepAdaptor_Surface surface ( convFace._face, false );
6949     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6950
6951     // check if the convex FACE is of spherical shape
6952
6953     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6954     Bnd_B3d nodesBox;
6955     gp_Pnt  center;
6956
6957     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6958     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6959     {
6960       _EdgesOnShape& eos = *(id2eos->second);
6961       if ( eos.ShapeType() == TopAbs_VERTEX )
6962       {
6963         _LayerEdge* ledge = eos._edges[ 0 ];
6964         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6965           centersBox.Add( center );
6966       }
6967       for ( size_t i = 0; i < eos._edges.size(); ++i )
6968         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6969     }
6970     if ( centersBox.IsVoid() )
6971     {
6972       debugMsg( "Error: centersBox.IsVoid()" );
6973       return false;
6974     }
6975     const bool isSpherical =
6976       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6977
6978     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6979     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6980
6981     if ( isSpherical )
6982     {
6983       // set _LayerEdge::_normal as average of all normals
6984
6985       // WARNING: different density of nodes on EDGEs is not taken into account that
6986       // can lead to an improper new normal
6987
6988       gp_XYZ avgNormal( 0,0,0 );
6989       nbEdges = 0;
6990       id2eos = convFace._subIdToEOS.begin();
6991       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6992       {
6993         _EdgesOnShape& eos = *(id2eos->second);
6994         // set data of _CentralCurveOnEdge
6995         if ( eos.ShapeType() == TopAbs_EDGE )
6996         {
6997           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6998           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6999           if ( !eos._sWOL.IsNull() )
7000             ceCurve._adjFace.Nullify();
7001           else
7002             ceCurve._ledges.insert( ceCurve._ledges.end(),
7003                                     eos._edges.begin(), eos._edges.end());
7004         }
7005         // summarize normals
7006         for ( size_t i = 0; i < eos._edges.size(); ++i )
7007           avgNormal += eos._edges[ i ]->_normal;
7008       }
7009       double normSize = avgNormal.SquareModulus();
7010       if ( normSize < 1e-200 )
7011       {
7012         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7013         return false;
7014       }
7015       avgNormal /= Sqrt( normSize );
7016
7017       // compute new _LayerEdge::_cosin on EDGEs
7018       double avgCosin = 0;
7019       int     nbCosin = 0;
7020       gp_Vec inFaceDir;
7021       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7022       {
7023         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7024         if ( ceCurve._adjFace.IsNull() )
7025           continue;
7026         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7027         {
7028           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7029           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7030           if ( isOK )
7031           {
7032             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7033             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7034             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7035             nbCosin++;
7036           }
7037         }
7038       }
7039       if ( nbCosin > 0 )
7040         avgCosin /= nbCosin;
7041
7042       // set _LayerEdge::_normal = avgNormal
7043       id2eos = convFace._subIdToEOS.begin();
7044       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7045       {
7046         _EdgesOnShape& eos = *(id2eos->second);
7047         if ( eos.ShapeType() != TopAbs_EDGE )
7048           for ( size_t i = 0; i < eos._edges.size(); ++i )
7049             eos._edges[ i ]->_cosin = avgCosin;
7050
7051         for ( size_t i = 0; i < eos._edges.size(); ++i )
7052         {
7053           eos._edges[ i ]->SetNormal( avgNormal );
7054           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7055         }
7056       }
7057     }
7058     else // if ( isSpherical )
7059     {
7060       // We suppose that centers of curvature at all points of the FACE
7061       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7062       // having a common center of curvature we define the same new normal
7063       // as a sum of normals of _LayerEdge's on EDGEs among them.
7064
7065       // get all centers of curvature for each EDGE
7066
7067       helper.SetSubShape( convFace._face );
7068       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7069
7070       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7071       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7072       {
7073         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7074
7075         // set adjacent FACE
7076         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7077
7078         // get _LayerEdge's of the EDGE
7079         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7080         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7081         if ( !eos || eos->_edges.empty() )
7082         {
7083           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7084           for ( int iV = 0; iV < 2; ++iV )
7085           {
7086             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7087             TGeomID     vID = meshDS->ShapeToIndex( v );
7088             eos = data.GetShapeEdges( vID );
7089             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7090           }
7091           edgeLEdge    = &vertexLEdges[0];
7092           edgeLEdgeEnd = edgeLEdge + 2;
7093
7094           centerCurves[ iE ]._adjFace.Nullify();
7095         }
7096         else
7097         {
7098           if ( ! eos->_toSmooth )
7099             data.SortOnEdge( edge, eos->_edges );
7100           edgeLEdge    = &eos->_edges[ 0 ];
7101           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7102           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7103           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7104
7105           if ( ! eos->_sWOL.IsNull() )
7106             centerCurves[ iE ]._adjFace.Nullify();
7107         }
7108
7109         // Get curvature centers
7110
7111         centersBox.Clear();
7112
7113         if ( edgeLEdge[0]->IsOnEdge() &&
7114              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7115         { // 1st VERTEX
7116           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7117           centersBox.Add( center );
7118         }
7119         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7120           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7121           { // EDGE or VERTEXes
7122             centerCurves[ iE ].Append( center, *edgeLEdge );
7123             centersBox.Add( center );
7124           }
7125         if ( edgeLEdge[-1]->IsOnEdge() &&
7126              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7127         { // 2nd VERTEX
7128           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7129           centersBox.Add( center );
7130         }
7131         centerCurves[ iE ]._isDegenerated =
7132           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7133
7134       } // loop on EDGES of convFace._face to set up data of centerCurves
7135
7136       // Compute new normals for _LayerEdge's on EDGEs
7137
7138       double avgCosin = 0;
7139       int     nbCosin = 0;
7140       gp_Vec inFaceDir;
7141       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7142       {
7143         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7144         if ( ceCurve._isDegenerated )
7145           continue;
7146         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7147         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7148         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7149         {
7150           isOK = false;
7151           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7152           {
7153             if ( iE1 != iE2 )
7154               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7155           }
7156           if ( isOK && !ceCurve._adjFace.IsNull() )
7157           {
7158             // compute new _LayerEdge::_cosin
7159             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7160             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7161             if ( isOK )
7162             {
7163               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7164               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7165               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7166               nbCosin++;
7167             }
7168           }
7169         }
7170       }
7171       // set new normals to _LayerEdge's of NOT degenerated central curves
7172       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7173       {
7174         if ( centerCurves[ iE ]._isDegenerated )
7175           continue;
7176         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7177         {
7178           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7179           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7180         }
7181       }
7182       // set new normals to _LayerEdge's of     degenerated central curves
7183       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7184       {
7185         if ( !centerCurves[ iE ]._isDegenerated ||
7186              centerCurves[ iE ]._ledges.size() < 3 )
7187           continue;
7188         // new normal is an average of new normals at VERTEXes that
7189         // was computed on non-degenerated _CentralCurveOnEdge's
7190         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7191                            centerCurves[ iE ]._ledges.back ()->_normal );
7192         double sz = newNorm.Modulus();
7193         if ( sz < 1e-200 )
7194           continue;
7195         newNorm /= sz;
7196         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7197                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7198         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7199         {
7200           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7201           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7202           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7203         }
7204       }
7205
7206       // Find new normals for _LayerEdge's based on FACE
7207
7208       if ( nbCosin > 0 )
7209         avgCosin /= nbCosin;
7210       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7211       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7212       if ( id2eos != convFace._subIdToEOS.end() )
7213       {
7214         int iE = 0;
7215         gp_XYZ newNorm;
7216         _EdgesOnShape& eos = * ( id2eos->second );
7217         for ( size_t i = 0; i < eos._edges.size(); ++i )
7218         {
7219           _LayerEdge* ledge = eos._edges[ i ];
7220           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7221             continue;
7222           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7223           {
7224             iE = iE % centerCurves.size();
7225             if ( centerCurves[ iE ]._isDegenerated )
7226               continue;
7227             newNorm.SetCoord( 0,0,0 );
7228             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7229             {
7230               ledge->SetNormal( newNorm );
7231               ledge->_cosin  = avgCosin;
7232               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7233               break;
7234             }
7235           }
7236         }
7237       }
7238
7239     } // not a quasi-spherical FACE
7240
7241     // Update _LayerEdge's data according to a new normal
7242
7243     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7244                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7245
7246     id2eos = convFace._subIdToEOS.begin();
7247     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7248     {
7249       _EdgesOnShape& eos = * ( id2eos->second );
7250       for ( size_t i = 0; i < eos._edges.size(); ++i )
7251       {
7252         _LayerEdge* & ledge = eos._edges[ i ];
7253         double len = ledge->_len;
7254         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7255         ledge->SetCosin( ledge->_cosin );
7256         ledge->SetNewLength( len, eos, helper );
7257       }
7258       if ( eos.ShapeType() != TopAbs_FACE )
7259         for ( size_t i = 0; i < eos._edges.size(); ++i )
7260         {
7261           _LayerEdge* ledge = eos._edges[ i ];
7262           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7263           {
7264             _LayerEdge* neibor = ledge->_neibors[iN];
7265             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7266             {
7267               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7268               neibor->Set( _LayerEdge::MOVED );
7269               neibor->SetSmooLen( neibor->_len );
7270             }
7271           }
7272         }
7273     } // loop on sub-shapes of convFace._face
7274
7275     // Find FACEs adjacent to convFace._face that got necessity to smooth
7276     // as a result of normals modification
7277
7278     set< _EdgesOnShape* > adjFacesToSmooth;
7279     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7280     {
7281       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7282            centerCurves[ iE ]._adjFaceToSmooth )
7283         continue;
7284       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7285       {
7286         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7287         {
7288           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7289           break;
7290         }
7291       }
7292     }
7293     data.AddShapesToSmooth( adjFacesToSmooth );
7294
7295     dumpFunctionEnd();
7296
7297
7298   } // loop on data._convexFaces
7299
7300   return true;
7301 }
7302
7303 //================================================================================
7304 /*!
7305  * \brief Finds a center of curvature of a surface at a _LayerEdge
7306  */
7307 //================================================================================
7308
7309 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7310                                         BRepLProp_SLProps&  surfProp,
7311                                         SMESH_MesherHelper& helper,
7312                                         gp_Pnt &            center ) const
7313 {
7314   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7315   surfProp.SetParameters( uv.X(), uv.Y() );
7316   if ( !surfProp.IsCurvatureDefined() )
7317     return false;
7318
7319   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7320   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7321   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7322   if ( surfCurvatureMin > surfCurvatureMax )
7323     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7324   else
7325     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7326
7327   return true;
7328 }
7329
7330 //================================================================================
7331 /*!
7332  * \brief Check that prisms are not distorted
7333  */
7334 //================================================================================
7335
7336 bool _ConvexFace::CheckPrisms() const
7337 {
7338   double vol = 0;
7339   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7340   {
7341     const _LayerEdge* edge = _simplexTestEdges[i];
7342     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7343     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7344       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7345       {
7346         debugMsg( "Bad simplex of _simplexTestEdges ("
7347                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7348                   << " "<< edge->_simplices[j]._nPrev->GetID()
7349                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7350         return false;
7351       }
7352   }
7353   return true;
7354 }
7355
7356 //================================================================================
7357 /*!
7358  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7359  *        stored in this _CentralCurveOnEdge.
7360  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7361  *  \param [in,out] newNormal - current normal at this point, to be redefined
7362  *  \return bool - true if succeeded.
7363  */
7364 //================================================================================
7365
7366 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7367 {
7368   if ( this->_isDegenerated )
7369     return false;
7370
7371   // find two centers the given one lies between
7372
7373   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7374   {
7375     double sl2 = 1.001 * _segLength2[ i ];
7376
7377     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7378     if ( d1 > sl2 )
7379       continue;
7380     
7381     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7382     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7383       continue;
7384
7385     d1 = Sqrt( d1 );
7386     d2 = Sqrt( d2 );
7387     double r = d1 / ( d1 + d2 );
7388     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7389                    (      r ) * _ledges[ i+1 ]->_normal );
7390     norm.Normalize();
7391
7392     newNormal += norm;
7393     double sz = newNormal.Modulus();
7394     if ( sz < 1e-200 )
7395       break;
7396     newNormal /= sz;
7397     return true;
7398   }
7399   return false;
7400 }
7401
7402 //================================================================================
7403 /*!
7404  * \brief Set shape members
7405  */
7406 //================================================================================
7407
7408 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7409                                      const _ConvexFace&  convFace,
7410                                      _SolidData&         data,
7411                                      SMESH_MesherHelper& helper)
7412 {
7413   _edge = edge;
7414
7415   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7416   while ( const TopoDS_Shape* F = fIt->next())
7417     if ( !convFace._face.IsSame( *F ))
7418     {
7419       _adjFace = TopoDS::Face( *F );
7420       _adjFaceToSmooth = false;
7421       // _adjFace already in a smoothing queue ?
7422       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7423         _adjFaceToSmooth = eos->_toSmooth;
7424       break;
7425     }
7426 }
7427
7428 //================================================================================
7429 /*!
7430  * \brief Looks for intersection of it's last segment with faces
7431  *  \param distance - returns shortest distance from the last node to intersection
7432  */
7433 //================================================================================
7434
7435 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7436                                    double &                 distance,
7437                                    const double&            epsilon,
7438                                    _EdgesOnShape&           eos,
7439                                    const SMDS_MeshElement** intFace)
7440 {
7441   vector< const SMDS_MeshElement* > suspectFaces;
7442   double segLen;
7443   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7444   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7445
7446   bool segmentIntersected = false;
7447   distance = Precision::Infinite();
7448   int iFace = -1; // intersected face
7449   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7450   {
7451     const SMDS_MeshElement* face = suspectFaces[j];
7452     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7453          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7454       continue; // face sharing _LayerEdge node
7455     const int nbNodes = face->NbCornerNodes();
7456     bool intFound = false;
7457     double dist;
7458     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7459     if ( nbNodes == 3 )
7460     {
7461       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7462     }
7463     else
7464     {
7465       const SMDS_MeshNode* tria[3];
7466       tria[0] = *nIt++;
7467       tria[1] = *nIt++;
7468       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7469       {
7470         tria[2] = *nIt++;
7471         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7472         tria[1] = tria[2];
7473       }
7474     }
7475     if ( intFound )
7476     {
7477       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7478         segmentIntersected = true;
7479       if ( distance > dist )
7480         distance = dist, iFace = j;
7481     }
7482   }
7483   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7484
7485   distance -= segLen;
7486
7487   if ( segmentIntersected )
7488   {
7489 #ifdef __myDEBUG
7490     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7491     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7492     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7493          << ", intersection with face ("
7494          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7495          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7496          << ") distance = " << distance << endl;
7497 #endif
7498   }
7499
7500   return segmentIntersected;
7501 }
7502
7503 //================================================================================
7504 /*!
7505  * \brief Returns a point used to check orientation of _simplices
7506  */
7507 //================================================================================
7508
7509 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7510 {
7511   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7512
7513   if ( !eos || eos->_sWOL.IsNull() )
7514     return _pos[ i ];
7515
7516   if ( eos->SWOLType() == TopAbs_EDGE )
7517   {
7518     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7519   }
7520   //else //  TopAbs_FACE
7521
7522   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7523 }
7524
7525 //================================================================================
7526 /*!
7527  * \brief Returns size and direction of the last segment
7528  */
7529 //================================================================================
7530
7531 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7532 {
7533   // find two non-coincident positions
7534   gp_XYZ orig = _pos.back();
7535   gp_XYZ vec;
7536   int iPrev = _pos.size() - 2;
7537   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7538   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7539   while ( iPrev >= 0 )
7540   {
7541     vec = orig - _pos[iPrev];
7542     if ( vec.SquareModulus() > tol*tol )
7543       break;
7544     else
7545       iPrev--;
7546   }
7547
7548   // make gp_Ax1
7549   gp_Ax1 segDir;
7550   if ( iPrev < 0 )
7551   {
7552     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7553     segDir.SetDirection( _normal );
7554     segLen = 0;
7555   }
7556   else
7557   {
7558     gp_Pnt pPrev = _pos[ iPrev ];
7559     if ( !eos._sWOL.IsNull() )
7560     {
7561       TopLoc_Location loc;
7562       if ( eos.SWOLType() == TopAbs_EDGE )
7563       {
7564         double f,l;
7565         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7566         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7567       }
7568       else
7569       {
7570         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7571         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7572       }
7573       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7574     }
7575     segDir.SetLocation( pPrev );
7576     segDir.SetDirection( vec );
7577     segLen = vec.Modulus();
7578   }
7579
7580   return segDir;
7581 }
7582
7583 //================================================================================
7584 /*!
7585  * \brief Return the last position of the target node on a FACE. 
7586  *  \param [in] F - the FACE this _LayerEdge is inflated along
7587  *  \return gp_XY - result UV
7588  */
7589 //================================================================================
7590
7591 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7592 {
7593   if ( F.IsSame( eos._sWOL )) // F is my FACE
7594     return gp_XY( _pos.back().X(), _pos.back().Y() );
7595
7596   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7597     return gp_XY( 1e100, 1e100 );
7598
7599   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7600   double f, l, u = _pos.back().X();
7601   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7602   if ( !C2d.IsNull() && f <= u && u <= l )
7603     return C2d->Value( u ).XY();
7604
7605   return gp_XY( 1e100, 1e100 );
7606 }
7607
7608 //================================================================================
7609 /*!
7610  * \brief Test intersection of the last segment with a given triangle
7611  *   using Moller-Trumbore algorithm
7612  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7613  */
7614 //================================================================================
7615
7616 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7617                                const gp_XYZ& vert0,
7618                                const gp_XYZ& vert1,
7619                                const gp_XYZ& vert2,
7620                                double&       t,
7621                                const double& EPSILON) const
7622 {
7623   const gp_Pnt& orig = lastSegment.Location();
7624   const gp_Dir& dir  = lastSegment.Direction();
7625
7626   /* calculate distance from vert0 to ray origin */
7627   //gp_XYZ tvec = orig.XYZ() - vert0;
7628
7629   //if ( tvec * dir > EPSILON )
7630     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7631     //return false;
7632
7633   gp_XYZ edge1 = vert1 - vert0;
7634   gp_XYZ edge2 = vert2 - vert0;
7635
7636   /* begin calculating determinant - also used to calculate U parameter */
7637   gp_XYZ pvec = dir.XYZ() ^ edge2;
7638
7639   /* if determinant is near zero, ray lies in plane of triangle */
7640   double det = edge1 * pvec;
7641
7642   const double ANGL_EPSILON = 1e-12;
7643   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7644     return false;
7645
7646   /* calculate distance from vert0 to ray origin */
7647   gp_XYZ tvec = orig.XYZ() - vert0;
7648
7649   /* calculate U parameter and test bounds */
7650   double u = ( tvec * pvec ) / det;
7651   //if (u < 0.0 || u > 1.0)
7652   if ( u < -EPSILON || u > 1.0 + EPSILON )
7653     return false;
7654
7655   /* prepare to test V parameter */
7656   gp_XYZ qvec = tvec ^ edge1;
7657
7658   /* calculate V parameter and test bounds */
7659   double v = (dir.XYZ() * qvec) / det;
7660   //if ( v < 0.0 || u + v > 1.0 )
7661   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7662     return false;
7663
7664   /* calculate t, ray intersects triangle */
7665   t = (edge2 * qvec) / det;
7666
7667   //return true;
7668   return t > 0.;
7669 }
7670
7671 //================================================================================
7672 /*!
7673  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7674  *        neighbor _LayerEdge's by it's own inflation vector.
7675  *  \param [in] eov - EOS of the VERTEX
7676  *  \param [in] eos - EOS of the FACE
7677  *  \param [in] step - inflation step
7678  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7679  */
7680 //================================================================================
7681
7682 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7683                                    const _EdgesOnShape*    eos,
7684                                    const int               step,
7685                                    vector< _LayerEdge* > & badSmooEdges )
7686 {
7687   // check if any of _neibors is in badSmooEdges
7688   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7689                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7690     return;
7691
7692   // get all edges to move
7693
7694   set< _LayerEdge* > edges;
7695
7696   // find a distance between _LayerEdge on VERTEX and its neighbors
7697   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7698   double dist2 = 0;
7699   for ( size_t i = 0; i < _neibors.size(); ++i )
7700   {
7701     _LayerEdge* nEdge = _neibors[i];
7702     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7703     {
7704       edges.insert( nEdge );
7705       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7706     }
7707   }
7708   // add _LayerEdge's close to curPosV
7709   size_t nbE;
7710   do {
7711     nbE = edges.size();
7712     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7713     {
7714       _LayerEdge* edgeF = *e;
7715       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7716       {
7717         _LayerEdge* nEdge = edgeF->_neibors[i];
7718         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7719              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7720           edges.insert( nEdge );
7721       }
7722     }
7723   }
7724   while ( nbE < edges.size() );
7725
7726   // move the target node of the got edges
7727
7728   gp_XYZ prevPosV = PrevPos();
7729   if ( eov->SWOLType() == TopAbs_EDGE )
7730   {
7731     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7732     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7733   }
7734   else if ( eov->SWOLType() == TopAbs_FACE )
7735   {
7736     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7737     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7738   }
7739
7740   SMDS_FacePosition* fPos;
7741   //double r = 1. - Min( 0.9, step / 10. );
7742   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7743   {
7744     _LayerEdge*       edgeF = *e;
7745     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7746     const gp_XYZ    newPosF = curPosV + prevVF;
7747     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7748     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7749     edgeF->_pos.back() = newPosF;
7750     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7751
7752     // set _curvature to make edgeF updated by putOnOffsetSurface()
7753     if ( !edgeF->_curvature )
7754       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7755       {
7756         edgeF->_curvature = new _Curvature;
7757         edgeF->_curvature->_r = 0;
7758         edgeF->_curvature->_k = 0;
7759         edgeF->_curvature->_h2lenRatio = 0;
7760         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7761       }
7762   }
7763   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7764   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7765   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7766   // {
7767   //   _LayerEdge*      edgeF = *e;
7768   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7769   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7770   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7771   //   edgeF->_pos.back() = newPosF;
7772   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7773   // }
7774
7775   // smooth _LayerEdge's around moved nodes
7776   //size_t nbBadBefore = badSmooEdges.size();
7777   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7778   {
7779     _LayerEdge* edgeF = *e;
7780     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7781       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7782         //&& !edges.count( edgeF->_neibors[j] ))
7783       {
7784         _LayerEdge* edgeFN = edgeF->_neibors[j];
7785         edgeFN->Unset( SMOOTHED );
7786         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7787         // if ( nbBad > 0 )
7788         // {
7789         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7790         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7791         //   int        nbBadAfter = edgeFN->_simplices.size();
7792         //   double vol;
7793         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7794         //   {
7795         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7796         //   }
7797         //   if ( nbBadAfter <= nbBad )
7798         //   {
7799         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7800         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7801         //     edgeF->_pos.back() = newPosF;
7802         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7803         //     nbBad = nbBadAfter;
7804         //   }
7805         // }
7806         if ( nbBad > 0 )
7807           badSmooEdges.push_back( edgeFN );
7808       }
7809   }
7810     // move a bit not smoothed around moved nodes
7811   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7812   //   {
7813   //   _LayerEdge*      edgeF = badSmooEdges[i];
7814   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7815   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7816   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7817   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7818   //   edgeF->_pos.back() = newPosF;
7819   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7820   // }
7821 }
7822
7823 //================================================================================
7824 /*!
7825  * \brief Perform smooth of _LayerEdge's based on EDGE's
7826  *  \retval bool - true if node has been moved
7827  */
7828 //================================================================================
7829
7830 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7831                               const TopoDS_Face&             F,
7832                               SMESH_MesherHelper&            helper)
7833 {
7834   ASSERT( IsOnEdge() );
7835
7836   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7837   SMESH_TNodeXYZ oldPos( tgtNode );
7838   double dist01, distNewOld;
7839   
7840   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7841   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7842   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7843
7844   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7845   double lenDelta = 0;
7846   if ( _curvature )
7847   {
7848     //lenDelta = _curvature->lenDelta( _len );
7849     lenDelta = _curvature->lenDeltaByDist( dist01 );
7850     newPos.ChangeCoord() += _normal * lenDelta;
7851   }
7852
7853   distNewOld = newPos.Distance( oldPos );
7854
7855   if ( F.IsNull() )
7856   {
7857     if ( _2neibors->_plnNorm )
7858     {
7859       // put newPos on the plane defined by source node and _plnNorm
7860       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7861       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7862       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7863     }
7864     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7865     _pos.back() = newPos.XYZ();
7866   }
7867   else
7868   {
7869     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7870     gp_XY uv( Precision::Infinite(), 0 );
7871     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7872     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7873
7874     newPos = surface->Value( uv );
7875     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7876   }
7877
7878   // commented for IPAL0052478
7879   // if ( _curvature && lenDelta < 0 )
7880   // {
7881   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7882   //   _len -= prevPos.Distance( oldPos );
7883   //   _len += prevPos.Distance( newPos );
7884   // }
7885   bool moved = distNewOld > dist01/50;
7886   //if ( moved )
7887   dumpMove( tgtNode ); // debug
7888
7889   return moved;
7890 }
7891
7892 //================================================================================
7893 /*!
7894  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7895  */
7896 //================================================================================
7897
7898 void _LayerEdge::SmoothWoCheck()
7899 {
7900   if ( Is( DIFFICULT ))
7901     return;
7902
7903   bool moved = Is( SMOOTHED );
7904   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7905     moved = _neibors[i]->Is( SMOOTHED );
7906   if ( !moved )
7907     return;
7908
7909   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7910
7911   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7912   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7913   _pos.back() = newPos;
7914
7915   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7916 }
7917
7918 //================================================================================
7919 /*!
7920  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7921  */
7922 //================================================================================
7923
7924 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7925 {
7926   if ( ! Is( NEAR_BOUNDARY ))
7927     return 0;
7928
7929   int nbBad = 0;
7930   double vol;
7931   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7932   {
7933     _LayerEdge* eN = _neibors[iN];
7934     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7935       continue;
7936     if ( needSmooth )
7937       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7938                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7939                        eN->_pos.size() != _pos.size() );
7940
7941     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7942     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7943     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7944       if ( eN->_nodes.size() > 1 &&
7945            eN->_simplices[i].Includes( _nodes.back() ) &&
7946            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7947       {
7948         ++nbBad;
7949         if ( badNeibors )
7950         {
7951           badNeibors->push_back( eN );
7952           debugMsg("Bad boundary simplex ( "
7953                    << " "<< eN->_nodes[0]->GetID()
7954                    << " "<< eN->_nodes.back()->GetID()
7955                    << " "<< eN->_simplices[i]._nPrev->GetID()
7956                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7957         }
7958         else
7959         {
7960           break;
7961         }
7962       }
7963   }
7964   return nbBad;
7965 }
7966
7967 //================================================================================
7968 /*!
7969  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7970  *  \retval int - nb of bad simplices around this _LayerEdge
7971  */
7972 //================================================================================
7973
7974 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7975 {
7976   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7977     return 0; // shape of simplices not changed
7978   if ( _simplices.size() < 2 )
7979     return 0; // _LayerEdge inflated along EDGE or FACE
7980
7981   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7982     findBest = true;
7983
7984   const gp_XYZ& curPos  = _pos.back();
7985   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7986
7987   // quality metrics (orientation) of tetras around _tgtNode
7988   int nbOkBefore = 0;
7989   double vol, minVolBefore = 1e100;
7990   for ( size_t i = 0; i < _simplices.size(); ++i )
7991   {
7992     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7993     minVolBefore = Min( minVolBefore, vol );
7994   }
7995   int nbBad = _simplices.size() - nbOkBefore;
7996
7997   bool bndNeedSmooth = false;
7998   if ( nbBad == 0 )
7999     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8000   if ( nbBad > 0 )
8001     Set( DISTORTED );
8002
8003   // evaluate min angle
8004   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8005   {
8006     size_t nbGoodAngles = _simplices.size();
8007     double angle;
8008     for ( size_t i = 0; i < _simplices.size(); ++i )
8009     {
8010       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8011         --nbGoodAngles;
8012     }
8013     if ( nbGoodAngles == _simplices.size() )
8014     {
8015       Unset( MOVED );
8016       return 0;
8017     }
8018   }
8019   if ( Is( ON_CONCAVE_FACE ))
8020     findBest = true;
8021
8022   if ( step % 2 == 0 )
8023     findBest = false;
8024
8025   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8026   {
8027     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8028       _smooFunction = _funs[ FUN_CENTROIDAL ];
8029     else
8030       _smooFunction = _funs[ FUN_LAPLACIAN ];
8031   }
8032
8033   // compute new position for the last _pos using different _funs
8034   gp_XYZ newPos;
8035   bool moved = false;
8036   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8037   {
8038     if ( iFun < 0 )
8039       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8040     else if ( _funs[ iFun ] == _smooFunction )
8041       continue; // _smooFunction again
8042     else if ( step > 1 )
8043       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8044     else
8045       break; // let "easy" functions improve elements around distorted ones
8046
8047     if ( _curvature )
8048     {
8049       double delta  = _curvature->lenDelta( _len );
8050       if ( delta > 0 )
8051         newPos += _normal * delta;
8052       else
8053       {
8054         double segLen = _normal * ( newPos - prevPos );
8055         if ( segLen + delta > 0 )
8056           newPos += _normal * delta;
8057       }
8058       // double segLenChange = _normal * ( curPos - newPos );
8059       // newPos += 0.5 * _normal * segLenChange;
8060     }
8061
8062     int nbOkAfter = 0;
8063     double minVolAfter = 1e100;
8064     for ( size_t i = 0; i < _simplices.size(); ++i )
8065     {
8066       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8067       minVolAfter = Min( minVolAfter, vol );
8068     }
8069     // get worse?
8070     if ( nbOkAfter < nbOkBefore )
8071       continue;
8072
8073     if (( findBest ) &&
8074         ( nbOkAfter == nbOkBefore ) &&
8075         ( minVolAfter <= minVolBefore ))
8076       continue;
8077
8078     nbBad        = _simplices.size() - nbOkAfter;
8079     minVolBefore = minVolAfter;
8080     nbOkBefore   = nbOkAfter;
8081     moved        = true;
8082
8083     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8084     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8085     _pos.back() = newPos;
8086
8087     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8088                   << (nbBad ? " --BAD" : ""));
8089
8090     if ( iFun > -1 )
8091     {
8092       continue; // look for a better function
8093     }
8094
8095     if ( !findBest )
8096       break;
8097
8098   } // loop on smoothing functions
8099
8100   if ( moved ) // notify _neibors
8101   {
8102     Set( SMOOTHED );
8103     for ( size_t i = 0; i < _neibors.size(); ++i )
8104       if ( !_neibors[i]->Is( MOVED ))
8105       {
8106         _neibors[i]->Set( MOVED );
8107         toSmooth.push_back( _neibors[i] );
8108       }
8109   }
8110
8111   return nbBad;
8112 }
8113
8114 //================================================================================
8115 /*!
8116  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8117  *  \retval int - nb of bad simplices around this _LayerEdge
8118  */
8119 //================================================================================
8120
8121 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8122 {
8123   if ( !_smooFunction )
8124     return 0; // _LayerEdge inflated along EDGE or FACE
8125   if ( Is( BLOCKED ))
8126     return 0; // not inflated
8127
8128   const gp_XYZ& curPos  = _pos.back();
8129   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8130
8131   // quality metrics (orientation) of tetras around _tgtNode
8132   int nbOkBefore = 0;
8133   double vol, minVolBefore = 1e100;
8134   for ( size_t i = 0; i < _simplices.size(); ++i )
8135   {
8136     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8137     minVolBefore = Min( minVolBefore, vol );
8138   }
8139   int nbBad = _simplices.size() - nbOkBefore;
8140
8141   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8142   {
8143     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8144       _smooFunction = _funs[ FUN_LAPLACIAN ];
8145     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8146       _smooFunction = _funs[ FUN_CENTROIDAL ];
8147   }
8148
8149   // compute new position for the last _pos using different _funs
8150   gp_XYZ newPos;
8151   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8152   {
8153     if ( iFun < 0 )
8154       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8155     else if ( _funs[ iFun ] == _smooFunction )
8156       continue; // _smooFunction again
8157     else if ( step > 1 )
8158       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8159     else
8160       break; // let "easy" functions improve elements around distorted ones
8161
8162     if ( _curvature )
8163     {
8164       double delta  = _curvature->lenDelta( _len );
8165       if ( delta > 0 )
8166         newPos += _normal * delta;
8167       else
8168       {
8169         double segLen = _normal * ( newPos - prevPos );
8170         if ( segLen + delta > 0 )
8171           newPos += _normal * delta;
8172       }
8173       // double segLenChange = _normal * ( curPos - newPos );
8174       // newPos += 0.5 * _normal * segLenChange;
8175     }
8176
8177     int nbOkAfter = 0;
8178     double minVolAfter = 1e100;
8179     for ( size_t i = 0; i < _simplices.size(); ++i )
8180     {
8181       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8182       minVolAfter = Min( minVolAfter, vol );
8183     }
8184     // get worse?
8185     if ( nbOkAfter < nbOkBefore )
8186       continue;
8187     if (( isConcaveFace || findBest ) &&
8188         ( nbOkAfter == nbOkBefore ) &&
8189         ( minVolAfter <= minVolBefore )
8190         )
8191       continue;
8192
8193     nbBad        = _simplices.size() - nbOkAfter;
8194     minVolBefore = minVolAfter;
8195     nbOkBefore   = nbOkAfter;
8196
8197     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8198     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8199     _pos.back() = newPos;
8200
8201     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8202                   << ( nbBad ? "--BAD" : ""));
8203
8204     // commented for IPAL0052478
8205     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8206     // _len += prevPos.Distance(newPos);
8207
8208     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8209     {
8210       //_smooFunction = _funs[ iFun ];
8211       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8212       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8213       // << " minVol: " << minVolAfter
8214       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8215       // << endl;
8216       continue; // look for a better function
8217     }
8218
8219     if ( !findBest )
8220       break;
8221
8222   } // loop on smoothing functions
8223
8224   return nbBad;
8225 }
8226
8227 //================================================================================
8228 /*!
8229  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8230  *        For a correct result, _simplices must contain nodes lying on geometry.
8231  */
8232 //================================================================================
8233
8234 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8235                                      const TNode2Edge&     n2eMap)
8236 {
8237   if ( _smooFunction ) return;
8238
8239   // use smoothNefPolygon() near concaveVertices
8240   if ( !concaveVertices.empty() )
8241   {
8242     _smooFunction = _funs[ FUN_CENTROIDAL ];
8243
8244     Set( ON_CONCAVE_FACE );
8245
8246     for ( size_t i = 0; i < _simplices.size(); ++i )
8247     {
8248       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8249       {
8250         _smooFunction = _funs[ FUN_NEFPOLY ];
8251
8252         // set FUN_CENTROIDAL to neighbor edges
8253         for ( i = 0; i < _neibors.size(); ++i )
8254         {
8255           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8256           {
8257             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8258           }
8259         }
8260         return;
8261       }
8262     }
8263
8264     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8265     // // where the nodes are smoothed too far along a sphere thus creating
8266     // // inverted _simplices
8267     // double dist[theNbSmooFuns];
8268     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8269     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8270
8271     // double minDist = Precision::Infinite();
8272     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8273     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8274     // {
8275     //   gp_Pnt newP = (this->*_funs[i])();
8276     //   dist[i] = p.SquareDistance( newP );
8277     //   if ( dist[i]*coef[i] < minDist )
8278     //   {
8279     //     _smooFunction = _funs[i];
8280     //     minDist = dist[i]*coef[i];
8281     //   }
8282     // }
8283   }
8284   else
8285   {
8286     _smooFunction = _funs[ FUN_LAPLACIAN ];
8287   }
8288   // int minDim = 3;
8289   // for ( size_t i = 0; i < _simplices.size(); ++i )
8290   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8291   // if ( minDim == 0 )
8292   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8293   // else if ( minDim == 1 )
8294   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8295
8296
8297   // int iMin;
8298   // for ( int i = 0; i < FUN_NB; ++i )
8299   // {
8300   //   //cout << dist[i] << " ";
8301   //   if ( _smooFunction == _funs[i] ) {
8302   //     iMin = i;
8303   //     //debugMsg( fNames[i] );
8304   //     break;
8305   //   }
8306   // }
8307   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8308 }
8309
8310 //================================================================================
8311 /*!
8312  * \brief Returns a name of _SmooFunction
8313  */
8314 //================================================================================
8315
8316 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8317 {
8318   if ( !fun )
8319     fun = _smooFunction;
8320   for ( int i = 0; i < theNbSmooFuns; ++i )
8321     if ( fun == _funs[i] )
8322       return i;
8323
8324   return theNbSmooFuns;
8325 }
8326
8327 //================================================================================
8328 /*!
8329  * \brief Computes a new node position using Laplacian smoothing
8330  */
8331 //================================================================================
8332
8333 gp_XYZ _LayerEdge::smoothLaplacian()
8334 {
8335   gp_XYZ newPos (0,0,0);
8336   for ( size_t i = 0; i < _simplices.size(); ++i )
8337     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8338   newPos /= _simplices.size();
8339
8340   return newPos;
8341 }
8342
8343 //================================================================================
8344 /*!
8345  * \brief Computes a new node position using angular-based smoothing
8346  */
8347 //================================================================================
8348
8349 gp_XYZ _LayerEdge::smoothAngular()
8350 {
8351   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8352   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8353   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8354
8355   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8356   gp_XYZ pN( 0,0,0 );
8357   for ( size_t i = 0; i < _simplices.size(); ++i )
8358   {
8359     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8360     edgeDir.push_back( p - pPrev );
8361     edgeSize.push_back( edgeDir.back().Magnitude() );
8362     if ( edgeSize.back() < numeric_limits<double>::min() )
8363     {
8364       edgeDir.pop_back();
8365       edgeSize.pop_back();
8366     }
8367     else
8368     {
8369       edgeDir.back() /= edgeSize.back();
8370       points.push_back( p );
8371       pN += p;
8372     }
8373     pPrev = p;
8374   }
8375   edgeDir.push_back ( edgeDir[0] );
8376   edgeSize.push_back( edgeSize[0] );
8377   pN /= points.size();
8378
8379   gp_XYZ newPos(0,0,0);
8380   double sumSize = 0;
8381   for ( size_t i = 0; i < points.size(); ++i )
8382   {
8383     gp_Vec toN    = pN - points[i];
8384     double toNLen = toN.Magnitude();
8385     if ( toNLen < numeric_limits<double>::min() )
8386     {
8387       newPos += pN;
8388       continue;
8389     }
8390     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8391     double bisecLen = bisec.SquareMagnitude();
8392     if ( bisecLen < numeric_limits<double>::min() )
8393     {
8394       gp_Vec norm = edgeDir[i] ^ toN;
8395       bisec = norm ^ edgeDir[i];
8396       bisecLen = bisec.SquareMagnitude();
8397     }
8398     bisecLen = Sqrt( bisecLen );
8399     bisec /= bisecLen;
8400
8401 #if 1
8402     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8403     sumSize += bisecLen;
8404 #else
8405     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8406     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8407 #endif
8408     newPos += pNew;
8409   }
8410   newPos /= sumSize;
8411
8412   // project newPos to an average plane
8413
8414   gp_XYZ norm(0,0,0); // plane normal
8415   points.push_back( points[0] );
8416   for ( size_t i = 1; i < points.size(); ++i )
8417   {
8418     gp_XYZ vec1 = points[ i-1 ] - pN;
8419     gp_XYZ vec2 = points[ i   ] - pN;
8420     gp_XYZ cross = vec1 ^ vec2;
8421     try {
8422       cross.Normalize();
8423       if ( cross * norm < numeric_limits<double>::min() )
8424         norm += cross.Reversed();
8425       else
8426         norm += cross;
8427     }
8428     catch (Standard_Failure) { // if |cross| == 0.
8429     }
8430   }
8431   gp_XYZ vec = newPos - pN;
8432   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8433   newPos     = newPos - r * norm;
8434
8435   return newPos;
8436 }
8437
8438 //================================================================================
8439 /*!
8440  * \brief Computes a new node position using weigthed node positions
8441  */
8442 //================================================================================
8443
8444 gp_XYZ _LayerEdge::smoothLengthWeighted()
8445 {
8446   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8447   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8448
8449   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8450   for ( size_t i = 0; i < _simplices.size(); ++i )
8451   {
8452     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8453     edgeSize.push_back( ( p - pPrev ).Modulus() );
8454     if ( edgeSize.back() < numeric_limits<double>::min() )
8455     {
8456       edgeSize.pop_back();
8457     }
8458     else
8459     {
8460       points.push_back( p );
8461     }
8462     pPrev = p;
8463   }
8464   edgeSize.push_back( edgeSize[0] );
8465
8466   gp_XYZ newPos(0,0,0);
8467   double sumSize = 0;
8468   for ( size_t i = 0; i < points.size(); ++i )
8469   {
8470     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8471     sumSize += edgeSize[i] + edgeSize[i+1];
8472   }
8473   newPos /= sumSize;
8474   return newPos;
8475 }
8476
8477 //================================================================================
8478 /*!
8479  * \brief Computes a new node position using angular-based smoothing
8480  */
8481 //================================================================================
8482
8483 gp_XYZ _LayerEdge::smoothCentroidal()
8484 {
8485   gp_XYZ newPos(0,0,0);
8486   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8487   double sumSize = 0;
8488   for ( size_t i = 0; i < _simplices.size(); ++i )
8489   {
8490     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8491     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8492     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8493     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8494
8495     sumSize += size;
8496     newPos += gc * size;
8497   }
8498   newPos /= sumSize;
8499
8500   return newPos;
8501 }
8502
8503 //================================================================================
8504 /*!
8505  * \brief Computes a new node position located inside a Nef polygon
8506  */
8507 //================================================================================
8508
8509 gp_XYZ _LayerEdge::smoothNefPolygon()
8510 #ifdef OLD_NEF_POLYGON
8511 {
8512   gp_XYZ newPos(0,0,0);
8513
8514   // get a plane to search a solution on
8515
8516   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8517   size_t i;
8518   const double tol = numeric_limits<double>::min();
8519   gp_XYZ center(0,0,0);
8520   for ( i = 0; i < _simplices.size(); ++i )
8521   {
8522     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8523                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8524     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8525   }
8526   vecs.back() = vecs[0];
8527   center /= _simplices.size();
8528
8529   gp_XYZ zAxis(0,0,0);
8530   for ( i = 0; i < _simplices.size(); ++i )
8531     zAxis += vecs[i] ^ vecs[i+1];
8532
8533   gp_XYZ yAxis;
8534   for ( i = 0; i < _simplices.size(); ++i )
8535   {
8536     yAxis = vecs[i];
8537     if ( yAxis.SquareModulus() > tol )
8538       break;
8539   }
8540   gp_XYZ xAxis = yAxis ^ zAxis;
8541   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8542   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8543   //                             p0.Distance( _simplices[2]._nPrev ));
8544   // gp_XYZ center = smoothLaplacian();
8545   // gp_XYZ xAxis, yAxis, zAxis;
8546   // for ( i = 0; i < _simplices.size(); ++i )
8547   // {
8548   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8549   //   if ( xAxis.SquareModulus() > tol*tol )
8550   //     break;
8551   // }
8552   // for ( i = 1; i < _simplices.size(); ++i )
8553   // {
8554   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8555   //   zAxis = xAxis ^ yAxis;
8556   //   if ( zAxis.SquareModulus() > tol*tol )
8557   //     break;
8558   // }
8559   // if ( i == _simplices.size() ) return newPos;
8560
8561   yAxis = zAxis ^ xAxis;
8562   xAxis /= xAxis.Modulus();
8563   yAxis /= yAxis.Modulus();
8564
8565   // get half-planes of _simplices
8566
8567   vector< _halfPlane > halfPlns( _simplices.size() );
8568   int nbHP = 0;
8569   for ( size_t i = 0; i < _simplices.size(); ++i )
8570   {
8571     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8572     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8573     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8574     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8575     gp_XY  vec12 = p2 - p1;
8576     double dist12 = vec12.Modulus();
8577     if ( dist12 < tol )
8578       continue;
8579     vec12 /= dist12;
8580     halfPlns[ nbHP ]._pos = p1;
8581     halfPlns[ nbHP ]._dir = vec12;
8582     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8583     ++nbHP;
8584   }
8585
8586   // intersect boundaries of half-planes, define state of intersection points
8587   // in relation to all half-planes and calculate internal point of a 2D polygon
8588
8589   double sumLen = 0;
8590   gp_XY newPos2D (0,0);
8591
8592   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8593   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8594   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8595
8596   vector< vector< TIntPntState > > allIntPnts( nbHP );
8597   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8598   {
8599     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8600     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8601
8602     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8603     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8604
8605     int nbNotOut = 0;
8606     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8607
8608     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8609     {
8610       if ( iHP1 == iHP2 ) continue;
8611
8612       TIntPntState & ips1 = intPnts1[ iHP2 ];
8613       if ( ips1.second == UNDEF )
8614       {
8615         // find an intersection point of boundaries of iHP1 and iHP2
8616
8617         if ( iHP2 == iPrev ) // intersection with neighbors is known
8618           ips1.first = halfPlns[ iHP1 ]._pos;
8619         else if ( iHP2 == iNext )
8620           ips1.first = halfPlns[ iHP2 ]._pos;
8621         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8622           ips1.second = NO_INT;
8623
8624         // classify the found intersection point
8625         if ( ips1.second != NO_INT )
8626         {
8627           ips1.second = NOT_OUT;
8628           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8629             if ( i != iHP1 && i != iHP2 &&
8630                  halfPlns[ i ].IsOut( ips1.first, tol ))
8631               ips1.second = IS_OUT;
8632         }
8633         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8634         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8635         TIntPntState & ips2 = intPnts2[ iHP1 ];
8636         ips2 = ips1;
8637       }
8638       if ( ips1.second == NOT_OUT )
8639       {
8640         ++nbNotOut;
8641         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8642       }
8643     }
8644
8645     // find a NOT_OUT segment of boundary which is located between
8646     // two NOT_OUT int points
8647
8648     if ( nbNotOut < 2 )
8649       continue; // no such a segment
8650
8651     if ( nbNotOut > 2 )
8652     {
8653       // sort points along the boundary
8654       map< double, TIntPntState* > ipsByParam;
8655       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8656       {
8657         TIntPntState & ips1 = intPnts1[ iHP2 ];
8658         if ( ips1.second != NO_INT )
8659         {
8660           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8661           double param = op * halfPlns[ iHP1 ]._dir;
8662           ipsByParam.insert( make_pair( param, & ips1 ));
8663         }
8664       }
8665       // look for two neighboring NOT_OUT points
8666       nbNotOut = 0;
8667       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8668       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8669       {
8670         TIntPntState & ips1 = *(u2ips->second);
8671         if ( ips1.second == NOT_OUT )
8672           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8673         else if ( nbNotOut >= 2 )
8674           break;
8675         else
8676           nbNotOut = 0;
8677       }
8678     }
8679
8680     if ( nbNotOut >= 2 )
8681     {
8682       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8683       sumLen += len;
8684
8685       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8686     }
8687   }
8688
8689   if ( sumLen > 0 )
8690   {
8691     newPos2D /= sumLen;
8692     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8693   }
8694   else
8695   {
8696     newPos = center;
8697   }
8698
8699   return newPos;
8700 }
8701 #else // OLD_NEF_POLYGON
8702 { ////////////////////////////////// NEW
8703   gp_XYZ newPos(0,0,0);
8704
8705   // get a plane to search a solution on
8706
8707   size_t i;
8708   gp_XYZ center(0,0,0);
8709   for ( i = 0; i < _simplices.size(); ++i )
8710     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8711   center /= _simplices.size();
8712
8713   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8714   for ( i = 0; i < _simplices.size(); ++i )
8715     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8716   vecs.back() = vecs[0];
8717
8718   const double tol = numeric_limits<double>::min();
8719   gp_XYZ zAxis(0,0,0);
8720   for ( i = 0; i < _simplices.size(); ++i )
8721   {
8722     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8723     try {
8724       cross.Normalize();
8725       if ( cross * zAxis < tol )
8726         zAxis += cross.Reversed();
8727       else
8728         zAxis += cross;
8729     }
8730     catch (Standard_Failure) { // if |cross| == 0.
8731     }
8732   }
8733
8734   gp_XYZ yAxis;
8735   for ( i = 0; i < _simplices.size(); ++i )
8736   {
8737     yAxis = vecs[i];
8738     if ( yAxis.SquareModulus() > tol )
8739       break;
8740   }
8741   gp_XYZ xAxis = yAxis ^ zAxis;
8742   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8743   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8744   //                             p0.Distance( _simplices[2]._nPrev ));
8745   // gp_XYZ center = smoothLaplacian();
8746   // gp_XYZ xAxis, yAxis, zAxis;
8747   // for ( i = 0; i < _simplices.size(); ++i )
8748   // {
8749   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8750   //   if ( xAxis.SquareModulus() > tol*tol )
8751   //     break;
8752   // }
8753   // for ( i = 1; i < _simplices.size(); ++i )
8754   // {
8755   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8756   //   zAxis = xAxis ^ yAxis;
8757   //   if ( zAxis.SquareModulus() > tol*tol )
8758   //     break;
8759   // }
8760   // if ( i == _simplices.size() ) return newPos;
8761
8762   yAxis = zAxis ^ xAxis;
8763   xAxis /= xAxis.Modulus();
8764   yAxis /= yAxis.Modulus();
8765
8766   // get half-planes of _simplices
8767
8768   vector< _halfPlane > halfPlns( _simplices.size() );
8769   int nbHP = 0;
8770   for ( size_t i = 0; i < _simplices.size(); ++i )
8771   {
8772     const gp_XYZ& OP1 = vecs[ i   ];
8773     const gp_XYZ& OP2 = vecs[ i+1 ];
8774     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8775     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8776     gp_XY  vec12 = p2 - p1;
8777     double dist12 = vec12.Modulus();
8778     if ( dist12 < tol )
8779       continue;
8780     vec12 /= dist12;
8781     halfPlns[ nbHP ]._pos = p1;
8782     halfPlns[ nbHP ]._dir = vec12;
8783     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8784     ++nbHP;
8785   }
8786
8787   // intersect boundaries of half-planes, define state of intersection points
8788   // in relation to all half-planes and calculate internal point of a 2D polygon
8789
8790   double sumLen = 0;
8791   gp_XY newPos2D (0,0);
8792
8793   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8794   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8795   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8796
8797   vector< vector< TIntPntState > > allIntPnts( nbHP );
8798   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8799   {
8800     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8801     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8802
8803     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8804     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8805
8806     int nbNotOut = 0;
8807     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8808
8809     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8810     {
8811       if ( iHP1 == iHP2 ) continue;
8812
8813       TIntPntState & ips1 = intPnts1[ iHP2 ];
8814       if ( ips1.second == UNDEF )
8815       {
8816         // find an intersection point of boundaries of iHP1 and iHP2
8817
8818         if ( iHP2 == iPrev ) // intersection with neighbors is known
8819           ips1.first = halfPlns[ iHP1 ]._pos;
8820         else if ( iHP2 == iNext )
8821           ips1.first = halfPlns[ iHP2 ]._pos;
8822         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8823           ips1.second = NO_INT;
8824
8825         // classify the found intersection point
8826         if ( ips1.second != NO_INT )
8827         {
8828           ips1.second = NOT_OUT;
8829           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8830             if ( i != iHP1 && i != iHP2 &&
8831                  halfPlns[ i ].IsOut( ips1.first, tol ))
8832               ips1.second = IS_OUT;
8833         }
8834         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8835         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8836         TIntPntState & ips2 = intPnts2[ iHP1 ];
8837         ips2 = ips1;
8838       }
8839       if ( ips1.second == NOT_OUT )
8840       {
8841         ++nbNotOut;
8842         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8843       }
8844     }
8845
8846     // find a NOT_OUT segment of boundary which is located between
8847     // two NOT_OUT int points
8848
8849     if ( nbNotOut < 2 )
8850       continue; // no such a segment
8851
8852     if ( nbNotOut > 2 )
8853     {
8854       // sort points along the boundary
8855       map< double, TIntPntState* > ipsByParam;
8856       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8857       {
8858         TIntPntState & ips1 = intPnts1[ iHP2 ];
8859         if ( ips1.second != NO_INT )
8860         {
8861           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8862           double param = op * halfPlns[ iHP1 ]._dir;
8863           ipsByParam.insert( make_pair( param, & ips1 ));
8864         }
8865       }
8866       // look for two neighboring NOT_OUT points
8867       nbNotOut = 0;
8868       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8869       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8870       {
8871         TIntPntState & ips1 = *(u2ips->second);
8872         if ( ips1.second == NOT_OUT )
8873           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8874         else if ( nbNotOut >= 2 )
8875           break;
8876         else
8877           nbNotOut = 0;
8878       }
8879     }
8880
8881     if ( nbNotOut >= 2 )
8882     {
8883       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8884       sumLen += len;
8885
8886       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8887     }
8888   }
8889
8890   if ( sumLen > 0 )
8891   {
8892     newPos2D /= sumLen;
8893     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8894   }
8895   else
8896   {
8897     newPos = center;
8898   }
8899
8900   return newPos;
8901 }
8902 #endif // OLD_NEF_POLYGON
8903
8904 //================================================================================
8905 /*!
8906  * \brief Add a new segment to _LayerEdge during inflation
8907  */
8908 //================================================================================
8909
8910 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8911 {
8912   if ( Is( BLOCKED ))
8913     return;
8914
8915   if ( len > _maxLen )
8916   {
8917     len = _maxLen;
8918     Block( eos.GetData() );
8919   }
8920   const double lenDelta = len - _len;
8921   if ( lenDelta < len * 1e-3  )
8922   {
8923     Block( eos.GetData() );
8924     return;
8925   }
8926
8927   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8928   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8929   gp_XYZ newXYZ;
8930   if ( eos._hyp.IsOffsetMethod() )
8931   {
8932     newXYZ = oldXYZ;
8933     gp_Vec faceNorm;
8934     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8935     while ( faceIt->more() )
8936     {
8937       const SMDS_MeshElement* face = faceIt->next();
8938       if ( !eos.GetNormal( face, faceNorm ))
8939         continue;
8940
8941       // translate plane of a face
8942       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8943
8944       // find point of intersection of the face plane located at baryCenter
8945       // and _normal located at newXYZ
8946       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8947       double dot =  ( faceNorm.XYZ() * _normal );
8948       if ( dot < std::numeric_limits<double>::min() )
8949         dot = lenDelta * 1e-3;
8950       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8951       newXYZ += step * _normal;
8952     }
8953     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8954   }
8955   else
8956   {
8957     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8958   }
8959
8960   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8961   _pos.push_back( newXYZ );
8962
8963   if ( !eos._sWOL.IsNull() )
8964   {
8965     double distXYZ[4];
8966     bool uvOK = false;
8967     if ( eos.SWOLType() == TopAbs_EDGE )
8968     {
8969       double u = Precision::Infinite(); // to force projection w/o distance check
8970       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8971                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8972       _pos.back().SetCoord( u, 0, 0 );
8973       if ( _nodes.size() > 1 && uvOK )
8974       {
8975         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8976         pos->SetUParameter( u );
8977       }
8978     }
8979     else //  TopAbs_FACE
8980     {
8981       gp_XY uv( Precision::Infinite(), 0 );
8982       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8983                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8984       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8985       if ( _nodes.size() > 1 && uvOK )
8986       {
8987         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8988         pos->SetUParameter( uv.X() );
8989         pos->SetVParameter( uv.Y() );
8990       }
8991     }
8992     if ( uvOK )
8993     {
8994       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8995     }
8996     else
8997     {
8998       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8999       _pos.pop_back();
9000       Block( eos.GetData() );
9001       return;
9002     }
9003   }
9004
9005   _len = len;
9006
9007   // notify _neibors
9008   if ( eos.ShapeType() != TopAbs_FACE )
9009   {
9010     for ( size_t i = 0; i < _neibors.size(); ++i )
9011       //if (  _len > _neibors[i]->GetSmooLen() )
9012         _neibors[i]->Set( MOVED );
9013
9014     Set( MOVED );
9015   }
9016   dumpMove( n ); //debug
9017 }
9018
9019 //================================================================================
9020 /*!
9021  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9022  */
9023 //================================================================================
9024
9025 void _LayerEdge::Block( _SolidData& data )
9026 {
9027   //if ( Is( BLOCKED )) return;
9028   Set( BLOCKED );
9029
9030   _maxLen = _len;
9031   std::queue<_LayerEdge*> queue;
9032   queue.push( this );
9033
9034   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9035   while ( !queue.empty() )
9036   {
9037     _LayerEdge* edge = queue.front(); queue.pop();
9038     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9039     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9040     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9041     {
9042       _LayerEdge* neibor = edge->_neibors[iN];
9043       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9044         continue;
9045       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9046       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9047       double minDist = pSrc.SquareDistance( pSrcN );
9048       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9049       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9050       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9051       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9052       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
9053       {
9054         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9055       }
9056       if ( neibor->_maxLen > newMaxLen )
9057       {
9058         neibor->_maxLen = newMaxLen;
9059         if ( neibor->_maxLen < neibor->_len )
9060         {
9061           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9062           while ( neibor->_len > neibor->_maxLen &&
9063                   neibor->NbSteps() > 1 )
9064             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9065           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9066           //neibor->Block( data );
9067         }
9068         queue.push( neibor );
9069       }
9070     }
9071   }
9072 }
9073
9074 //================================================================================
9075 /*!
9076  * \brief Remove last inflation step
9077  */
9078 //================================================================================
9079
9080 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9081 {
9082   if ( _pos.size() > curStep && _nodes.size() > 1 )
9083   {
9084     _pos.resize( curStep );
9085
9086     gp_Pnt      nXYZ = _pos.back();
9087     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9088     SMESH_TNodeXYZ curXYZ( n );
9089     if ( !eos._sWOL.IsNull() )
9090     {
9091       TopLoc_Location loc;
9092       if ( eos.SWOLType() == TopAbs_EDGE )
9093       {
9094         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9095         pos->SetUParameter( nXYZ.X() );
9096         double f,l;
9097         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9098         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9099       }
9100       else
9101       {
9102         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9103         pos->SetUParameter( nXYZ.X() );
9104         pos->SetVParameter( nXYZ.Y() );
9105         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9106         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9107       }
9108     }
9109     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9110     dumpMove( n );
9111
9112     if ( restoreLength )
9113     {
9114       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9115     }
9116   }
9117 }
9118
9119 //================================================================================
9120 /*!
9121  * \brief Return index of a _pos distant from _normal
9122  */
9123 //================================================================================
9124
9125 int _LayerEdge::GetSmoothedPos( const double tol )
9126 {
9127   int iSmoothed = 0;
9128   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9129   {
9130     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9131     if ( normDist > tol * tol )
9132       iSmoothed = i;
9133   }
9134   return iSmoothed;
9135 }
9136
9137 //================================================================================
9138 /*!
9139  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9140  */
9141 //================================================================================
9142
9143 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9144 {
9145   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9146     return;
9147
9148   // find the 1st smoothed _pos
9149   int iSmoothed = GetSmoothedPos( tol );
9150   if ( !iSmoothed ) return;
9151
9152   //if ( 1 || Is( DISTORTED ))
9153   {
9154     gp_XYZ normal = _normal;
9155     if ( Is( NORMAL_UPDATED ))
9156       for ( size_t i = 1; i < _pos.size(); ++i )
9157       {
9158         normal = _pos[i] - _pos[0];
9159         double size = normal.Modulus();
9160         if ( size > RealSmall() )
9161         {
9162           normal /= size;
9163           break;
9164         }
9165       }
9166     const double r = 0.2;
9167     for ( int iter = 0; iter < 50; ++iter )
9168     {
9169       double minDot = 1;
9170       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9171       {
9172         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9173         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9174         _pos[i] = newPos;
9175         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9176         double newLen = ( 1-r ) * midLen + r * segLen[i];
9177         const_cast< double& >( segLen[i] ) = newLen;
9178         // check angle between normal and (_pos[i+1], _pos[i] )
9179         gp_XYZ posDir = _pos[i+1] - _pos[i];
9180         double size   = posDir.SquareModulus();
9181         if ( size > RealSmall() )
9182           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9183       }
9184       if ( minDot > 0.5 * 0.5 )
9185         break;
9186     }
9187   }
9188   // else
9189   // {
9190   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9191   //   {
9192   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9193   //       continue;
9194
9195   //     double     wgt = segLen[i] / segLen.back();
9196   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9197   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9198   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9199   //     _pos[i] = newPos;
9200   //   }
9201   // }
9202 }
9203
9204 //================================================================================
9205 /*!
9206  * \brief Print flags
9207  */
9208 //================================================================================
9209
9210 std::string _LayerEdge::DumpFlags() const
9211 {
9212   SMESH_Comment dump;
9213   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9214     if ( _flags & flag )
9215     {
9216       EFlags f = (EFlags) flag;
9217       switch ( f ) {
9218       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9219       case MOVED:           dump << "MOVED";           break;
9220       case SMOOTHED:        dump << "SMOOTHED";        break;
9221       case DIFFICULT:       dump << "DIFFICULT";       break;
9222       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9223       case BLOCKED:         dump << "BLOCKED";         break;
9224       case INTERSECTED:     dump << "INTERSECTED";     break;
9225       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9226       case MARKED:          dump << "MARKED";          break;
9227       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9228       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9229       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9230       case DISTORTED:       dump << "DISTORTED";       break;
9231       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9232       case SHRUNK:          dump << "SHRUNK";          break;
9233       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9234       }
9235       dump << " ";
9236     }
9237   cout << dump << endl;
9238   return dump;
9239 }
9240
9241 //================================================================================
9242 /*!
9243   case brief:
9244   default:
9245 */
9246 //================================================================================
9247
9248 bool _ViscousBuilder::refine(_SolidData& data)
9249 {
9250   SMESH_MesherHelper& helper = data.GetHelper();
9251   helper.SetElementsOnShape(false);
9252
9253   Handle(Geom_Curve) curve;
9254   Handle(ShapeAnalysis_Surface) surface;
9255   TopoDS_Edge geomEdge;
9256   TopoDS_Face geomFace;
9257   TopLoc_Location loc;
9258   double f,l, u = 0;
9259   gp_XY uv;
9260   vector< gp_XYZ > pos3D;
9261   bool isOnEdge;
9262   TGeomID prevBaseId = -1;
9263   TNode2Edge* n2eMap = 0;
9264   TNode2Edge::iterator n2e;
9265
9266   // Create intermediate nodes on each _LayerEdge
9267
9268   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9269   {
9270     _EdgesOnShape& eos = data._edgesOnShape[iS];
9271     if ( eos._edges.empty() ) continue;
9272
9273     if ( eos._edges[0]->_nodes.size() < 2 )
9274       continue; // on _noShrinkShapes
9275
9276     // get data of a shrink shape
9277     isOnEdge = false;
9278     geomEdge.Nullify(); geomFace.Nullify();
9279     curve.Nullify(); surface.Nullify();
9280     if ( !eos._sWOL.IsNull() )
9281     {
9282       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9283       if ( isOnEdge )
9284       {
9285         geomEdge = TopoDS::Edge( eos._sWOL );
9286         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9287       }
9288       else
9289       {
9290         geomFace = TopoDS::Face( eos._sWOL );
9291         surface  = helper.GetSurface( geomFace );
9292       }
9293     }
9294     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9295     {
9296       geomFace = TopoDS::Face( eos._shape );
9297       surface  = helper.GetSurface( geomFace );
9298       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9299       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9300       {
9301         eos._eosC1[ i ]->_toSmooth = true;
9302         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9303           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9304       }
9305     }
9306
9307     vector< double > segLen;
9308     for ( size_t i = 0; i < eos._edges.size(); ++i )
9309     {
9310       _LayerEdge& edge = *eos._edges[i];
9311       if ( edge._pos.size() < 2 )
9312         continue;
9313
9314       // get accumulated length of segments
9315       segLen.resize( edge._pos.size() );
9316       segLen[0] = 0.0;
9317       if ( eos._sWOL.IsNull() )
9318       {
9319         bool useNormal = true;
9320         bool   usePos  = false;
9321         bool smoothed  = false;
9322         double   preci = 0.1 * edge._len;
9323         if ( eos._toSmooth && edge._pos.size() > 2 )
9324         {
9325           smoothed = edge.GetSmoothedPos( preci );
9326         }
9327         if ( smoothed )
9328         {
9329           if ( !surface.IsNull() &&
9330                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9331           {
9332             useNormal = usePos = false;
9333             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9334             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9335             {
9336               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9337               if ( surface->Gap() < 2. * edge._len )
9338                 segLen[j] = surface->Gap();
9339               else
9340                 useNormal = true;
9341             }
9342           }
9343         }
9344         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9345         {
9346 #ifndef __NODES_AT_POS
9347           useNormal = usePos = false;
9348           edge._pos[1] = edge._pos.back();
9349           edge._pos.resize( 2 );
9350           segLen.resize( 2 );
9351           segLen[ 1 ] = edge._len;
9352 #endif
9353         }
9354         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9355         {
9356           useNormal = usePos = false;
9357           _LayerEdge tmpEdge; // get original _normal
9358           tmpEdge._nodes.push_back( edge._nodes[0] );
9359           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9360             usePos = true;
9361           else
9362             for ( size_t j = 1; j < edge._pos.size(); ++j )
9363               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9364         }
9365         if ( useNormal )
9366         {
9367           for ( size_t j = 1; j < edge._pos.size(); ++j )
9368             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9369         }
9370         if ( usePos )
9371         {
9372           for ( size_t j = 1; j < edge._pos.size(); ++j )
9373             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9374         }
9375         else
9376         {
9377           bool swapped = ( edge._pos.size() > 2 );
9378           while ( swapped )
9379           {
9380             swapped = false;
9381             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9382               if ( segLen[j] > segLen.back() )
9383               {
9384                 segLen.erase( segLen.begin() + j );
9385                 edge._pos.erase( edge._pos.begin() + j );
9386                 --j;
9387               }
9388               else if ( segLen[j] < segLen[j-1] )
9389               {
9390                 std::swap( segLen[j], segLen[j-1] );
9391                 std::swap( edge._pos[j], edge._pos[j-1] );
9392                 swapped = true;
9393               }
9394           }
9395         }
9396         // smooth a path formed by edge._pos
9397 #ifndef __NODES_AT_POS
9398         if (( smoothed ) /*&&
9399             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9400           edge.SmoothPos( segLen, preci );
9401 #endif
9402       }
9403       else if ( eos._isRegularSWOL ) // usual SWOL
9404       {
9405         for ( size_t j = 1; j < edge._pos.size(); ++j )
9406           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9407       }
9408       else if ( !surface.IsNull() ) // SWOL surface with singularities
9409       {
9410         pos3D.resize( edge._pos.size() );
9411         for ( size_t j = 0; j < edge._pos.size(); ++j )
9412           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9413
9414         for ( size_t j = 1; j < edge._pos.size(); ++j )
9415           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9416       }
9417
9418       // allocate memory for new nodes if it is not yet refined
9419       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9420       if ( edge._nodes.size() == 2 )
9421       {
9422 #ifdef __NODES_AT_POS
9423         int nbNodes = edge._pos.size();
9424 #else
9425         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9426 #endif
9427         edge._nodes.resize( nbNodes, 0 );
9428         edge._nodes[1] = 0;
9429         edge._nodes.back() = tgtNode;
9430       }
9431       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9432       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9433       if ( baseShapeId != prevBaseId )
9434       {
9435         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9436         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9437         prevBaseId = baseShapeId;
9438       }
9439       _LayerEdge* edgeOnSameNode = 0;
9440       bool        useExistingPos = false;
9441       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9442       {
9443         edgeOnSameNode = n2e->second;
9444         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9445         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9446         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9447         if ( isOnEdge )
9448         {
9449           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9450           epos->SetUParameter( otherTgtPos.X() );
9451         }
9452         else
9453         {
9454           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9455           fpos->SetUParameter( otherTgtPos.X() );
9456           fpos->SetVParameter( otherTgtPos.Y() );
9457         }
9458       }
9459       // calculate height of the first layer
9460       double h0;
9461       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9462       const double f = eos._hyp.GetStretchFactor();
9463       const int    N = eos._hyp.GetNumberLayers();
9464       const double fPowN = pow( f, N );
9465       if ( fPowN - 1 <= numeric_limits<double>::min() )
9466         h0 = T / N;
9467       else
9468         h0 = T * ( f - 1 )/( fPowN - 1 );
9469
9470       const double zeroLen = std::numeric_limits<double>::min();
9471
9472       // create intermediate nodes
9473       double hSum = 0, hi = h0/f;
9474       size_t iSeg = 1;
9475       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9476       {
9477         // compute an intermediate position
9478         hi *= f;
9479         hSum += hi;
9480         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9481           ++iSeg;
9482         int iPrevSeg = iSeg-1;
9483         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9484           --iPrevSeg;
9485         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9486         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9487 #ifdef __NODES_AT_POS
9488         pos = edge._pos[ iStep ];
9489 #endif
9490         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9491         if ( !eos._sWOL.IsNull() )
9492         {
9493           // compute XYZ by parameters <pos>
9494           if ( isOnEdge )
9495           {
9496             u = pos.X();
9497             if ( !node )
9498               pos = curve->Value( u ).Transformed(loc);
9499           }
9500           else if ( eos._isRegularSWOL )
9501           {
9502             uv.SetCoord( pos.X(), pos.Y() );
9503             if ( !node )
9504               pos = surface->Value( pos.X(), pos.Y() );
9505           }
9506           else
9507           {
9508             uv.SetCoord( pos.X(), pos.Y() );
9509             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9510             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9511             if ( !node )
9512               pos = surface->Value( uv );
9513           }
9514         }
9515         // create or update the node
9516         if ( !node )
9517         {
9518           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9519           if ( !eos._sWOL.IsNull() )
9520           {
9521             if ( isOnEdge )
9522               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9523             else
9524               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9525           }
9526           else
9527           {
9528             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9529           }
9530         }
9531         else
9532         {
9533           if ( !eos._sWOL.IsNull() )
9534           {
9535             // make average pos from new and current parameters
9536             if ( isOnEdge )
9537             {
9538               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9539               if ( useExistingPos )
9540                 u = helper.GetNodeU( geomEdge, node );
9541               pos = curve->Value( u ).Transformed(loc);
9542
9543               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9544               epos->SetUParameter( u );
9545             }
9546             else
9547             {
9548               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9549               if ( useExistingPos )
9550                 uv = helper.GetNodeUV( geomFace, node );
9551               pos = surface->Value( uv );
9552
9553               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9554               fpos->SetUParameter( uv.X() );
9555               fpos->SetVParameter( uv.Y() );
9556             }
9557           }
9558           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9559         }
9560       } // loop on edge._nodes
9561
9562       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9563       {
9564         if ( isOnEdge )
9565           edge._pos.back().SetCoord( u, 0,0);
9566         else
9567           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9568
9569         if ( edgeOnSameNode )
9570           edgeOnSameNode->_pos.back() = edge._pos.back();
9571       }
9572
9573     } // loop on eos._edges to create nodes
9574
9575
9576     if ( !getMeshDS()->IsEmbeddedMode() )
9577       // Log node movement
9578       for ( size_t i = 0; i < eos._edges.size(); ++i )
9579       {
9580         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9581         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9582       }
9583   }
9584
9585
9586   // Create volumes
9587
9588   helper.SetElementsOnShape(true);
9589
9590   vector< vector<const SMDS_MeshNode*>* > nnVec;
9591   set< vector<const SMDS_MeshNode*>* >    nnSet;
9592   set< int >                       degenEdgeInd;
9593   vector<const SMDS_MeshElement*>     degenVols;
9594
9595   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9596   for ( ; exp.More(); exp.Next() )
9597   {
9598     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9599     if ( data._ignoreFaceIds.count( faceID ))
9600       continue;
9601     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9602     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9603     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9604     while ( fIt->more() )
9605     {
9606       const SMDS_MeshElement* face = fIt->next();
9607       const int            nbNodes = face->NbCornerNodes();
9608       nnVec.resize( nbNodes );
9609       nnSet.clear();
9610       degenEdgeInd.clear();
9611       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9612       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9613       for ( int iN = 0; iN < nbNodes; ++iN )
9614       {
9615         const SMDS_MeshNode* n = nIt->next();
9616         _LayerEdge*       edge = data._n2eMap[ n ];
9617         const int i = isReversedFace ? nbNodes-1-iN : iN;
9618         nnVec[ i ] = & edge->_nodes;
9619         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9620         minZ = std::min( minZ, nnVec[ i ]->size() );
9621
9622         if ( helper.HasDegeneratedEdges() )
9623           nnSet.insert( nnVec[ i ]);
9624       }
9625
9626       if ( maxZ == 0 )
9627         continue;
9628       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9629         continue;
9630
9631       switch ( nbNodes )
9632       {
9633       case 3: // TRIA
9634       {
9635         // PENTA
9636         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9637           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9638                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9639
9640         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9641         {
9642           for ( int iN = 0; iN < nbNodes; ++iN )
9643             if ( nnVec[ iN ]->size() < iZ+1 )
9644               degenEdgeInd.insert( iN );
9645
9646           if ( degenEdgeInd.size() == 1 )  // PYRAM
9647           {
9648             int i2 = *degenEdgeInd.begin();
9649             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9650             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9651             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9652                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9653           }
9654           else  // TETRA
9655           {
9656             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9657             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9658                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9659                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9660                               (*nnVec[ i3 ])[ iZ ]);
9661           }
9662         }
9663         break; // TRIA
9664       }
9665       case 4: // QUAD
9666       {
9667         // HEX
9668         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9669           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9670                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9671                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9672                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9673
9674         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9675         {
9676           for ( int iN = 0; iN < nbNodes; ++iN )
9677             if ( nnVec[ iN ]->size() < iZ+1 )
9678               degenEdgeInd.insert( iN );
9679
9680           switch ( degenEdgeInd.size() )
9681           {
9682           case 2: // PENTA
9683           {
9684             int i2 = *degenEdgeInd.begin();
9685             int i3 = *degenEdgeInd.rbegin();
9686             bool ok = ( i3 - i2 == 1 );
9687             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9688             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9689             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9690
9691             const SMDS_MeshElement* vol =
9692               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9693                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9694             if ( !ok && vol )
9695               degenVols.push_back( vol );
9696           }
9697           break;
9698
9699           default: // degen HEX
9700           {
9701             const SMDS_MeshElement* vol =
9702               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9703                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9704                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9705                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9706                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9707                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9708                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9709                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9710             degenVols.push_back( vol );
9711           }
9712           }
9713         }
9714         break; // HEX
9715       }
9716       default:
9717         return error("Not supported type of element", data._index);
9718
9719       } // switch ( nbNodes )
9720     } // while ( fIt->more() )
9721   } // loop on FACEs
9722
9723   if ( !degenVols.empty() )
9724   {
9725     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9726     if ( !err || err->IsOK() )
9727     {
9728       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9729                                          "Bad quality volumes created" ));
9730       err->myBadElements.insert( err->myBadElements.end(),
9731                                  degenVols.begin(),degenVols.end() );
9732     }
9733   }
9734
9735   return true;
9736 }
9737
9738 //================================================================================
9739 /*!
9740  * \brief Shrink 2D mesh on faces to let space for inflated layers
9741  */
9742 //================================================================================
9743
9744 bool _ViscousBuilder::shrink(_SolidData& theData)
9745 {
9746   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
9747   // _LayerEdge's inflated along FACE or EDGE)
9748   map< TGeomID, list< _SolidData* > > f2sdMap;
9749   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9750   {
9751     _SolidData& data = _sdVec[i];
9752     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9753     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9754       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrinkedFaces.Contains( s2s->second ))
9755       {
9756         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
9757
9758         // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9759         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9760         // by StdMeshers_QuadToTriaAdaptor
9761         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9762         {
9763           SMESH_ProxyMesh::SubMesh* proxySub =
9764             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9765           if ( proxySub->NbElements() == 0 )
9766           {
9767             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9768             while ( fIt->more() )
9769             {
9770               const SMDS_MeshElement* f = fIt->next();
9771               // as a result 3D algo will use elements from proxySub and not from smDS
9772               proxySub->AddElement( f );
9773               f->setIsMarked( true );
9774
9775               // Mark nodes on the FACE to discriminate them from nodes
9776               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
9777               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
9778               {
9779                 const SMDS_MeshNode* n = f->GetNode( iN );
9780                 if ( n->GetPosition()->GetDim() == 2 )
9781                   n->setIsMarked( true );
9782               }
9783             }
9784           }
9785         }
9786       }
9787   }
9788
9789   SMESH_MesherHelper helper( *_mesh );
9790   helper.ToFixNodeParameters( true );
9791
9792   // EDGEs to shrink
9793   map< TGeomID, _Shrinker1D > e2shrMap;
9794   vector< _EdgesOnShape* > subEOS;
9795   vector< _LayerEdge* > lEdges;
9796
9797   // loop on FACEs to srink mesh on
9798   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
9799   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9800   {
9801     list< _SolidData* > & dataList = f2sd->second;
9802     if ( dataList.front()->_n2eMap.empty() ||
9803          dataList.back() ->_n2eMap.empty() )
9804       continue; // not yet computed
9805     if ( dataList.front() != &theData &&
9806          dataList.back()  != &theData )
9807       continue;
9808
9809     _SolidData&      data = *dataList.front();
9810     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
9811     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9812     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9813     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9814
9815     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
9816
9817     _shrinkedFaces.Add( F );
9818     helper.SetSubShape( F );
9819
9820     // ===========================
9821     // Prepare data for shrinking
9822     // ===========================
9823
9824     // Collect nodes to smooth (they are marked at the beginning of this method)
9825     vector < const SMDS_MeshNode* > smoothNodes;
9826     {
9827       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9828       while ( nIt->more() )
9829       {
9830         const SMDS_MeshNode* n = nIt->next();
9831         if ( n->isMarked() )
9832           smoothNodes.push_back( n );
9833       }
9834     }
9835     // Find out face orientation
9836     double refSign = 1;
9837     const set<TGeomID> ignoreShapes;
9838     bool isOkUV;
9839     if ( !smoothNodes.empty() )
9840     {
9841       vector<_Simplex> simplices;
9842       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9843       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
9844       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9845       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9846       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
9847         refSign = -1;
9848     }
9849
9850     // Find _LayerEdge's inflated along F
9851     subEOS.clear();
9852     lEdges.clear();
9853     {
9854       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9855                                                                 /*complexFirst=*/true); //!!!
9856       while ( subIt->more() )
9857       {
9858         const TGeomID subID = subIt->next()->GetId();
9859         if ( data._noShrinkShapes.count( subID ))
9860           continue;
9861         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9862         if ( !eos || eos->_sWOL.IsNull() )
9863           if ( data2 ) // check in adjacent SOLID
9864           {
9865             eos = data2->GetShapeEdges( subID );
9866             if ( !eos || eos->_sWOL.IsNull() )
9867               continue;
9868           }
9869         subEOS.push_back( eos );
9870
9871         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9872         {
9873           lEdges.push_back( eos->_edges[ i ] );
9874           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9875         }
9876       }
9877     }
9878
9879     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9880     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9881     while ( fIt->more() )
9882       if ( const SMDS_MeshElement* f = fIt->next() )
9883         dumpChangeNodes( f );
9884     dumpFunctionEnd();
9885
9886     // Replace source nodes by target nodes in mesh faces to shrink
9887     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9888     const SMDS_MeshNode* nodes[20];
9889     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9890     {
9891       _EdgesOnShape& eos = * subEOS[ iS ];
9892       for ( size_t i = 0; i < eos._edges.size(); ++i )
9893       {
9894         _LayerEdge& edge = *eos._edges[i];
9895         const SMDS_MeshNode* srcNode = edge._nodes[0];
9896         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9897         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9898         while ( fIt->more() )
9899         {
9900           const SMDS_MeshElement* f = fIt->next();
9901           if ( !smDS->Contains( f ) || !f->isMarked() )
9902             continue;
9903           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9904           for ( int iN = 0; nIt->more(); ++iN )
9905           {
9906             const SMDS_MeshNode* n = nIt->next();
9907             nodes[iN] = ( n == srcNode ? tgtNode : n );
9908           }
9909           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9910           dumpChangeNodes( f );
9911         }
9912       }
9913     }
9914     dumpFunctionEnd();
9915
9916     // find out if a FACE is concave
9917     const bool isConcaveFace = isConcave( F, helper );
9918
9919     // Create _SmoothNode's on face F
9920     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9921     {
9922       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9923       const bool sortSimplices = isConcaveFace;
9924       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9925       {
9926         const SMDS_MeshNode* n = smoothNodes[i];
9927         nodesToSmooth[ i ]._node = n;
9928         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
9929         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9930         // fix up incorrect uv of nodes on the FACE
9931         helper.GetNodeUV( F, n, 0, &isOkUV);
9932         dumpMove( n );
9933       }
9934       dumpFunctionEnd();
9935     }
9936     //if ( nodesToSmooth.empty() ) continue;
9937
9938     // Find EDGE's to shrink and set simpices to LayerEdge's
9939     set< _Shrinker1D* > eShri1D;
9940     {
9941       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9942       {
9943         _EdgesOnShape& eos = * subEOS[ iS ];
9944         if ( eos.SWOLType() == TopAbs_EDGE )
9945         {
9946           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9947           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9948           eShri1D.insert( & srinker );
9949           srinker.AddEdge( eos._edges[0], eos, helper );
9950           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9951           // restore params of nodes on EGDE if the EDGE has been already
9952           // srinked while srinking other FACE
9953           srinker.RestoreParams();
9954         }
9955         for ( size_t i = 0; i < eos._edges.size(); ++i )
9956         {
9957           _LayerEdge& edge = * eos._edges[i];
9958           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9959
9960           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
9961           // not-marked nodes are those added by refine()
9962           edge._nodes.back()->setIsMarked( true );
9963         }
9964       }
9965     }
9966
9967     bool toFixTria = false; // to improve quality of trias by diagonal swap
9968     if ( isConcaveFace )
9969     {
9970       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9971       if ( hasTria != hasQuad ) {
9972         toFixTria = hasTria;
9973       }
9974       else {
9975         set<int> nbNodesSet;
9976         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9977         while ( fIt->more() && nbNodesSet.size() < 2 )
9978           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9979         toFixTria = ( *nbNodesSet.begin() == 3 );
9980       }
9981     }
9982
9983     // ==================
9984     // Perform shrinking
9985     // ==================
9986
9987     bool shrinked = true;
9988     int nbBad, shriStep=0, smooStep=0;
9989     _SmoothNode::SmoothType smoothType
9990       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9991     SMESH_Comment errMsg;
9992     while ( shrinked )
9993     {
9994       shriStep++;
9995       // Move boundary nodes (actually just set new UV)
9996       // -----------------------------------------------
9997       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9998       shrinked = false;
9999       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10000       {
10001         _EdgesOnShape& eos = * subEOS[ iS ];
10002         for ( size_t i = 0; i < eos._edges.size(); ++i )
10003         {
10004           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
10005         }
10006       }
10007       dumpFunctionEnd();
10008
10009       // Move nodes on EDGE's
10010       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
10011       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
10012       for ( ; shr != eShri1D.end(); ++shr )
10013         (*shr)->Compute( /*set3D=*/false, helper );
10014
10015       // Smoothing in 2D
10016       // -----------------
10017       int nbNoImpSteps = 0;
10018       bool       moved = true;
10019       nbBad = 1;
10020       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
10021       {
10022         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10023
10024         int oldBadNb = nbBad;
10025         nbBad = 0;
10026         moved = false;
10027         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
10028         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
10029         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10030         {
10031           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
10032                                             smooTy, /*set3D=*/isConcaveFace);
10033         }
10034         if ( nbBad < oldBadNb )
10035           nbNoImpSteps = 0;
10036         else
10037           nbNoImpSteps++;
10038
10039         dumpFunctionEnd();
10040       }
10041
10042       errMsg.clear();
10043       if ( nbBad > 0 )
10044         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
10045       if ( shriStep > 200 )
10046         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
10047       if ( !errMsg.empty() )
10048         break;
10049
10050       // Fix narrow triangles by swapping diagonals
10051       // ---------------------------------------
10052       if ( toFixTria )
10053       {
10054         set<const SMDS_MeshNode*> usedNodes;
10055         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
10056
10057         // update working data
10058         set<const SMDS_MeshNode*>::iterator n;
10059         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
10060         {
10061           n = usedNodes.find( nodesToSmooth[ i ]._node );
10062           if ( n != usedNodes.end())
10063           {
10064             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
10065                                     nodesToSmooth[ i ]._simplices,
10066                                     ignoreShapes, NULL,
10067                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
10068             usedNodes.erase( n );
10069           }
10070         }
10071         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
10072         {
10073           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
10074           if ( n != usedNodes.end())
10075           {
10076             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
10077                                     lEdges[i]->_simplices,
10078                                     ignoreShapes );
10079             usedNodes.erase( n );
10080           }
10081         }
10082       }
10083       // TODO: check effect of this additional smooth
10084       // additional laplacian smooth to increase allowed shrink step
10085       // for ( int st = 1; st; --st )
10086       // {
10087       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10088       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10089       //   {
10090       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10091       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
10092       //   }
10093       // }
10094
10095     } // while ( shrinked )
10096
10097     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
10098     {
10099       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
10100
10101       // remove faces
10102       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
10103       {
10104         vector< const SMDS_MeshElement* > facesToRm;
10105         if ( psm )
10106         {
10107           facesToRm.reserve( psm->NbElements() );
10108           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
10109             facesToRm.push_back( ite->next() );
10110
10111           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10112             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10113               psm->Clear();
10114         }
10115         for ( size_t i = 0; i < facesToRm.size(); ++i )
10116           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
10117       }
10118       // remove nodes
10119       {
10120         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
10121         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
10122           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10123             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
10124                                 subEOS[iS]->_edges[i]->_nodes.end() );
10125         }
10126         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
10127         while ( itn->more() ) {
10128           const SMDS_MeshNode* n = itn->next();
10129           if ( !nodesToKeep.count( n ))
10130             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
10131         }
10132       }
10133       // restore position and UV of target nodes
10134       gp_Pnt p;
10135       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10136         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
10137         {
10138           _LayerEdge*       edge = subEOS[iS]->_edges[i];
10139           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
10140           if ( edge->_pos.empty() ||
10141                edge->Is( _LayerEdge::SHRUNK )) continue;
10142           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
10143           {
10144             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10145             pos->SetUParameter( edge->_pos[0].X() );
10146             pos->SetVParameter( edge->_pos[0].Y() );
10147             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10148           }
10149           else
10150           {
10151             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10152             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10153             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10154           }
10155           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10156           dumpMove( tgtNode );
10157         }
10158       // shrink EDGE sub-meshes and set proxy sub-meshes
10159       UVPtStructVec uvPtVec;
10160       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10161       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10162       {
10163         _Shrinker1D* shr = (*shrIt);
10164         shr->Compute( /*set3D=*/true, helper );
10165
10166         // set proxy mesh of EDGEs w/o layers
10167         map< double, const SMDS_MeshNode* > nodes;
10168         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10169         // remove refinement nodes
10170         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10171         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10172         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10173         if ( u2n->second == sn0 || u2n->second == sn1 )
10174         {
10175           while ( u2n->second != tn0 && u2n->second != tn1 )
10176             ++u2n;
10177           nodes.erase( nodes.begin(), u2n );
10178         }
10179         u2n = --nodes.end();
10180         if ( u2n->second == sn0 || u2n->second == sn1 )
10181         {
10182           while ( u2n->second != tn0 && u2n->second != tn1 )
10183             --u2n;
10184           nodes.erase( ++u2n, nodes.end() );
10185         }
10186         // set proxy sub-mesh
10187         uvPtVec.resize( nodes.size() );
10188         u2n = nodes.begin();
10189         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10190         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10191         {
10192           uvPtVec[ i ].node = u2n->second;
10193           uvPtVec[ i ].param = u2n->first;
10194           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10195         }
10196         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10197         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10198       }
10199
10200       // set proxy mesh of EDGEs with layers
10201       vector< _LayerEdge* > edges;
10202       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10203       {
10204         _EdgesOnShape& eos = * subEOS[ iS ];
10205         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10206
10207         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10208         data.SortOnEdge( E, eos._edges );
10209
10210         edges.clear();
10211         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10212           if ( !eov->_edges.empty() )
10213             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10214
10215         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10216
10217         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10218           if ( !eov->_edges.empty() )
10219             edges.push_back( eov->_edges[0] ); // on last VERTEX
10220
10221         uvPtVec.resize( edges.size() );
10222         for ( size_t i = 0; i < edges.size(); ++i )
10223         {
10224           uvPtVec[ i ].node = edges[i]->_nodes.back();
10225           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10226           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10227         }
10228         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10229         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10230         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10231       }
10232       // temporary clear the FACE sub-mesh from faces made by refine()
10233       vector< const SMDS_MeshElement* > elems;
10234       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10235       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10236         elems.push_back( ite->next() );
10237       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10238         elems.push_back( ite->next() );
10239       smDS->Clear();
10240
10241       // compute the mesh on the FACE
10242       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10243       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10244
10245       // re-fill proxy sub-meshes of the FACE
10246       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10247         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10248           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10249             psm->AddElement( ite->next() );
10250
10251       // re-fill smDS
10252       for ( size_t i = 0; i < elems.size(); ++i )
10253         smDS->AddElement( elems[i] );
10254
10255       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10256         return error( errMsg );
10257
10258     } // end of re-meshing in case of failed smoothing
10259     else
10260     {
10261       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10262       bool isStructuredFixed = false;
10263       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10264         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10265       if ( !isStructuredFixed )
10266       {
10267         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10268           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10269
10270         for ( int st = 3; st; --st )
10271         {
10272           switch( st ) {
10273           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10274           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10275           case 3: smoothType = _SmoothNode::ANGULAR; break;
10276           }
10277           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10278           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10279           {
10280             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10281                                      smoothType,/*set3D=*/st==1 );
10282           }
10283           dumpFunctionEnd();
10284         }
10285       }
10286       if ( !getMeshDS()->IsEmbeddedMode() )
10287         // Log node movement
10288         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10289         {
10290           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10291           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10292         }
10293     }
10294
10295     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10296     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10297     if ( data2 )
10298       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
10299
10300   } // loop on FACES to srink mesh on
10301
10302
10303   // Replace source nodes by target nodes in shrinked mesh edges
10304
10305   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10306   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10307     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10308
10309   return true;
10310 }
10311
10312 //================================================================================
10313 /*!
10314  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10315  */
10316 //================================================================================
10317
10318 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10319                                            _EdgesOnShape&         eos,
10320                                            SMESH_MesherHelper&    helper,
10321                                            const SMESHDS_SubMesh* faceSubMesh)
10322 {
10323   const SMDS_MeshNode* srcNode = edge._nodes[0];
10324   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10325
10326   if ( eos.SWOLType() == TopAbs_FACE )
10327   {
10328     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10329     {
10330       edge._pos.clear();
10331       edge.Set( _LayerEdge::SHRUNK );
10332       return srcNode == tgtNode;
10333     }
10334     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10335     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10336     gp_Vec2d uvDir( srcUV, tgtUV );
10337     double uvLen = uvDir.Magnitude();
10338     uvDir /= uvLen;
10339     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10340     edge._len = uvLen;
10341
10342     //edge._pos.resize(1);
10343     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10344
10345     // set UV of source node to target node
10346     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10347     pos->SetUParameter( srcUV.X() );
10348     pos->SetVParameter( srcUV.Y() );
10349   }
10350   else // _sWOL is TopAbs_EDGE
10351   {
10352     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10353     {
10354       edge._pos.clear();
10355       edge.Set( _LayerEdge::SHRUNK );
10356       return srcNode == tgtNode;
10357     }
10358     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10359     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10360     if ( !edgeSM || edgeSM->NbElements() == 0 )
10361       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10362
10363     const SMDS_MeshNode* n2 = 0;
10364     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10365     while ( eIt->more() && !n2 )
10366     {
10367       const SMDS_MeshElement* e = eIt->next();
10368       if ( !edgeSM->Contains(e)) continue;
10369       n2 = e->GetNode( 0 );
10370       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10371     }
10372     if ( !n2 )
10373       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10374
10375     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10376     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10377     double u2   = helper.GetNodeU( E, n2,      srcNode );
10378
10379     //edge._pos.clear();
10380
10381     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10382     {
10383       // tgtNode is located so that it does not make faces with wrong orientation
10384       edge.Set( _LayerEdge::SHRUNK );
10385       return true;
10386     }
10387     //edge._pos.resize(1);
10388     edge._pos[0].SetCoord( U_TGT, uTgt );
10389     edge._pos[0].SetCoord( U_SRC, uSrc );
10390     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10391
10392     edge._simplices.resize( 1 );
10393     edge._simplices[0]._nPrev = n2;
10394
10395     // set U of source node to the target node
10396     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10397     pos->SetUParameter( uSrc );
10398   }
10399   return true;
10400 }
10401
10402 //================================================================================
10403 /*!
10404  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10405  */
10406 //================================================================================
10407
10408 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10409 {
10410   if ( edge._nodes.size() == 1 )
10411   {
10412     edge._pos.clear();
10413     edge._len = 0;
10414
10415     const SMDS_MeshNode* srcNode = edge._nodes[0];
10416     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10417     if ( S.IsNull() ) return;
10418
10419     gp_Pnt p;
10420
10421     switch ( S.ShapeType() )
10422     {
10423     case TopAbs_EDGE:
10424     {
10425       double f,l;
10426       TopLoc_Location loc;
10427       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10428       if ( curve.IsNull() ) return;
10429       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10430       p = curve->Value( ePos->GetUParameter() );
10431       break;
10432     }
10433     case TopAbs_VERTEX:
10434     {
10435       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10436       break;
10437     }
10438     default: return;
10439     }
10440     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10441     dumpMove( srcNode );
10442   }
10443 }
10444
10445 //================================================================================
10446 /*!
10447  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10448  */
10449 //================================================================================
10450
10451 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10452                                   SMESH_MesherHelper&         helper,
10453                                   const bool                  is2D,
10454                                   const int                   step,
10455                                   set<const SMDS_MeshNode*> * involvedNodes)
10456 {
10457   SMESH::Controls::AspectRatio qualifier;
10458   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10459   const double maxAspectRatio = is2D ? 4. : 2;
10460   _NodeCoordHelper xyz( F, helper, is2D );
10461
10462   // find bad triangles
10463
10464   vector< const SMDS_MeshElement* > badTrias;
10465   vector< double >                  badAspects;
10466   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10467   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10468   while ( fIt->more() )
10469   {
10470     const SMDS_MeshElement * f = fIt->next();
10471     if ( f->NbCornerNodes() != 3 ) continue;
10472     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10473     double aspect = qualifier.GetValue( points );
10474     if ( aspect > maxAspectRatio )
10475     {
10476       badTrias.push_back( f );
10477       badAspects.push_back( aspect );
10478     }
10479   }
10480   if ( step == 1 )
10481   {
10482     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10483     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10484     while ( fIt->more() )
10485     {
10486       const SMDS_MeshElement * f = fIt->next();
10487       if ( f->NbCornerNodes() == 3 )
10488         dumpChangeNodes( f );
10489     }
10490     dumpFunctionEnd();
10491   }
10492   if ( badTrias.empty() )
10493     return;
10494
10495   // find couples of faces to swap diagonal
10496
10497   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10498   vector< T2Trias > triaCouples; 
10499
10500   TIDSortedElemSet involvedFaces, emptySet;
10501   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10502   {
10503     T2Trias trias    [3];
10504     double  aspRatio [3];
10505     int i1, i2, i3;
10506
10507     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10508       continue;
10509     for ( int iP = 0; iP < 3; ++iP )
10510       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10511
10512     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10513     int bestCouple = -1;
10514     for ( int iSide = 0; iSide < 3; ++iSide )
10515     {
10516       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10517       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10518       trias [iSide].first  = badTrias[iTia];
10519       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10520                                                              & i1, & i2 );
10521       if (( ! trias[iSide].second ) ||
10522           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10523           ( ! sm->Contains( trias[iSide].second )))
10524         continue;
10525
10526       // aspect ratio of an adjacent tria
10527       for ( int iP = 0; iP < 3; ++iP )
10528         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10529       double aspectInit = qualifier.GetValue( points2 );
10530
10531       // arrange nodes as after diag-swaping
10532       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10533         i3 = helper.WrapIndex( i1-1, 3 );
10534       else
10535         i3 = helper.WrapIndex( i1+1, 3 );
10536       points1 = points;
10537       points1( 1+ iSide ) = points2( 1+ i3 );
10538       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10539
10540       // aspect ratio after diag-swaping
10541       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10542       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10543         continue;
10544
10545       // prevent inversion of a triangle
10546       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10547       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10548       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10549         continue;
10550
10551       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10552         bestCouple = iSide;
10553     }
10554
10555     if ( bestCouple >= 0 )
10556     {
10557       triaCouples.push_back( trias[bestCouple] );
10558       involvedFaces.insert ( trias[bestCouple].second );
10559     }
10560     else
10561     {
10562       involvedFaces.erase( badTrias[iTia] );
10563     }
10564   }
10565   if ( triaCouples.empty() )
10566     return;
10567
10568   // swap diagonals
10569
10570   SMESH_MeshEditor editor( helper.GetMesh() );
10571   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10572   for ( size_t i = 0; i < triaCouples.size(); ++i )
10573   {
10574     dumpChangeNodes( triaCouples[i].first );
10575     dumpChangeNodes( triaCouples[i].second );
10576     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10577   }
10578
10579   if ( involvedNodes )
10580     for ( size_t i = 0; i < triaCouples.size(); ++i )
10581     {
10582       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10583                              triaCouples[i].first->end_nodes() );
10584       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10585                              triaCouples[i].second->end_nodes() );
10586     }
10587
10588   // just for debug dump resulting triangles
10589   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10590   for ( size_t i = 0; i < triaCouples.size(); ++i )
10591   {
10592     dumpChangeNodes( triaCouples[i].first );
10593     dumpChangeNodes( triaCouples[i].second );
10594   }
10595 }
10596
10597 //================================================================================
10598 /*!
10599  * \brief Move target node to it's final position on the FACE during shrinking
10600  */
10601 //================================================================================
10602
10603 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10604                                  const TopoDS_Face&    F,
10605                                  _EdgesOnShape&        eos,
10606                                  SMESH_MesherHelper&   helper )
10607 {
10608   if ( Is( SHRUNK ))
10609     return false; // already at the target position
10610
10611   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10612
10613   if ( eos.SWOLType() == TopAbs_FACE )
10614   {
10615     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10616     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10617     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10618     const double uvLen = tgtUV.Distance( curUV );
10619     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10620
10621     // Select shrinking step such that not to make faces with wrong orientation.
10622     double stepSize = 1e100;
10623     for ( size_t i = 0; i < _simplices.size(); ++i )
10624     {
10625       if ( !_simplices[i]._nPrev->isMarked() ||
10626            !_simplices[i]._nNext->isMarked() )
10627         continue; // simplex of quadrangle created by addBoundaryElements()
10628
10629       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10630       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10631       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10632       gp_XY dirN = uvN2 - uvN1;
10633       double det = uvDir.Crossed( dirN );
10634       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10635       gp_XY dirN2Cur = curUV - uvN1;
10636       double step = dirN.Crossed( dirN2Cur ) / det;
10637       if ( step > 0 )
10638         stepSize = Min( step, stepSize );
10639     }
10640     gp_Pnt2d newUV;
10641     if ( uvLen <= stepSize )
10642     {
10643       newUV = tgtUV;
10644       Set( SHRUNK );
10645       //_pos.clear();
10646     }
10647     else if ( stepSize > 0 )
10648     {
10649       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10650     }
10651     else
10652     {
10653       return true;
10654     }
10655     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10656     pos->SetUParameter( newUV.X() );
10657     pos->SetVParameter( newUV.Y() );
10658
10659 #ifdef __myDEBUG
10660     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10661     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10662     dumpMove( tgtNode );
10663 #endif
10664   }
10665   else // _sWOL is TopAbs_EDGE
10666   {
10667     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10668     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10669     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10670
10671     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10672     const double uSrc   = _pos[0].Coord( U_SRC );
10673     const double lenTgt = _pos[0].Coord( LEN_TGT );
10674
10675     double newU = _pos[0].Coord( U_TGT );
10676     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10677     {
10678       Set( _LayerEdge::SHRUNK );
10679       //_pos.clear();
10680     }
10681     else
10682     {
10683       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10684     }
10685     tgtPos->SetUParameter( newU );
10686 #ifdef __myDEBUG
10687     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10688     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10689     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10690     dumpMove( tgtNode );
10691 #endif
10692   }
10693
10694   return true;
10695 }
10696
10697 //================================================================================
10698 /*!
10699  * \brief Perform smooth on the FACE
10700  *  \retval bool - true if the node has been moved
10701  */
10702 //================================================================================
10703
10704 bool _SmoothNode::Smooth(int&                  nbBad,
10705                          Handle(Geom_Surface)& surface,
10706                          SMESH_MesherHelper&   helper,
10707                          const double          refSign,
10708                          SmoothType            how,
10709                          bool                  set3D)
10710 {
10711   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10712
10713   // get uv of surrounding nodes
10714   vector<gp_XY> uv( _simplices.size() );
10715   for ( size_t i = 0; i < _simplices.size(); ++i )
10716     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10717
10718   // compute new UV for the node
10719   gp_XY newPos (0,0);
10720   if ( how == TFI && _simplices.size() == 4 )
10721   {
10722     gp_XY corners[4];
10723     for ( size_t i = 0; i < _simplices.size(); ++i )
10724       if ( _simplices[i]._nOpp )
10725         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10726       else
10727         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10728
10729     newPos = helper.calcTFI ( 0.5, 0.5,
10730                               corners[0], corners[1], corners[2], corners[3],
10731                               uv[1], uv[2], uv[3], uv[0] );
10732   }
10733   else if ( how == ANGULAR )
10734   {
10735     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10736   }
10737   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10738   {
10739     // average centers of diagonals wieghted with their reciprocal lengths
10740     if ( _simplices.size() == 4 )
10741     {
10742       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10743       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10744       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10745     }
10746     else
10747     {
10748       double sumWeight = 0;
10749       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10750       for ( int i = 0; i < nb; ++i )
10751       {
10752         int iFrom = i + 2;
10753         int iTo   = i + _simplices.size() - 1;
10754         for ( int j = iFrom; j < iTo; ++j )
10755         {
10756           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10757           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10758           sumWeight += w;
10759           newPos += w * ( uv[i]+uv[i2] );
10760         }
10761       }
10762       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10763     }
10764   }
10765   else
10766   {
10767     // Laplacian smooth
10768     for ( size_t i = 0; i < _simplices.size(); ++i )
10769       newPos += uv[i];
10770     newPos /= _simplices.size();
10771   }
10772
10773   // count quality metrics (orientation) of triangles around the node
10774   int nbOkBefore = 0;
10775   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10776   for ( size_t i = 0; i < _simplices.size(); ++i )
10777     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10778
10779   int nbOkAfter = 0;
10780   for ( size_t i = 0; i < _simplices.size(); ++i )
10781     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10782
10783   if ( nbOkAfter < nbOkBefore )
10784   {
10785     nbBad += _simplices.size() - nbOkBefore;
10786     return false;
10787   }
10788
10789   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10790   pos->SetUParameter( newPos.X() );
10791   pos->SetVParameter( newPos.Y() );
10792
10793 #ifdef __myDEBUG
10794   set3D = true;
10795 #endif
10796   if ( set3D )
10797   {
10798     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10799     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10800     dumpMove( _node );
10801   }
10802
10803   nbBad += _simplices.size() - nbOkAfter;
10804   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10805 }
10806
10807 //================================================================================
10808 /*!
10809  * \brief Computes new UV using angle based smoothing technic
10810  */
10811 //================================================================================
10812
10813 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10814                                      const gp_XY&   uvToFix,
10815                                      const double   refSign)
10816 {
10817   uv.push_back( uv.front() );
10818
10819   vector< gp_XY >  edgeDir ( uv.size() );
10820   vector< double > edgeSize( uv.size() );
10821   for ( size_t i = 1; i < edgeDir.size(); ++i )
10822   {
10823     edgeDir [i-1] = uv[i] - uv[i-1];
10824     edgeSize[i-1] = edgeDir[i-1].Modulus();
10825     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10826       edgeDir[i-1].SetX( 100 );
10827     else
10828       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10829   }
10830   edgeDir.back()  = edgeDir.front();
10831   edgeSize.back() = edgeSize.front();
10832
10833   gp_XY  newPos(0,0);
10834   //int    nbEdges = 0;
10835   double sumSize = 0;
10836   for ( size_t i = 1; i < edgeDir.size(); ++i )
10837   {
10838     if ( edgeDir[i-1].X() > 1. ) continue;
10839     int i1 = i-1;
10840     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10841     if ( i == edgeDir.size() ) break;
10842     gp_XY p = uv[i];
10843     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10844     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10845     gp_XY bisec = norm1 + norm2;
10846     double bisecSize = bisec.Modulus();
10847     if ( bisecSize < numeric_limits<double>::min() )
10848     {
10849       bisec = -edgeDir[i1] + edgeDir[i];
10850       bisecSize = bisec.Modulus();
10851     }
10852     bisec /= bisecSize;
10853
10854     gp_XY  dirToN  = uvToFix - p;
10855     double distToN = dirToN.Modulus();
10856     if ( bisec * dirToN < 0 )
10857       distToN = -distToN;
10858
10859     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10860     //++nbEdges;
10861     sumSize += edgeSize[i1] + edgeSize[i];
10862   }
10863   newPos /= /*nbEdges * */sumSize;
10864   return newPos;
10865 }
10866
10867 //================================================================================
10868 /*!
10869  * \brief Delete _SolidData
10870  */
10871 //================================================================================
10872
10873 _SolidData::~_SolidData()
10874 {
10875   TNode2Edge::iterator n2e = _n2eMap.begin();
10876   for ( ; n2e != _n2eMap.end(); ++n2e )
10877   {
10878     _LayerEdge* & e = n2e->second;
10879     if ( e )
10880     {
10881       delete e->_curvature;
10882       if ( e->_2neibors )
10883         delete e->_2neibors->_plnNorm;
10884       delete e->_2neibors;
10885     }
10886     delete e;
10887     e = 0;
10888   }
10889   _n2eMap.clear();
10890
10891   delete _helper;
10892   _helper = 0;
10893 }
10894
10895 //================================================================================
10896 /*!
10897  * \brief Keep a _LayerEdge inflated along the EDGE
10898  */
10899 //================================================================================
10900
10901 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10902                            _EdgesOnShape&      eos,
10903                            SMESH_MesherHelper& helper )
10904 {
10905   // init
10906   if ( _nodes.empty() )
10907   {
10908     _edges[0] = _edges[1] = 0;
10909     _done = false;
10910   }
10911   // check _LayerEdge
10912   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
10913     return;
10914   if ( eos.SWOLType() != TopAbs_EDGE )
10915     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10916   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10917     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10918
10919   // store _LayerEdge
10920   _geomEdge = TopoDS::Edge( eos._sWOL );
10921   double f,l;
10922   BRep_Tool::Range( _geomEdge, f,l );
10923   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10924   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10925
10926   // Update _nodes
10927
10928   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10929   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10930
10931   if ( _nodes.empty() )
10932   {
10933     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10934     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10935       return;
10936     TopLoc_Location loc;
10937     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10938     GeomAdaptor_Curve aCurve(C, f,l);
10939     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10940
10941     int nbExpectNodes = eSubMesh->NbNodes();
10942     _initU  .reserve( nbExpectNodes );
10943     _normPar.reserve( nbExpectNodes );
10944     _nodes  .reserve( nbExpectNodes );
10945     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10946     while ( nIt->more() )
10947     {
10948       const SMDS_MeshNode* node = nIt->next();
10949
10950       // skip refinement nodes
10951       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10952            node == tgtNode0 || node == tgtNode1 )
10953         continue;
10954       bool hasMarkedFace = false;
10955       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
10956       while ( fIt->more() && !hasMarkedFace )
10957         hasMarkedFace = fIt->next()->isMarked();
10958       if ( !hasMarkedFace )
10959         continue;
10960
10961       _nodes.push_back( node );
10962       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10963       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10964       _normPar.push_back(  len / totLen );
10965     }
10966   }
10967   else
10968   {
10969     // remove target node of the _LayerEdge from _nodes
10970     size_t nbFound = 0;
10971     for ( size_t i = 0; i < _nodes.size(); ++i )
10972       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10973         _nodes[i] = 0, nbFound++;
10974     if ( nbFound == _nodes.size() )
10975       _nodes.clear();
10976   }
10977 }
10978
10979 //================================================================================
10980 /*!
10981  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10982  */
10983 //================================================================================
10984
10985 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10986 {
10987   if ( _done || _nodes.empty())
10988     return;
10989   const _LayerEdge* e = _edges[0];
10990   if ( !e ) e = _edges[1];
10991   if ( !e ) return;
10992
10993   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
10994             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
10995
10996   double f,l;
10997   if ( set3D || _done )
10998   {
10999     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
11000     GeomAdaptor_Curve aCurve(C, f,l);
11001
11002     if ( _edges[0] )
11003       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11004     if ( _edges[1] )
11005       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11006     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
11007
11008     for ( size_t i = 0; i < _nodes.size(); ++i )
11009     {
11010       if ( !_nodes[i] ) continue;
11011       double len = totLen * _normPar[i];
11012       GCPnts_AbscissaPoint discret( aCurve, len, f );
11013       if ( !discret.IsDone() )
11014         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
11015       double u = discret.Parameter();
11016       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11017       pos->SetUParameter( u );
11018       gp_Pnt p = C->Value( u );
11019       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
11020     }
11021   }
11022   else
11023   {
11024     BRep_Tool::Range( _geomEdge, f,l );
11025     if ( _edges[0] )
11026       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
11027     if ( _edges[1] )
11028       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
11029     
11030     for ( size_t i = 0; i < _nodes.size(); ++i )
11031     {
11032       if ( !_nodes[i] ) continue;
11033       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
11034       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11035       pos->SetUParameter( u );
11036     }
11037   }
11038 }
11039
11040 //================================================================================
11041 /*!
11042  * \brief Restore initial parameters of nodes on EDGE
11043  */
11044 //================================================================================
11045
11046 void _Shrinker1D::RestoreParams()
11047 {
11048   if ( _done )
11049     for ( size_t i = 0; i < _nodes.size(); ++i )
11050     {
11051       if ( !_nodes[i] ) continue;
11052       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
11053       pos->SetUParameter( _initU[i] );
11054     }
11055   _done = false;
11056 }
11057
11058 //================================================================================
11059 /*!
11060  * \brief Replace source nodes by target nodes in shrinked mesh edges
11061  */
11062 //================================================================================
11063
11064 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
11065 {
11066   const SMDS_MeshNode* nodes[3];
11067   for ( int i = 0; i < 2; ++i )
11068   {
11069     if ( !_edges[i] ) continue;
11070
11071     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
11072     if ( !eSubMesh ) return;
11073     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
11074     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
11075     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
11076     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11077     while ( eIt->more() )
11078     {
11079       const SMDS_MeshElement* e = eIt->next();
11080       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
11081           continue;
11082       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
11083       for ( int iN = 0; iN < e->NbNodes(); ++iN )
11084       {
11085         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
11086         nodes[iN] = ( n == srcNode ? tgtNode : n );
11087       }
11088       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
11089     }
11090   }
11091 }
11092
11093 //================================================================================
11094 /*!
11095  * \brief Creates 2D and 1D elements on boundaries of new prisms
11096  */
11097 //================================================================================
11098
11099 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
11100 {
11101   SMESH_MesherHelper helper( *_mesh );
11102
11103   vector< const SMDS_MeshNode* > faceNodes;
11104
11105   //for ( size_t i = 0; i < _sdVec.size(); ++i )
11106   {
11107     //_SolidData& data = _sdVec[i];
11108     TopTools_IndexedMapOfShape geomEdges;
11109     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
11110     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
11111     {
11112       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
11113       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
11114       if ( data._noShrinkShapes.count( edgeID ))
11115         continue;
11116
11117       // Get _LayerEdge's based on E
11118
11119       map< double, const SMDS_MeshNode* > u2nodes;
11120       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
11121         continue;
11122
11123       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
11124       TNode2Edge & n2eMap = data._n2eMap;
11125       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
11126       {
11127         //check if 2D elements are needed on E
11128         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
11129         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
11130         ledges.push_back( n2e->second );
11131         u2n++;
11132         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
11133           continue; // no layers on E
11134         ledges.push_back( n2eMap[ u2n->second ]);
11135
11136         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
11137         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
11138         int nbSharedPyram = 0;
11139         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
11140         while ( vIt->more() )
11141         {
11142           const SMDS_MeshElement* v = vIt->next();
11143           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
11144         }
11145         if ( nbSharedPyram > 1 )
11146           continue; // not free border of the pyramid
11147
11148         faceNodes.clear();
11149         faceNodes.push_back( ledges[0]->_nodes[0] );
11150         faceNodes.push_back( ledges[1]->_nodes[0] );
11151         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
11152         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
11153
11154         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
11155           continue; // faces already created
11156       }
11157       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
11158         ledges.push_back( n2eMap[ u2n->second ]);
11159
11160       // Find out orientation and type of face to create
11161
11162       bool reverse = false, isOnFace;
11163       TopoDS_Shape F;
11164
11165       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
11166       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
11167       {
11168         F = e2f->second.Oriented( TopAbs_FORWARD );
11169         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11170         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11171           reverse = !reverse, F.Reverse();
11172         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11173           reverse = !reverse;
11174       }
11175       else if ( !data._ignoreFaceIds.count( e2f->first ))
11176       {
11177         // find FACE with layers sharing E
11178         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
11179         if ( fIt->more() )
11180           F = *( fIt->next() );
11181       }
11182       // Find the sub-mesh to add new faces
11183       SMESHDS_SubMesh* sm = 0;
11184       if ( isOnFace )
11185         sm = getMeshDS()->MeshElements( F );
11186       else
11187         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11188       if ( !sm )
11189         return error("error in addBoundaryElements()", data._index);
11190
11191       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
11192       // faces for 3D meshing (PAL23414)
11193       SMESHDS_SubMesh* adjSM = 0;
11194       if ( isOnFace )
11195       {
11196         const TGeomID   faceID = sm->GetID();
11197         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
11198         while ( const TopoDS_Shape* solid = soIt->next() )
11199           if ( !solid->IsSame( data._solid ))
11200           {
11201             size_t iData = _solids.FindIndex( *solid ) - 1;
11202             if ( iData < _sdVec.size() &&
11203                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
11204                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
11205             {
11206               SMESH_ProxyMesh::SubMesh* proxySub =
11207                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
11208               if ( proxySub && proxySub->NbElements() > 0 )
11209                 adjSM = proxySub;
11210             }
11211           }
11212       }
11213
11214       // Make faces
11215       const int dj1 = reverse ? 0 : 1;
11216       const int dj2 = reverse ? 1 : 0;
11217       vector< const SMDS_MeshElement*> ff; // new faces row
11218       SMESHDS_Mesh* m = getMeshDS();
11219       for ( size_t j = 1; j < ledges.size(); ++j )
11220       {
11221         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11222         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11223         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
11224         if ( nn1.size() == nn2.size() )
11225         {
11226           if ( isOnFace )
11227             for ( size_t z = 1; z < nn1.size(); ++z )
11228               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11229           else
11230             for ( size_t z = 1; z < nn1.size(); ++z )
11231               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11232         }
11233         else if ( nn1.size() == 1 )
11234         {
11235           if ( isOnFace )
11236             for ( size_t z = 1; z < nn2.size(); ++z )
11237               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11238           else
11239             for ( size_t z = 1; z < nn2.size(); ++z )
11240               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11241         }
11242         else
11243         {
11244           if ( isOnFace )
11245             for ( size_t z = 1; z < nn1.size(); ++z )
11246               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11247           else
11248             for ( size_t z = 1; z < nn1.size(); ++z )
11249               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11250         }
11251
11252         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
11253         {
11254           for ( size_t z = 0; z < ff.size(); ++z )
11255             if ( ff[ z ])
11256               adjSM->AddElement( ff[ z ]);
11257           ff.clear();
11258         }
11259       }
11260
11261       // Make edges
11262       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11263       {
11264         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11265         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11266         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11267         {
11268           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11269           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
11270             continue;
11271           helper.SetSubShape( eos->_sWOL );
11272           helper.SetElementsOnShape( true );
11273           for ( size_t z = 1; z < nn.size(); ++z )
11274             helper.AddEdge( nn[z-1], nn[z] );
11275         }
11276       }
11277
11278     } // loop on EDGE's
11279   } // loop on _SolidData's
11280
11281   return true;
11282 }