Salome HOME
1a117aff222f58264a7e1d2ff30eb78281070213
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESHDS_Mesh.hxx"
34 #include "SMESH_Algo.hxx"
35 #include "SMESH_ComputeError.hxx"
36 #include "SMESH_ControlsDef.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_ProxyMesh.hxx"
44 #include "SMESH_subMesh.hxx"
45 #include "SMESH_subMeshEventListener.hxx"
46 #include "StdMeshers_FaceSide.hxx"
47 #include "StdMeshers_ViscousLayers2D.hxx"
48
49 #include <Adaptor3d_HSurface.hxx>
50 #include <BRepAdaptor_Curve.hxx>
51 #include <BRepAdaptor_Curve2d.hxx>
52 #include <BRepAdaptor_Surface.hxx>
53 //#include <BRepLProp_CLProps.hxx>
54 #include <BRepLProp_SLProps.hxx>
55 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B2d.hxx>
58 #include <Bnd_B3d.hxx>
59 #include <ElCLib.hxx>
60 #include <GCPnts_AbscissaPoint.hxx>
61 #include <GCPnts_TangentialDeflection.hxx>
62 #include <Geom2d_Circle.hxx>
63 #include <Geom2d_Line.hxx>
64 #include <Geom2d_TrimmedCurve.hxx>
65 #include <GeomAdaptor_Curve.hxx>
66 #include <GeomLib.hxx>
67 #include <Geom_Circle.hxx>
68 #include <Geom_Curve.hxx>
69 #include <Geom_Line.hxx>
70 #include <Geom_TrimmedCurve.hxx>
71 #include <Precision.hxx>
72 #include <Standard_ErrorHandler.hxx>
73 #include <Standard_Failure.hxx>
74 #include <TColStd_Array1OfReal.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_ListOfShape.hxx>
79 #include <TopTools_MapIteratorOfMapOfShape.hxx>
80 #include <TopTools_MapOfShape.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Vertex.hxx>
85 #include <gp_Ax1.hxx>
86 #include <gp_Cone.hxx>
87 #include <gp_Sphere.hxx>
88 #include <gp_Vec.hxx>
89 #include <gp_XY.hxx>
90
91 #include <cmath>
92 #include <limits>
93 #include <list>
94 #include <queue>
95 #include <string>
96
97 #ifdef _DEBUG_
98 #define __myDEBUG
99 //#define __NOT_INVALIDATE_BAD_SMOOTH
100 //#define __NODES_AT_POS
101 #endif
102
103 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
104 #define BLOCK_INFLATION // of individual _LayerEdge's
105 #define OLD_NEF_POLYGON
106
107 using namespace std;
108
109 //================================================================================
110 namespace VISCOUS_3D
111 {
112   typedef int TGeomID;
113
114   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
115
116   const double theMinSmoothCosin = 0.1;
117   const double theSmoothThickToElemSizeRatio = 0.3;
118   const double theMinSmoothTriaAngle = 30;
119   const double theMinSmoothQuadAngle = 45;
120
121   // what part of thickness is allowed till intersection
122   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
123   const double theThickToIntersection = 1.5;
124
125   bool needSmoothing( double cosin, double tgtThick, double elemSize )
126   {
127     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
128   }
129   double getSmoothingThickness( double cosin, double elemSize )
130   {
131     return theSmoothThickToElemSizeRatio * elemSize / cosin;
132   }
133
134   /*!
135    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
136    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
137    */
138   struct _MeshOfSolid : public SMESH_ProxyMesh,
139                         public SMESH_subMeshEventListenerData
140   {
141     bool                  _n2nMapComputed;
142     SMESH_ComputeErrorPtr _warning;
143
144     _MeshOfSolid( SMESH_Mesh* mesh)
145       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
146     {
147       SMESH_ProxyMesh::setMesh( *mesh );
148     }
149
150     // returns submesh for a geom face
151     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
152     {
153       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
154       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
155     }
156     void setNode2Node(const SMDS_MeshNode*                 srcNode,
157                       const SMDS_MeshNode*                 proxyNode,
158                       const SMESH_ProxyMesh::SubMesh* subMesh)
159     {
160       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
161     }
162   };
163   //--------------------------------------------------------------------------------
164   /*!
165    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
166    * It is used to clear an inferior dim sub-meshes modified by viscous layers
167    */
168   class _ShrinkShapeListener : SMESH_subMeshEventListener
169   {
170     _ShrinkShapeListener()
171       : SMESH_subMeshEventListener(/*isDeletable=*/false,
172                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
173   public:
174     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
175     virtual void ProcessEvent(const int                       event,
176                               const int                       eventType,
177                               SMESH_subMesh*                  solidSM,
178                               SMESH_subMeshEventListenerData* data,
179                               const SMESH_Hypothesis*         hyp)
180     {
181       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
182       {
183         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
184       }
185     }
186   };
187   //--------------------------------------------------------------------------------
188   /*!
189    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
190    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
191    * delete the data as soon as it has been used
192    */
193   class _ViscousListener : SMESH_subMeshEventListener
194   {
195     _ViscousListener():
196       SMESH_subMeshEventListener(/*isDeletable=*/false,
197                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
198     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
199   public:
200     virtual void ProcessEvent(const int                       event,
201                               const int                       eventType,
202                               SMESH_subMesh*                  subMesh,
203                               SMESH_subMeshEventListenerData* data,
204                               const SMESH_Hypothesis*         hyp)
205     {
206       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
207           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
208             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
209       {
210         // delete SMESH_ProxyMesh containing temporary faces
211         subMesh->DeleteEventListener( this );
212       }
213     }
214     // Finds or creates proxy mesh of the solid
215     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
216                                       const TopoDS_Shape& solid,
217                                       bool                toCreate=false)
218     {
219       if ( !mesh ) return 0;
220       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
221       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
222       if ( !data && toCreate )
223       {
224         data = new _MeshOfSolid(mesh);
225         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
226         sm->SetEventListener( Get(), data, sm );
227       }
228       return data;
229     }
230     // Removes proxy mesh of the solid
231     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
232     {
233       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
234     }
235   };
236   
237   //================================================================================
238   /*!
239    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
240    * the main shape when sub-mesh of the main shape is cleared,
241    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
242    * is cleared
243    */
244   //================================================================================
245
246   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
247   {
248     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
249     SMESH_subMeshEventListenerData* data =
250       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
251     if ( data )
252     {
253       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
254            data->mySubMeshes.end())
255         data->mySubMeshes.push_back( sub );
256     }
257     else
258     {
259       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
260       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
261     }
262   }
263   struct _SolidData;
264   //--------------------------------------------------------------------------------
265   /*!
266    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
267    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
268    * The class is used to check validity of face or volumes around a smoothed node;
269    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
270    */
271   struct _Simplex
272   {
273     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
274     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
275     _Simplex(const SMDS_MeshNode* nPrev=0,
276              const SMDS_MeshNode* nNext=0,
277              const SMDS_MeshNode* nOpp=0)
278       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
279     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
280     {
281       const double M[3][3] =
282         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
283          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
284          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
285       vol = ( + M[0][0] * M[1][1] * M[2][2]
286               + M[0][1] * M[1][2] * M[2][0]
287               + M[0][2] * M[1][0] * M[2][1]
288               - M[0][0] * M[1][2] * M[2][1]
289               - M[0][1] * M[1][0] * M[2][2]
290               - M[0][2] * M[1][1] * M[2][0]);
291       return vol > 1e-100;
292     }
293     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
294     {
295       SMESH_TNodeXYZ pSrc( nSrc );
296       return IsForward( &pSrc, &pTgt, vol );
297     }
298     bool IsForward(const gp_XY&         tgtUV,
299                    const SMDS_MeshNode* smoothedNode,
300                    const TopoDS_Face&   face,
301                    SMESH_MesherHelper&  helper,
302                    const double         refSign) const
303     {
304       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
305       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
306       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
307       double d = v1 ^ v2;
308       return d*refSign > 1e-100;
309     }
310     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
311     {
312       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
313       if ( !_nOpp ) // triangle
314       {
315         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
316         double tp2 = tp.SquareMagnitude();
317         double pn2 = pn.SquareMagnitude();
318         double nt2 = nt.SquareMagnitude();
319
320         if ( tp2 < pn2 && tp2 < nt2 )
321           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
322         else if ( pn2 < nt2 )
323           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
324         else
325           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
326
327         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
328                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
329         return minAngle < theMaxCos2;
330       }
331       else // quadrangle
332       {
333         SMESH_TNodeXYZ pOpp( _nOpp );
334         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
335         double tp2 = tp.SquareMagnitude();
336         double po2 = po.SquareMagnitude();
337         double on2 = on.SquareMagnitude();
338         double nt2 = nt.SquareMagnitude();
339         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
340                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
341                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
342                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
343
344         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
345                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
346         return minAngle < theMaxCos2;
347       }
348     }
349     bool IsNeighbour(const _Simplex& other) const
350     {
351       return _nPrev == other._nNext || _nNext == other._nPrev;
352     }
353     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
354     static void GetSimplices( const SMDS_MeshNode* node,
355                               vector<_Simplex>&   simplices,
356                               const set<TGeomID>& ingnoreShapes,
357                               const _SolidData*   dataToCheckOri = 0,
358                               const bool          toSort = false);
359     static void SortSimplices(vector<_Simplex>& simplices);
360   };
361   //--------------------------------------------------------------------------------
362   /*!
363    * Structure used to take into account surface curvature while smoothing
364    */
365   struct _Curvature
366   {
367     double   _r; // radius
368     double   _k; // factor to correct node smoothed position
369     double   _h2lenRatio; // avgNormProj / (2*avgDist)
370     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
371   public:
372     static _Curvature* New( double avgNormProj, double avgDist )
373     {
374       _Curvature* c = 0;
375       if ( fabs( avgNormProj / avgDist ) > 1./200 )
376       {
377         c = new _Curvature;
378         c->_r = avgDist * avgDist / avgNormProj;
379         c->_k = avgDist * avgDist / c->_r / c->_r;
380         //c->_k = avgNormProj / c->_r;
381         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
382         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
383
384         c->_uv.SetCoord( 0., 0. );
385       }
386       return c;
387     }
388     double lenDelta(double len) const { return _k * ( _r + len ); }
389     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
390   };
391   //--------------------------------------------------------------------------------
392
393   struct _2NearEdges;
394   struct _LayerEdge;
395   struct _EdgesOnShape;
396   struct _Smoother1D;
397   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
398
399   //--------------------------------------------------------------------------------
400   /*!
401    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
402    * and a node of the most internal layer (_nodes.back())
403    */
404   struct _LayerEdge
405   {
406     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
407
408     vector< const SMDS_MeshNode*> _nodes;
409
410     gp_XYZ              _normal;    // to boundary of solid
411     vector<gp_XYZ>      _pos;       // points computed during inflation
412     double              _len;       // length achived with the last inflation step
413     double              _maxLen;    // maximal possible length
414     double              _cosin;     // of angle (_normal ^ surface)
415     double              _minAngle;  // of _simplices
416     double              _lenFactor; // to compute _len taking _cosin into account
417     int                 _flags;
418
419     // simplices connected to the source node (_nodes[0]);
420     // used for smoothing and quality check of _LayerEdge's based on the FACE
421     vector<_Simplex>    _simplices;
422     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
423     PSmooFun            _smooFunction; // smoothing function
424     _Curvature*         _curvature;
425     // data for smoothing of _LayerEdge's based on the EDGE
426     _2NearEdges*        _2neibors;
427
428     enum EFlags { TO_SMOOTH       = 0x0000001,
429                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
430                   SMOOTHED        = 0x0000004, // set by this->Smooth()
431                   DIFFICULT       = 0x0000008, // near concave VERTEX
432                   ON_CONCAVE_FACE = 0x0000010,
433                   BLOCKED         = 0x0000020, // not to inflate any more
434                   INTERSECTED     = 0x0000040, // close intersection with a face found
435                   NORMAL_UPDATED  = 0x0000080,
436                   MARKED          = 0x0000100, // local usage
437                   MULTI_NORMAL    = 0x0000200, // a normal is invisible by some of surrounding faces
438                   NEAR_BOUNDARY   = 0x0000400, // is near FACE boundary forcing smooth
439                   SMOOTHED_C1     = 0x0000800, // is on _eosC1
440                   DISTORTED       = 0x0001000, // was bad before smoothing
441                   RISKY_SWOL      = 0x0002000, // SWOL is parallel to a source FACE
442                   UNUSED_FLAG     = 0x0100000
443     };
444     bool Is   ( int flag ) const { return _flags & flag; }
445     void Set  ( int flag ) { _flags |= flag; }
446     void Unset( int flag ) { _flags &= ~flag; }
447
448     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
449     bool SetNewLength2d( Handle(Geom_Surface)& surface,
450                          const TopoDS_Face&    F,
451                          _EdgesOnShape&        eos,
452                          SMESH_MesherHelper&   helper );
453     void SetDataByNeighbors( const SMDS_MeshNode* n1,
454                              const SMDS_MeshNode* n2,
455                              const _EdgesOnShape& eos,
456                              SMESH_MesherHelper&  helper);
457     void Block( _SolidData& data );
458     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
459     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
460                             const TNode2Edge&     n2eMap);
461     void SmoothPos( const vector< double >& segLen, const double tol );
462     int  GetSmoothedPos( const double tol );
463     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
464     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
465     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
466     void SmoothWoCheck();
467     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
468                       const TopoDS_Face&             F,
469                       SMESH_MesherHelper&            helper);
470     void MoveNearConcaVer( const _EdgesOnShape*    eov,
471                            const _EdgesOnShape*    eos,
472                            const int               step,
473                            vector< _LayerEdge* > & badSmooEdges);
474     bool FindIntersection( SMESH_ElementSearcher&   searcher,
475                            double &                 distance,
476                            const double&            epsilon,
477                            _EdgesOnShape&           eos,
478                            const SMDS_MeshElement** face = 0);
479     bool SegTriaInter( const gp_Ax1&        lastSegment,
480                        const gp_XYZ&        p0,
481                        const gp_XYZ&        p1,
482                        const gp_XYZ&        p2,
483                        double&              dist,
484                        const double&        epsilon) const;
485     bool SegTriaInter( const gp_Ax1&        lastSegment,
486                        const SMDS_MeshNode* n0,
487                        const SMDS_MeshNode* n1,
488                        const SMDS_MeshNode* n2,
489                        double&              dist,
490                        const double&        epsilon) const
491     { return SegTriaInter( lastSegment,
492                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
493                            dist, epsilon );
494     }
495     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
496     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
497     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
498     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const;
499     bool   IsOnEdge() const { return _2neibors; }
500     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
501     void   SetCosin( double cosin );
502     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
503     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
504     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
505     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
506       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
507     }
508     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
509
510     gp_XYZ smoothLaplacian();
511     gp_XYZ smoothAngular();
512     gp_XYZ smoothLengthWeighted();
513     gp_XYZ smoothCentroidal();
514     gp_XYZ smoothNefPolygon();
515
516     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
517     static const int theNbSmooFuns = FUN_NB;
518     static PSmooFun _funs[theNbSmooFuns];
519     static const char* _funNames[theNbSmooFuns+1];
520     int smooFunID( PSmooFun fun=0) const;
521   };
522   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
523                                                             &_LayerEdge::smoothLengthWeighted,
524                                                             &_LayerEdge::smoothCentroidal,
525                                                             &_LayerEdge::smoothNefPolygon,
526                                                             &_LayerEdge::smoothAngular };
527   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
528                                                          "LengthWeighted",
529                                                          "Centroidal",
530                                                          "NefPolygon",
531                                                          "Angular",
532                                                          "None"};
533   struct _LayerEdgeCmp
534   {
535     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
536     {
537       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
538       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
539     }
540   };
541   //--------------------------------------------------------------------------------
542   /*!
543    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
544    */
545   struct _halfPlane
546   {
547     gp_XY _pos, _dir, _inNorm;
548     bool IsOut( const gp_XY p, const double tol ) const
549     {
550       return _inNorm * ( p - _pos ) < -tol;
551     }
552     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
553     {
554       //const double eps = 1e-10;
555       double D = _dir.Crossed( hp._dir );
556       if ( fabs(D) < std::numeric_limits<double>::min())
557         return false;
558       gp_XY vec21 = _pos - hp._pos; 
559       double u = hp._dir.Crossed( vec21 ) / D; 
560       intPnt = _pos + _dir * u;
561       return true;
562     }
563   };
564   //--------------------------------------------------------------------------------
565   /*!
566    * Structure used to smooth a _LayerEdge based on an EDGE.
567    */
568   struct _2NearEdges
569   {
570     double               _wgt  [2]; // weights of _nodes
571     _LayerEdge*          _edges[2];
572
573      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
574     gp_XYZ*              _plnNorm;
575
576     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
577     const SMDS_MeshNode* tgtNode(bool is2nd) {
578       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
579     }
580     const SMDS_MeshNode* srcNode(bool is2nd) {
581       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
582     }
583     void reverse() {
584       std::swap( _wgt  [0], _wgt  [1] );
585       std::swap( _edges[0], _edges[1] );
586     }
587     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
588       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
589     }
590     bool include( const _LayerEdge* e ) {
591       return ( _edges[0] == e || _edges[1] == e );
592     }
593   };
594
595
596   //--------------------------------------------------------------------------------
597   /*!
598    * \brief Layers parameters got by averaging several hypotheses
599    */
600   struct AverageHyp
601   {
602     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
603       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
604     {
605       Add( hyp );
606     }
607     void Add( const StdMeshers_ViscousLayers* hyp )
608     {
609       if ( hyp )
610       {
611         _nbHyps++;
612         _nbLayers       = hyp->GetNumberLayers();
613         //_thickness     += hyp->GetTotalThickness();
614         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
615         _stretchFactor += hyp->GetStretchFactor();
616         _method         = hyp->GetMethod();
617       }
618     }
619     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
620     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
621     int    GetNumberLayers()   const { return _nbLayers; }
622     int    GetMethod()         const { return _method; }
623
624     bool   UseSurfaceNormal()  const
625     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
626     bool   ToSmooth()          const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   IsOffsetMethod()    const
629     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
630
631   private:
632     int     _nbLayers, _nbHyps, _method;
633     double  _thickness, _stretchFactor;
634   };
635
636   //--------------------------------------------------------------------------------
637   /*!
638    * \brief _LayerEdge's on a shape and other shape data
639    */
640   struct _EdgesOnShape
641   {
642     vector< _LayerEdge* > _edges;
643
644     TopoDS_Shape          _shape;
645     TGeomID               _shapeID;
646     SMESH_subMesh *       _subMesh;
647     // face or edge w/o layer along or near which _edges are inflated
648     TopoDS_Shape          _sWOL;
649     bool                  _isRegularSWOL; // w/o singularities
650     // averaged StdMeshers_ViscousLayers parameters
651     AverageHyp            _hyp;
652     bool                  _toSmooth;
653     _Smoother1D*          _edgeSmoother;
654     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
655     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
656
657     vector< gp_XYZ >         _faceNormals; // if _shape is FACE
658     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
659
660     Handle(ShapeAnalysis_Surface) _offsetSurf;
661     _LayerEdge*                   _edgeForOffset;
662
663     _SolidData*            _data; // parent SOLID
664
665     TopAbs_ShapeEnum ShapeType() const
666     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
667     TopAbs_ShapeEnum SWOLType() const
668     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
669     bool             HasC1( const _EdgesOnShape* other ) const
670     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
671     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
672     _SolidData&      GetData() const { return *_data; }
673
674     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
675   };
676
677   //--------------------------------------------------------------------------------
678   /*!
679    * \brief Convex FACE whose radius of curvature is less than the thickness of 
680    *        layers. It is used to detect distortion of prisms based on a convex
681    *        FACE and to update normals to enable further increasing the thickness
682    */
683   struct _ConvexFace
684   {
685     TopoDS_Face                     _face;
686
687     // edges whose _simplices are used to detect prism distortion
688     vector< _LayerEdge* >           _simplexTestEdges;
689
690     // map a sub-shape to _SolidData::_edgesOnShape
691     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
692
693     bool                            _normalsFixed;
694
695     bool GetCenterOfCurvature( _LayerEdge*         ledge,
696                                BRepLProp_SLProps&  surfProp,
697                                SMESH_MesherHelper& helper,
698                                gp_Pnt &            center ) const;
699     bool CheckPrisms() const;
700   };
701
702   //--------------------------------------------------------------------------------
703   /*!
704    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
705    *        at inflation up to the full thickness. A detected collision
706    *        is fixed in updateNormals()
707    */
708   struct _CollisionEdges
709   {
710     _LayerEdge*           _edge;
711     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
712     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
713     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
714   };
715
716   //--------------------------------------------------------------------------------
717   /*!
718    * \brief Data of a SOLID
719    */
720   struct _SolidData
721   {
722     typedef const StdMeshers_ViscousLayers* THyp;
723     TopoDS_Shape                    _solid;
724     TGeomID                         _index; // SOLID id
725     _MeshOfSolid*                   _proxyMesh;
726     list< THyp >                    _hyps;
727     list< TopoDS_Shape >            _hypShapes;
728     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
729     set< TGeomID >                  _reversedFaceIds;
730     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
731
732     double                          _stepSize, _stepSizeCoeff, _geomSize;
733     const SMDS_MeshNode*            _stepSizeNodes[2];
734
735     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
736
737     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
738     map< TGeomID, TNode2Edge* >     _s2neMap;
739     // _LayerEdge's with underlying shapes
740     vector< _EdgesOnShape >         _edgesOnShape;
741
742     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
743     //        layers and a FACE w/o layers
744     // value: the shape (FACE or EDGE) to shrink mesh on.
745     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
746     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
747
748     // Convex FACEs whose radius of curvature is less than the thickness of layers
749     map< TGeomID, _ConvexFace >      _convexFaces;
750
751     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
752     // the adjacent SOLID
753     set< TGeomID >                   _noShrinkShapes;
754
755     int                              _nbShapesToSmooth;
756
757     //map< TGeomID,Handle(Geom_Curve)> _edge2curve;
758
759     vector< _CollisionEdges >        _collisionEdges;
760     set< TGeomID >                   _concaveFaces;
761
762     double                           _maxThickness; // of all _hyps
763     double                           _minThickness; // of all _hyps
764
765     double                           _epsilon; // precision for SegTriaInter()
766
767     SMESH_MesherHelper*              _helper;
768
769     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
770                _MeshOfSolid*       m=0)
771       :_solid(s), _proxyMesh(m), _helper(0) {}
772     ~_SolidData();
773
774     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
775     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
776
777     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
778       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
779       return id2face == _convexFaces.end() ? 0 : & id2face->second;
780     }
781     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
782     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
783     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
784     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
785
786     SMESH_MesherHelper& GetHelper() const { return *_helper; }
787
788     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
789       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
790         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
791           _edgesOnShape[i]._edges[j]->Unset( flag );
792     }
793     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
794                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
795
796     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
797   };
798   //--------------------------------------------------------------------------------
799   /*!
800    * \brief Offset plane used in getNormalByOffset()
801    */
802   struct _OffsetPlane
803   {
804     gp_Pln _plane;
805     int    _faceIndex;
806     int    _faceIndexNext[2];
807     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
808     bool   _isLineOK[2];
809     _OffsetPlane() {
810       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
811     }
812     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
813                                     const TopoDS_Edge&   E,
814                                     const TopoDS_Vertex& V );
815     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
816     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
817   };
818   //--------------------------------------------------------------------------------
819   /*!
820    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
821    */
822   struct _CentralCurveOnEdge
823   {
824     bool                  _isDegenerated;
825     vector< gp_Pnt >      _curvaCenters;
826     vector< _LayerEdge* > _ledges;
827     vector< gp_XYZ >      _normals; // new normal for each of _ledges
828     vector< double >      _segLength2;
829
830     TopoDS_Edge           _edge;
831     TopoDS_Face           _adjFace;
832     bool                  _adjFaceToSmooth;
833
834     void Append( const gp_Pnt& center, _LayerEdge* ledge )
835     {
836       if ( _curvaCenters.size() > 0 )
837         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
838       _curvaCenters.push_back( center );
839       _ledges.push_back( ledge );
840       _normals.push_back( ledge->_normal );
841     }
842     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
843     void SetShapes( const TopoDS_Edge&  edge,
844                     const _ConvexFace&  convFace,
845                     _SolidData&         data,
846                     SMESH_MesherHelper& helper);
847   };
848   //--------------------------------------------------------------------------------
849   /*!
850    * \brief Data of node on a shrinked FACE
851    */
852   struct _SmoothNode
853   {
854     const SMDS_MeshNode*         _node;
855     vector<_Simplex>             _simplices; // for quality check
856
857     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
858
859     bool Smooth(int&                  badNb,
860                 Handle(Geom_Surface)& surface,
861                 SMESH_MesherHelper&   helper,
862                 const double          refSign,
863                 SmoothType            how,
864                 bool                  set3D);
865
866     gp_XY computeAngularPos(vector<gp_XY>& uv,
867                             const gp_XY&   uvToFix,
868                             const double   refSign );
869   };
870   //--------------------------------------------------------------------------------
871   /*!
872    * \brief Builder of viscous layers
873    */
874   class _ViscousBuilder
875   {
876   public:
877     _ViscousBuilder();
878     // does it's job
879     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
880                                   const TopoDS_Shape& shape);
881     // check validity of hypotheses
882     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
883                                            const TopoDS_Shape& shape );
884
885     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
886     void RestoreListeners();
887
888     // computes SMESH_ProxyMesh::SubMesh::_n2n;
889     bool MakeN2NMap( _MeshOfSolid* pm );
890
891   private:
892
893     bool findSolidsWithLayers();
894     bool findFacesWithLayers(const bool onlyWith=false);
895     void getIgnoreFaces(const TopoDS_Shape&             solid,
896                         const StdMeshers_ViscousLayers* hyp,
897                         const TopoDS_Shape&             hypShape,
898                         set<TGeomID>&                   ignoreFaces);
899     bool makeLayer(_SolidData& data);
900     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
901     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
902                       SMESH_MesherHelper& helper, _SolidData& data);
903     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
904                          const TopoDS_Face&   face,
905                          SMESH_MesherHelper&  helper,
906                          bool&                isOK,
907                          bool                 shiftInside=false);
908     bool getFaceNormalAtSingularity(const gp_XY&        uv,
909                                     const TopoDS_Face&  face,
910                                     SMESH_MesherHelper& helper,
911                                     gp_Dir&             normal );
912     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
913     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
914                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
915                               int                              nbFaces,
916                               bool                             lastNoOffset = false);
917     bool findNeiborsOnEdge(const _LayerEdge*     edge,
918                            const SMDS_MeshNode*& n1,
919                            const SMDS_MeshNode*& n2,
920                            _EdgesOnShape&        eos,
921                            _SolidData&           data);
922     void findSimplexTestEdges( _SolidData&                    data,
923                                vector< vector<_LayerEdge*> >& edgesByGeom);
924     void computeGeomSize( _SolidData& data );
925     bool findShapesToSmooth( _SolidData& data);
926     void limitStepSizeByCurvature( _SolidData&  data );
927     void limitStepSize( _SolidData&             data,
928                         const SMDS_MeshElement* face,
929                         const _LayerEdge*       maxCosinEdge );
930     void limitStepSize( _SolidData& data, const double minSize);
931     bool inflate(_SolidData& data);
932     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
933     int  invalidateBadSmooth( _SolidData&               data,
934                               SMESH_MesherHelper&       helper,
935                               vector< _LayerEdge* >&    badSmooEdges,
936                               vector< _EdgesOnShape* >& eosC1,
937                               const int                 infStep );
938     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
939     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
940                              vector< _EdgesOnShape* >& eosC1,
941                              int smooStep=0, bool moveAll=false );
942     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
943     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
944     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
945                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
946                                  SMESH_MesherHelper& helper );
947     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
948     bool updateNormalsOfConvexFaces( _SolidData&         data,
949                                      SMESH_MesherHelper& helper,
950                                      int                 stepNb );
951     void updateNormalsOfC1Vertices( _SolidData& data );
952     bool updateNormalsOfSmoothed( _SolidData&         data,
953                                   SMESH_MesherHelper& helper,
954                                   const int           nbSteps,
955                                   const double        stepSize );
956     bool isNewNormalOk( _SolidData&   data,
957                         _LayerEdge&   edge,
958                         const gp_XYZ& newNormal);
959     bool refine(_SolidData& data);
960     bool shrink();
961     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
962                               SMESH_MesherHelper& helper,
963                               const SMESHDS_SubMesh* faceSubMesh );
964     void restoreNoShrink( _LayerEdge& edge ) const;
965     void fixBadFaces(const TopoDS_Face&          F,
966                      SMESH_MesherHelper&         helper,
967                      const bool                  is2D,
968                      const int                   step,
969                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
970     bool addBoundaryElements();
971
972     bool error( const string& text, int solidID=-1 );
973     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
974
975     // debug
976     void makeGroupOfLE();
977
978     SMESH_Mesh*           _mesh;
979     SMESH_ComputeErrorPtr _error;
980
981     vector< _SolidData >  _sdVec;
982     int                   _tmpFaceID;
983   };
984   //--------------------------------------------------------------------------------
985   /*!
986    * \brief Shrinker of nodes on the EDGE
987    */
988   class _Shrinker1D
989   {
990     TopoDS_Edge                   _geomEdge;
991     vector<double>                _initU;
992     vector<double>                _normPar;
993     vector<const SMDS_MeshNode*>  _nodes;
994     const _LayerEdge*             _edges[2];
995     bool                          _done;
996   public:
997     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
998     void Compute(bool set3D, SMESH_MesherHelper& helper);
999     void RestoreParams();
1000     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1001     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1002     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1003     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1004     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1005     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1006   };
1007   //--------------------------------------------------------------------------------
1008   /*!
1009    * \brief Smoother of _LayerEdge's on EDGE.
1010    */
1011   struct _Smoother1D
1012   {
1013     struct OffPnt // point of the offsetted EDGE
1014     {
1015       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1016       double      _len;    // length reached at previous inflation step
1017       double      _param;  // on EDGE
1018       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1019       gp_XYZ      _edgeDir;// EDGE tangent at _param
1020       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1021     };
1022     vector< OffPnt >   _offPoints;
1023     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1024     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1025     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1026     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1027     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1028     _EdgesOnShape&     _eos;
1029     double             _curveLen; // length of the EDGE
1030
1031     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1032                                               _EdgesOnShape&      eos,
1033                                               SMESH_MesherHelper& helper);
1034
1035     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1036                  _EdgesOnShape&     eos )
1037       : _anaCurve( curveForSmooth ), _eos( eos )
1038     {
1039     }
1040     bool Perform(_SolidData&                    data,
1041                  Handle(ShapeAnalysis_Surface)& surface,
1042                  const TopoDS_Face&             F,
1043                  SMESH_MesherHelper&            helper )
1044     {
1045       if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
1046         prepare( data );
1047
1048       if ( isAnalytic() )
1049         return smoothAnalyticEdge( data, surface, F, helper );
1050       else
1051         return smoothComplexEdge ( data, surface, F, helper );
1052     }
1053     void prepare(_SolidData& data );
1054
1055     bool smoothAnalyticEdge( _SolidData&                    data,
1056                              Handle(ShapeAnalysis_Surface)& surface,
1057                              const TopoDS_Face&             F,
1058                              SMESH_MesherHelper&            helper);
1059
1060     bool smoothComplexEdge( _SolidData&                    data,
1061                             Handle(ShapeAnalysis_Surface)& surface,
1062                             const TopoDS_Face&             F,
1063                             SMESH_MesherHelper&            helper);
1064
1065     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1066                             const gp_XYZ&  edgeDir);
1067
1068     _LayerEdge* getLEdgeOnV( bool is2nd )
1069     {
1070       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1071     }
1072     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1073   };
1074   //--------------------------------------------------------------------------------
1075   /*!
1076    * \brief Class of temporary mesh face.
1077    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1078    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
1079    */
1080   struct _TmpMeshFace : public SMDS_MeshElement
1081   {
1082     vector<const SMDS_MeshNode* > _nn;
1083     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1084                   int id, int faceID=-1, int idInFace=-1):
1085       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); setIdInShape(idInFace); }
1086     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
1087     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
1088     virtual vtkIdType GetVtkType() const                      { return -1; }
1089     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
1090     virtual SMDSAbs_GeometryType GetGeomType() const
1091     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
1092     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
1093     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
1094   };
1095   //--------------------------------------------------------------------------------
1096   /*!
1097    * \brief Class of temporary mesh face storing _LayerEdge it's based on
1098    */
1099   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1100   {
1101     _LayerEdge *_le1, *_le2;
1102     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1103       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1104     {
1105       _nn[0]=_le1->_nodes[0];
1106       _nn[1]=_le1->_nodes.back();
1107       _nn[2]=_le2->_nodes.back();
1108       _nn[3]=_le2->_nodes[0];
1109     }
1110     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1111     {
1112       SMESH_TNodeXYZ p0s( _nn[0] );
1113       SMESH_TNodeXYZ p0t( _nn[1] );
1114       SMESH_TNodeXYZ p1t( _nn[2] );
1115       SMESH_TNodeXYZ p1s( _nn[3] );
1116       gp_XYZ  v0 = p0t - p0s;
1117       gp_XYZ  v1 = p1t - p1s;
1118       gp_XYZ v01 = p1s - p0s;
1119       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1120       gp_XYZ   d = v01 ^ n;
1121       d.Normalize();
1122       return d;
1123     }
1124     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1125     {
1126       _nn[0]=le1->_nodes[0];
1127       _nn[1]=le1->_nodes.back();
1128       _nn[2]=le2->_nodes.back();
1129       _nn[3]=le2->_nodes[0];
1130       return GetDir();
1131     }
1132   };
1133   //--------------------------------------------------------------------------------
1134   /*!
1135    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1136    * \warning Location of a surface is ignored
1137    */
1138   struct _NodeCoordHelper
1139   {
1140     SMESH_MesherHelper&        _helper;
1141     const TopoDS_Face&         _face;
1142     Handle(Geom_Surface)       _surface;
1143     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1144
1145     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1146       : _helper( helper ), _face( F )
1147     {
1148       if ( is2D )
1149       {
1150         TopLoc_Location loc;
1151         _surface = BRep_Tool::Surface( _face, loc );
1152       }
1153       if ( _surface.IsNull() )
1154         _fun = & _NodeCoordHelper::direct;
1155       else
1156         _fun = & _NodeCoordHelper::byUV;
1157     }
1158     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1159
1160   private:
1161     gp_XYZ direct(const SMDS_MeshNode* n) const
1162     {
1163       return SMESH_TNodeXYZ( n );
1164     }
1165     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1166     {
1167       gp_XY uv = _helper.GetNodeUV( _face, n );
1168       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1169     }
1170   };
1171
1172   //================================================================================
1173   /*!
1174    * \brief Check angle between vectors 
1175    */
1176   //================================================================================
1177
1178   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1179   {
1180     double dot = v1 * v2; // cos * |v1| * |v2|
1181     double l1  = v1.SquareMagnitude();
1182     double l2  = v2.SquareMagnitude();
1183     return (( dot * cos >= 0 ) && 
1184             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1185   }
1186
1187 } // namespace VISCOUS_3D
1188
1189
1190
1191 //================================================================================
1192 // StdMeshers_ViscousLayers hypothesis
1193 //
1194 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
1195   :SMESH_Hypothesis(hypId, studyId, gen),
1196    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1197    _method( SURF_OFFSET_SMOOTH )
1198 {
1199   _name = StdMeshers_ViscousLayers::GetHypType();
1200   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1201 } // --------------------------------------------------------------------------------
1202 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1203 {
1204   if ( faceIds != _shapeIds )
1205     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1206   if ( _isToIgnoreShapes != toIgnore )
1207     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1208 } // --------------------------------------------------------------------------------
1209 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1210 {
1211   if ( thickness != _thickness )
1212     _thickness = thickness, NotifySubMeshesHypothesisModification();
1213 } // --------------------------------------------------------------------------------
1214 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1215 {
1216   if ( _nbLayers != nb )
1217     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1218 } // --------------------------------------------------------------------------------
1219 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1220 {
1221   if ( _stretchFactor != factor )
1222     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1223 } // --------------------------------------------------------------------------------
1224 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1225 {
1226   if ( _method != method )
1227     _method = method, NotifySubMeshesHypothesisModification();
1228 } // --------------------------------------------------------------------------------
1229 SMESH_ProxyMesh::Ptr
1230 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1231                                   const TopoDS_Shape& theShape,
1232                                   const bool          toMakeN2NMap) const
1233 {
1234   using namespace VISCOUS_3D;
1235   _ViscousBuilder bulder;
1236   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
1237   if ( err && !err->IsOK() )
1238     return SMESH_ProxyMesh::Ptr();
1239
1240   vector<SMESH_ProxyMesh::Ptr> components;
1241   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1242   for ( ; exp.More(); exp.Next() )
1243   {
1244     if ( _MeshOfSolid* pm =
1245          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1246     {
1247       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1248         if ( !bulder.MakeN2NMap( pm ))
1249           return SMESH_ProxyMesh::Ptr();
1250       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1251       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1252
1253       if ( pm->_warning && !pm->_warning->IsOK() )
1254       {
1255         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1256         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1257         if ( !smError || smError->IsOK() )
1258           smError = pm->_warning;
1259       }
1260     }
1261     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1262   }
1263   switch ( components.size() )
1264   {
1265   case 0: break;
1266
1267   case 1: return components[0];
1268
1269   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1270   }
1271   return SMESH_ProxyMesh::Ptr();
1272 } // --------------------------------------------------------------------------------
1273 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1274 {
1275   save << " " << _nbLayers
1276        << " " << _thickness
1277        << " " << _stretchFactor
1278        << " " << _shapeIds.size();
1279   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1280     save << " " << _shapeIds[i];
1281   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1282   save << " " << _method;
1283   return save;
1284 } // --------------------------------------------------------------------------------
1285 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1286 {
1287   int nbFaces, faceID, shapeToTreat, method;
1288   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1289   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1290     _shapeIds.push_back( faceID );
1291   if ( load >> shapeToTreat ) {
1292     _isToIgnoreShapes = !shapeToTreat;
1293     if ( load >> method )
1294       _method = (ExtrusionMethod) method;
1295   }
1296   else {
1297     _isToIgnoreShapes = true; // old behavior
1298   }
1299   return load;
1300 } // --------------------------------------------------------------------------------
1301 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
1302                                                    const TopoDS_Shape& theShape)
1303 {
1304   // TODO
1305   return false;
1306 } // --------------------------------------------------------------------------------
1307 SMESH_ComputeErrorPtr
1308 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1309                                           const TopoDS_Shape&                  theShape,
1310                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1311 {
1312   VISCOUS_3D::_ViscousBuilder bulder;
1313   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
1314   if ( err && !err->IsOK() )
1315     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1316   else
1317     theStatus = SMESH_Hypothesis::HYP_OK;
1318
1319   return err;
1320 }
1321 // --------------------------------------------------------------------------------
1322 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1323 {
1324   bool isIn =
1325     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1326   return IsToIgnoreShapes() ? !isIn : isIn;
1327 }
1328 // END StdMeshers_ViscousLayers hypothesis
1329 //================================================================================
1330
1331 namespace VISCOUS_3D
1332 {
1333   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1334   {
1335     gp_Vec dir;
1336     double f,l;
1337     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1338     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1339     gp_Pnt p = BRep_Tool::Pnt( fromV );
1340     double distF = p.SquareDistance( c->Value( f ));
1341     double distL = p.SquareDistance( c->Value( l ));
1342     c->D1(( distF < distL ? f : l), p, dir );
1343     if ( distL < distF ) dir.Reverse();
1344     return dir.XYZ();
1345   }
1346   //--------------------------------------------------------------------------------
1347   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1348                      SMESH_MesherHelper& helper)
1349   {
1350     gp_Vec dir;
1351     double f,l; gp_Pnt p;
1352     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1353     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1354     double u = helper.GetNodeU( E, atNode );
1355     c->D1( u, p, dir );
1356     return dir.XYZ();
1357   }
1358   //--------------------------------------------------------------------------------
1359   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1360                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1361                      double* cosin=0);
1362   //--------------------------------------------------------------------------------
1363   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1364                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1365   {
1366     double f,l;
1367     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1368     if ( c.IsNull() )
1369     {
1370       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1371       return getFaceDir( F, v, node, helper, ok );
1372     }
1373     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1374     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1375     gp_Pnt p; gp_Vec du, dv, norm;
1376     surface->D1( uv.X(),uv.Y(), p, du,dv );
1377     norm = du ^ dv;
1378
1379     double u = helper.GetNodeU( fromE, node, 0, &ok );
1380     c->D1( u, p, du );
1381     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1382     if ( o == TopAbs_REVERSED )
1383       du.Reverse();
1384
1385     gp_Vec dir = norm ^ du;
1386
1387     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1388          helper.IsClosedEdge( fromE ))
1389     {
1390       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1391       else                        c->D1( f, p, dv );
1392       if ( o == TopAbs_REVERSED )
1393         dv.Reverse();
1394       gp_Vec dir2 = norm ^ dv;
1395       dir = dir.Normalized() + dir2.Normalized();
1396     }
1397     return dir.XYZ();
1398   }
1399   //--------------------------------------------------------------------------------
1400   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1401                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1402                      bool& ok, double* cosin)
1403   {
1404     TopoDS_Face faceFrw = F;
1405     faceFrw.Orientation( TopAbs_FORWARD );
1406     //double f,l; TopLoc_Location loc;
1407     TopoDS_Edge edges[2]; // sharing a vertex
1408     size_t nbEdges = 0;
1409     {
1410       TopoDS_Vertex VV[2];
1411       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1412       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1413       {
1414         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1415         if ( SMESH_Algo::isDegenerated( e )) continue;
1416         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1417         if ( VV[1].IsSame( fromV )) {
1418           nbEdges += edges[ 0 ].IsNull();
1419           edges[ 0 ] = e;
1420         }
1421         else if ( VV[0].IsSame( fromV )) {
1422           nbEdges += edges[ 1 ].IsNull();
1423           edges[ 1 ] = e;
1424         }
1425       }
1426     }
1427     gp_XYZ dir(0,0,0), edgeDir[2];
1428     if ( nbEdges == 2 )
1429     {
1430       // get dirs of edges going fromV
1431       ok = true;
1432       for ( size_t i = 0; i < nbEdges && ok; ++i )
1433       {
1434         edgeDir[i] = getEdgeDir( edges[i], fromV );
1435         double size2 = edgeDir[i].SquareModulus();
1436         if (( ok = size2 > numeric_limits<double>::min() ))
1437           edgeDir[i] /= sqrt( size2 );
1438       }
1439       if ( !ok ) return dir;
1440
1441       // get angle between the 2 edges
1442       gp_Vec faceNormal;
1443       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1444       if ( Abs( angle ) < 5 * M_PI/180 )
1445       {
1446         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1447       }
1448       else
1449       {
1450         dir = edgeDir[0] + edgeDir[1];
1451         if ( angle < 0 )
1452           dir.Reverse();
1453       }
1454       if ( cosin ) {
1455         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1456         *cosin = Cos( angle );
1457       }
1458     }
1459     else if ( nbEdges == 1 )
1460     {
1461       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1462       if ( cosin ) *cosin = 1.;
1463     }
1464     else
1465     {
1466       ok = false;
1467     }
1468
1469     return dir;
1470   }
1471
1472   //================================================================================
1473   /*!
1474    * \brief Finds concave VERTEXes of a FACE
1475    */
1476   //================================================================================
1477
1478   bool getConcaveVertices( const TopoDS_Face&  F,
1479                            SMESH_MesherHelper& helper,
1480                            set< TGeomID >*     vertices = 0)
1481   {
1482     // check angles at VERTEXes
1483     TError error;
1484     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1485     for ( size_t iW = 0; iW < wires.size(); ++iW )
1486     {
1487       const int nbEdges = wires[iW]->NbEdges();
1488       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1489         continue;
1490       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1491       {
1492         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1493         int iE2 = ( iE1 + 1 ) % nbEdges;
1494         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1495           iE2 = ( iE2 + 1 ) % nbEdges;
1496         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1497         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1498                                         wires[iW]->Edge( iE2 ), F, V );
1499         if ( angle < -5. * M_PI / 180. )
1500         {
1501           if ( !vertices )
1502             return true;
1503           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1504         }
1505       }
1506     }
1507     return vertices ? !vertices->empty() : false;
1508   }
1509
1510   //================================================================================
1511   /*!
1512    * \brief Returns true if a FACE is bound by a concave EDGE
1513    */
1514   //================================================================================
1515
1516   bool isConcave( const TopoDS_Face&  F,
1517                   SMESH_MesherHelper& helper,
1518                   set< TGeomID >*     vertices = 0 )
1519   {
1520     bool isConcv = false;
1521     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1522     //   return true;
1523     gp_Vec2d drv1, drv2;
1524     gp_Pnt2d p;
1525     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1526     for ( ; eExp.More(); eExp.Next() )
1527     {
1528       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1529       if ( SMESH_Algo::isDegenerated( E )) continue;
1530       // check if 2D curve is concave
1531       BRepAdaptor_Curve2d curve( E, F );
1532       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1533       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1534       curve.Intervals( intervals, GeomAbs_C2 );
1535       bool isConvex = true;
1536       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1537       {
1538         double u1 = intervals( i );
1539         double u2 = intervals( i+1 );
1540         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1541         double cross = drv1 ^ drv2;
1542         if ( E.Orientation() == TopAbs_REVERSED )
1543           cross = -cross;
1544         isConvex = ( cross > -1e-9 ); // 0.1 );
1545       }
1546       if ( !isConvex )
1547       {
1548         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1549         isConcv = true;
1550         if ( vertices )
1551           break;
1552         else
1553           return true;
1554       }
1555     }
1556
1557     // check angles at VERTEXes
1558     if ( getConcaveVertices( F, helper, vertices ))
1559       isConcv = true;
1560
1561     return isConcv;
1562   }
1563
1564   //================================================================================
1565   /*!
1566    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1567    *  \param [in] face - the mesh face to treat
1568    *  \param [in] nodeOnEdge - a node on the EDGE
1569    *  \param [out] faceSize - the computed distance
1570    *  \return bool - true if faceSize computed
1571    */
1572   //================================================================================
1573
1574   bool getDistFromEdge( const SMDS_MeshElement* face,
1575                         const SMDS_MeshNode*    nodeOnEdge,
1576                         double &                faceSize )
1577   {
1578     faceSize = Precision::Infinite();
1579     bool done = false;
1580
1581     int nbN  = face->NbCornerNodes();
1582     int iOnE = face->GetNodeIndex( nodeOnEdge );
1583     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1584                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1585     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1586                                       face->GetNode( iNext[1] ) };
1587     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1588     double segLen = -1.;
1589     // look for two neighbor not in-FACE nodes of face
1590     for ( int i = 0; i < 2; ++i )
1591     {
1592       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1593            nNext[i]->GetID() < nodeOnEdge->GetID() )
1594       {
1595         // look for an in-FACE node
1596         for ( int iN = 0; iN < nbN; ++iN )
1597         {
1598           if ( iN == iOnE || iN == iNext[i] )
1599             continue;
1600           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1601           gp_XYZ v = pInFace - segEnd;
1602           if ( segLen < 0 )
1603           {
1604             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1605             segLen = segVec.Modulus();
1606           }
1607           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1608           faceSize = Min( faceSize, distToSeg );
1609           done = true;
1610         }
1611         segLen = -1;
1612       }
1613     }
1614     return done;
1615   }
1616   //================================================================================
1617   /*!
1618    * \brief Return direction of axis or revolution of a surface
1619    */
1620   //================================================================================
1621
1622   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1623                           gp_Dir &                 axis )
1624   {
1625     switch ( surface.GetType() ) {
1626     case GeomAbs_Cone:
1627     {
1628       gp_Cone cone = surface.Cone();
1629       axis = cone.Axis().Direction();
1630       break;
1631     }
1632     case GeomAbs_Sphere:
1633     {
1634       gp_Sphere sphere = surface.Sphere();
1635       axis = sphere.Position().Direction();
1636       break;
1637     }
1638     case GeomAbs_SurfaceOfRevolution:
1639     {
1640       axis = surface.AxeOfRevolution().Direction();
1641       break;
1642     }
1643     //case GeomAbs_SurfaceOfExtrusion:
1644     case GeomAbs_OffsetSurface:
1645     {
1646       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1647       return getRovolutionAxis( base->Surface(), axis );
1648     }
1649     default: return false;
1650     }
1651     return true;
1652   }
1653
1654   //--------------------------------------------------------------------------------
1655   // DEBUG. Dump intermediate node positions into a python script
1656   // HOWTO use: run python commands written in a console to see
1657   //  construction steps of viscous layers
1658 #ifdef __myDEBUG
1659   ofstream* py;
1660   int       theNbPyFunc;
1661   struct PyDump {
1662     PyDump(SMESH_Mesh& m) {
1663       int tag = 3 + m.GetId();
1664       const char* fname = "/tmp/viscous.py";
1665       cout << "execfile('"<<fname<<"')"<<endl;
1666       py = new ofstream(fname);
1667       *py << "import SMESH" << endl
1668           << "from salome.smesh import smeshBuilder" << endl
1669           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1670           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1671           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1672       theNbPyFunc = 0;
1673     }
1674     void Finish() {
1675       if (py) {
1676         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1677           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1678         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1679           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1680       }
1681       delete py; py=0;
1682     }
1683     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1684   };
1685 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1686 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1687 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1688 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1689   void _dumpFunction(const string& fun, int ln)
1690   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1691   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1692   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1693                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1694   void _dumpCmd(const string& txt, int ln)
1695   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1696   void dumpFunctionEnd()
1697   { if (py) *py<< "  return"<< endl; }
1698   void dumpChangeNodes( const SMDS_MeshElement* f )
1699   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1700       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1701       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1702 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1703
1704 #else
1705
1706   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1707 #define dumpFunction(f) f
1708 #define dumpMove(n)
1709 #define dumpMoveComm(n,txt)
1710 #define dumpCmd(txt)
1711 #define dumpFunctionEnd()
1712 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1713 #define debugMsg( txt ) {}
1714
1715 #endif
1716 }
1717
1718 using namespace VISCOUS_3D;
1719
1720 //================================================================================
1721 /*!
1722  * \brief Constructor of _ViscousBuilder
1723  */
1724 //================================================================================
1725
1726 _ViscousBuilder::_ViscousBuilder()
1727 {
1728   _error = SMESH_ComputeError::New(COMPERR_OK);
1729   _tmpFaceID = 0;
1730 }
1731
1732 //================================================================================
1733 /*!
1734  * \brief Stores error description and returns false
1735  */
1736 //================================================================================
1737
1738 bool _ViscousBuilder::error(const string& text, int solidId )
1739 {
1740   const string prefix = string("Viscous layers builder: ");
1741   _error->myName    = COMPERR_ALGO_FAILED;
1742   _error->myComment = prefix + text;
1743   if ( _mesh )
1744   {
1745     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1746     if ( !sm && !_sdVec.empty() )
1747       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1748     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1749     {
1750       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1751       if ( smError && smError->myAlgo )
1752         _error->myAlgo = smError->myAlgo;
1753       smError = _error;
1754       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1755     }
1756     // set KO to all solids
1757     for ( size_t i = 0; i < _sdVec.size(); ++i )
1758     {
1759       if ( _sdVec[i]._index == solidId )
1760         continue;
1761       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1762       if ( !sm->IsEmpty() )
1763         continue;
1764       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1765       if ( !smError || smError->IsOK() )
1766       {
1767         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1768         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1769       }
1770     }
1771   }
1772   makeGroupOfLE(); // debug
1773
1774   return false;
1775 }
1776
1777 //================================================================================
1778 /*!
1779  * \brief At study restoration, restore event listeners used to clear an inferior
1780  *  dim sub-mesh modified by viscous layers
1781  */
1782 //================================================================================
1783
1784 void _ViscousBuilder::RestoreListeners()
1785 {
1786   // TODO
1787 }
1788
1789 //================================================================================
1790 /*!
1791  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1792  */
1793 //================================================================================
1794
1795 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1796 {
1797   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1798   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1799   for ( ; fExp.More(); fExp.Next() )
1800   {
1801     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1802     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1803
1804     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1805       continue;
1806     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1807       continue;
1808
1809     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1810       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1811
1812     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1813     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1814     while( prxIt->more() )
1815     {
1816       const SMDS_MeshElement* fSrc = srcIt->next();
1817       const SMDS_MeshElement* fPrx = prxIt->next();
1818       if ( fSrc->NbNodes() != fPrx->NbNodes())
1819         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1820       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1821         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1822     }
1823   }
1824   pm->_n2nMapComputed = true;
1825   return true;
1826 }
1827
1828 //================================================================================
1829 /*!
1830  * \brief Does its job
1831  */
1832 //================================================================================
1833
1834 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1835                                                const TopoDS_Shape& theShape)
1836 {
1837   // TODO: set priority of solids during Gen::Compute()
1838
1839   _mesh = & theMesh;
1840
1841   // check if proxy mesh already computed
1842   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1843   if ( !exp.More() )
1844     return error("No SOLID's in theShape"), _error;
1845
1846   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1847     return SMESH_ComputeErrorPtr(); // everything already computed
1848
1849   PyDump debugDump( theMesh );
1850
1851   // TODO: ignore already computed SOLIDs 
1852   if ( !findSolidsWithLayers())
1853     return _error;
1854
1855   if ( !findFacesWithLayers() )
1856     return _error;
1857
1858   for ( size_t i = 0; i < _sdVec.size(); ++i )
1859   {
1860     if ( ! makeLayer(_sdVec[i]) )
1861       return _error;
1862
1863     if ( _sdVec[i]._n2eMap.size() == 0 )
1864       continue;
1865     
1866     if ( ! inflate(_sdVec[i]) )
1867       return _error;
1868
1869     if ( ! refine(_sdVec[i]) )
1870       return _error;
1871   }
1872   if ( !shrink() )
1873     return _error;
1874
1875   addBoundaryElements();
1876
1877   makeGroupOfLE(); // debug
1878   debugDump.Finish();
1879
1880   return _error;
1881 }
1882
1883 //================================================================================
1884 /*!
1885  * \brief Check validity of hypotheses
1886  */
1887 //================================================================================
1888
1889 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1890                                                         const TopoDS_Shape& shape )
1891 {
1892   _mesh = & mesh;
1893
1894   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1895     return SMESH_ComputeErrorPtr(); // everything already computed
1896
1897
1898   findSolidsWithLayers();
1899   bool ok = findFacesWithLayers( true );
1900
1901   // remove _MeshOfSolid's of _SolidData's
1902   for ( size_t i = 0; i < _sdVec.size(); ++i )
1903     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1904
1905   if ( !ok )
1906     return _error;
1907
1908   return SMESH_ComputeErrorPtr();
1909 }
1910
1911 //================================================================================
1912 /*!
1913  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1914  */
1915 //================================================================================
1916
1917 bool _ViscousBuilder::findSolidsWithLayers()
1918 {
1919   // get all solids
1920   TopTools_IndexedMapOfShape allSolids;
1921   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1922   _sdVec.reserve( allSolids.Extent());
1923
1924   SMESH_Gen* gen = _mesh->GetGen();
1925   SMESH_HypoFilter filter;
1926   for ( int i = 1; i <= allSolids.Extent(); ++i )
1927   {
1928     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1929     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1930     if ( !algo ) continue;
1931     // TODO: check if algo is hidden
1932     const list <const SMESHDS_Hypothesis *> & allHyps =
1933       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1934     _SolidData* soData = 0;
1935     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1936     const StdMeshers_ViscousLayers* viscHyp = 0;
1937     for ( ; hyp != allHyps.end(); ++hyp )
1938       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
1939       {
1940         TopoDS_Shape hypShape;
1941         filter.Init( filter.Is( viscHyp ));
1942         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1943
1944         if ( !soData )
1945         {
1946           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1947                                                                     allSolids(i),
1948                                                                     /*toCreate=*/true);
1949           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1950           soData = & _sdVec.back();
1951           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1952           soData->_helper = new SMESH_MesherHelper( *_mesh );
1953           soData->_helper->SetSubShape( allSolids(i) );
1954         }
1955         soData->_hyps.push_back( viscHyp );
1956         soData->_hypShapes.push_back( hypShape );
1957       }
1958   }
1959   if ( _sdVec.empty() )
1960     return error
1961       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1962
1963   return true;
1964 }
1965
1966 //================================================================================
1967 /*!
1968  * \brief 
1969  */
1970 //================================================================================
1971
1972 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1973 {
1974   SMESH_MesherHelper helper( *_mesh );
1975   TopExp_Explorer exp;
1976   TopTools_IndexedMapOfShape solids;
1977
1978   // collect all faces-to-ignore defined by hyp
1979   for ( size_t i = 0; i < _sdVec.size(); ++i )
1980   {
1981     solids.Add( _sdVec[i]._solid );
1982
1983     // get faces-to-ignore defined by each hyp
1984     typedef const StdMeshers_ViscousLayers* THyp;
1985     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1986     list< TFacesOfHyp > ignoreFacesOfHyps;
1987     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1988     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1989     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1990     {
1991       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1992       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1993     }
1994
1995     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1996     const int nbHyps = _sdVec[i]._hyps.size();
1997     if ( nbHyps > 1 )
1998     {
1999       // check if two hypotheses define different parameters for the same FACE
2000       list< TFacesOfHyp >::iterator igFacesOfHyp;
2001       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2002       {
2003         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2004         THyp hyp = 0;
2005         igFacesOfHyp = ignoreFacesOfHyps.begin();
2006         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2007           if ( ! igFacesOfHyp->first.count( faceID ))
2008           {
2009             if ( hyp )
2010               return error(SMESH_Comment("Several hypotheses define "
2011                                          "Viscous Layers on the face #") << faceID );
2012             hyp = igFacesOfHyp->second;
2013           }
2014         if ( hyp )
2015           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2016         else
2017           _sdVec[i]._ignoreFaceIds.insert( faceID );
2018       }
2019
2020       // check if two hypotheses define different number of viscous layers for
2021       // adjacent faces of a solid
2022       set< int > nbLayersSet;
2023       igFacesOfHyp = ignoreFacesOfHyps.begin();
2024       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2025       {
2026         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2027       }
2028       if ( nbLayersSet.size() > 1 )
2029       {
2030         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2031         {
2032           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2033           THyp hyp1 = 0, hyp2 = 0;
2034           while( const TopoDS_Shape* face = fIt->next() )
2035           {
2036             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2037             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2038             if ( f2h != _sdVec[i]._face2hyp.end() )
2039             {
2040               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2041             }
2042           }
2043           if ( hyp1 && hyp2 &&
2044                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2045           {
2046             return error("Two hypotheses define different number of "
2047                          "viscous layers on adjacent faces");
2048           }
2049         }
2050       }
2051     } // if ( nbHyps > 1 )
2052     else
2053     {
2054       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2055     }
2056   } // loop on _sdVec
2057
2058   if ( onlyWith ) // is called to check hypotheses compatibility only
2059     return true;
2060
2061   // fill _SolidData::_reversedFaceIds
2062   for ( size_t i = 0; i < _sdVec.size(); ++i )
2063   {
2064     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2065     for ( ; exp.More(); exp.Next() )
2066     {
2067       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2068       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
2069       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2070           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2071           helper.IsReversedSubMesh( face ))
2072       {
2073         _sdVec[i]._reversedFaceIds.insert( faceID );
2074       }
2075     }
2076   }
2077
2078   // Find faces to shrink mesh on (solution 2 in issue 0020832);
2079   TopTools_IndexedMapOfShape shapes;
2080   for ( size_t i = 0; i < _sdVec.size(); ++i )
2081   {
2082     shapes.Clear();
2083     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2084     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2085     {
2086       const TopoDS_Shape& edge = shapes(iE);
2087       // find 2 faces sharing an edge
2088       TopoDS_Shape FF[2];
2089       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
2090       while ( fIt->more())
2091       {
2092         const TopoDS_Shape* f = fIt->next();
2093         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
2094           FF[ int( !FF[0].IsNull()) ] = *f;
2095       }
2096       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2097       // check presence of layers on them
2098       int ignore[2];
2099       for ( int j = 0; j < 2; ++j )
2100         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
2101       if ( ignore[0] == ignore[1] )
2102         continue; // nothing interesting
2103       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
2104       // check presence of layers on fWOL within an adjacent SOLID
2105       bool collision = false;
2106       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
2107       while ( const TopoDS_Shape* solid = sIt->next() )
2108         if ( !solid->IsSame( _sdVec[i]._solid ))
2109         {
2110           int iSolid = solids.FindIndex( *solid );
2111           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
2112           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
2113           {
2114             //_sdVec[i]._noShrinkShapes.insert( iFace );
2115             //fWOL.Nullify();
2116             collision = true;
2117           }
2118         }
2119       // add edge to maps
2120       if ( !fWOL.IsNull())
2121       {
2122         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2123         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2124         if ( collision )
2125         {
2126           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
2127           // on the edge but shrink won't be performed
2128           _sdVec[i]._noShrinkShapes.insert( edgeInd );
2129         }
2130       }
2131     }
2132   }
2133   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
2134   // the algo of the SOLID sharing the FACE does not support it
2135   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
2136   for ( size_t i = 0; i < _sdVec.size(); ++i )
2137   {
2138     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2139     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2140     {
2141       const TopoDS_Shape& fWOL = e2f->second;
2142       const TGeomID     edgeID = e2f->first;
2143       bool notShrinkFace = false;
2144       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2145       while ( soIt->more() )
2146       {
2147         const TopoDS_Shape* solid = soIt->next();
2148         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
2149         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
2150         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
2151         notShrinkFace = true;
2152         size_t iSolid = 0;
2153         for ( ; iSolid < _sdVec.size(); ++iSolid )
2154         {
2155           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
2156             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
2157               notShrinkFace = false;
2158             break;
2159           }
2160         }
2161         if ( notShrinkFace )
2162         {
2163           _sdVec[i]._noShrinkShapes.insert( edgeID );
2164
2165           // add VERTEXes of the edge in _noShrinkShapes
2166           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
2167           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2168             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
2169
2170           // check if there is a collision with to-shrink-from EDGEs in iSolid
2171           if ( iSolid == _sdVec.size() )
2172             continue; // no VL in the solid
2173           shapes.Clear();
2174           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2175           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2176           {
2177             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2178             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2179             if ( eID == edgeID ||
2180                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2181                  _sdVec[i]._noShrinkShapes.count( eID ))
2182               continue;
2183             for ( int is1st = 0; is1st < 2; ++is1st )
2184             {
2185               TopoDS_Vertex V = helper.IthVertex( is1st, E );
2186               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2187               {
2188                 // _sdVec[i]._noShrinkShapes.insert( eID );
2189                 // V = helper.IthVertex( !is1st, E );
2190                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
2191                 //iE = 0; // re-start the loop on EDGEs of fWOL
2192                 return error("No way to make a conformal mesh with "
2193                              "the given set of faces with layers", _sdVec[i]._index);
2194               }
2195             }
2196           }
2197         }
2198
2199       } // while ( soIt->more() )
2200     } // loop on _sdVec[i]._shrinkShape2Shape
2201   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2202
2203   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2204
2205   for ( size_t i = 0; i < _sdVec.size(); ++i )
2206   {
2207     shapes.Clear();
2208     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2209     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2210     {
2211       const TopoDS_Shape& vertex = shapes(iV);
2212       // find faces WOL sharing the vertex
2213       vector< TopoDS_Shape > facesWOL;
2214       size_t totalNbFaces = 0;
2215       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
2216       while ( fIt->more())
2217       {
2218         const TopoDS_Shape* f = fIt->next();
2219         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
2220         {
2221           totalNbFaces++;
2222           const int fID = getMeshDS()->ShapeToIndex( *f );
2223           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
2224                !_sdVec[i]._noShrinkShapes.count( fID )*/)
2225             facesWOL.push_back( *f );
2226         }
2227       }
2228       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2229         continue; // no layers at this vertex or no WOL
2230       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2231       switch ( facesWOL.size() )
2232       {
2233       case 1:
2234       {
2235         helper.SetSubShape( facesWOL[0] );
2236         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2237         {
2238           TopoDS_Shape seamEdge;
2239           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2240           while ( eIt->more() && seamEdge.IsNull() )
2241           {
2242             const TopoDS_Shape* e = eIt->next();
2243             if ( helper.IsRealSeam( *e ) )
2244               seamEdge = *e;
2245           }
2246           if ( !seamEdge.IsNull() )
2247           {
2248             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2249             break;
2250           }
2251         }
2252         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2253         break;
2254       }
2255       case 2:
2256       {
2257         // find an edge shared by 2 faces
2258         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2259         while ( eIt->more())
2260         {
2261           const TopoDS_Shape* e = eIt->next();
2262           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2263                helper.IsSubShape( *e, facesWOL[1]))
2264           {
2265             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2266           }
2267         }
2268         break;
2269       }
2270       default:
2271         return error("Not yet supported case", _sdVec[i]._index);
2272       }
2273     }
2274   }
2275
2276   // add FACEs of other SOLIDs to _ignoreFaceIds
2277   for ( size_t i = 0; i < _sdVec.size(); ++i )
2278   {
2279     shapes.Clear();
2280     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2281
2282     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2283     {
2284       if ( !shapes.Contains( exp.Current() ))
2285         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2286     }
2287   }
2288
2289   return true;
2290 }
2291
2292 //================================================================================
2293 /*!
2294  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2295  */
2296 //================================================================================
2297
2298 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2299                                      const StdMeshers_ViscousLayers* hyp,
2300                                      const TopoDS_Shape&             hypShape,
2301                                      set<TGeomID>&                   ignoreFaceIds)
2302 {
2303   TopExp_Explorer exp;
2304
2305   vector<TGeomID> ids = hyp->GetBndShapes();
2306   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2307   {
2308     for ( size_t ii = 0; ii < ids.size(); ++ii )
2309     {
2310       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2311       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2312         ignoreFaceIds.insert( ids[ii] );
2313     }
2314   }
2315   else // FACEs with layers are given
2316   {
2317     exp.Init( solid, TopAbs_FACE );
2318     for ( ; exp.More(); exp.Next() )
2319     {
2320       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2321       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2322         ignoreFaceIds.insert( faceInd );
2323     }
2324   }
2325
2326   // ignore internal FACEs if inlets and outlets are specified
2327   if ( hyp->IsToIgnoreShapes() )
2328   {
2329     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2330     TopExp::MapShapesAndAncestors( hypShape,
2331                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2332
2333     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2334     {
2335       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2336       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2337         continue;
2338
2339       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2340       if ( nbSolids > 1 )
2341         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2342     }
2343   }
2344 }
2345
2346 //================================================================================
2347 /*!
2348  * \brief Create the inner surface of the viscous layer and prepare data for infation
2349  */
2350 //================================================================================
2351
2352 bool _ViscousBuilder::makeLayer(_SolidData& data)
2353 {
2354   // get all sub-shapes to make layers on
2355   set<TGeomID> subIds, faceIds;
2356   subIds = data._noShrinkShapes;
2357   TopExp_Explorer exp( data._solid, TopAbs_FACE );
2358   for ( ; exp.More(); exp.Next() )
2359   {
2360     SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
2361     if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
2362       faceIds.insert( fSubM->GetId() );
2363   }
2364
2365   // make a map to find new nodes on sub-shapes shared with other SOLID
2366   map< TGeomID, TNode2Edge* >::iterator s2ne;
2367   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2368   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2369   {
2370     TGeomID shapeInd = s2s->first;
2371     for ( size_t i = 0; i < _sdVec.size(); ++i )
2372     {
2373       if ( _sdVec[i]._index == data._index ) continue;
2374       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2375       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2376            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2377       {
2378         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2379         break;
2380       }
2381     }
2382   }
2383
2384   // Create temporary faces and _LayerEdge's
2385
2386   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2387
2388   data._stepSize = Precision::Infinite();
2389   data._stepSizeNodes[0] = 0;
2390
2391   SMESH_MesherHelper helper( *_mesh );
2392   helper.SetSubShape( data._solid );
2393   helper.SetElementsOnShape( true );
2394
2395   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2396   TNode2Edge::iterator n2e2;
2397
2398   // collect _LayerEdge's of shapes they are based on
2399   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2400   const int nbShapes = getMeshDS()->MaxShapeIndex();
2401   edgesByGeom.resize( nbShapes+1 );
2402
2403   // set data of _EdgesOnShape's
2404   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
2405   {
2406     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
2407     while ( smIt->more() )
2408     {
2409       sm = smIt->next();
2410       if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
2411            !faceIds.count( sm->GetId() ))
2412         continue;
2413       setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
2414     }
2415   }
2416   // make _LayerEdge's
2417   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2418   {
2419     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2420     SMESH_subMesh* sm = _mesh->GetSubMesh( F );
2421     SMESH_ProxyMesh::SubMesh* proxySub =
2422       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2423
2424     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2425     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2426
2427     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2428     while ( eIt->more() )
2429     {
2430       const SMDS_MeshElement* face = eIt->next();
2431       double          faceMaxCosin = -1;
2432       _LayerEdge*     maxCosinEdge = 0;
2433       int             nbDegenNodes = 0;
2434
2435       newNodes.resize( face->NbCornerNodes() );
2436       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2437       {
2438         const SMDS_MeshNode* n = face->GetNode( i );
2439         const int      shapeID = n->getshapeId();
2440         const bool onDegenShap = helper.IsDegenShape( shapeID );
2441         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2442         if ( onDegenShap )
2443         {
2444           if ( onDegenEdge )
2445           {
2446             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2447             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2448             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2449             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2450               n = vN;
2451               nbDegenNodes++;
2452             }
2453           }
2454           else
2455           {
2456             nbDegenNodes++;
2457           }
2458         }
2459         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2460         if ( !(*n2e).second )
2461         {
2462           // add a _LayerEdge
2463           _LayerEdge* edge = new _LayerEdge();
2464           edge->_nodes.push_back( n );
2465           n2e->second = edge;
2466           edgesByGeom[ shapeID ]._edges.push_back( edge );
2467           const bool noShrink = data._noShrinkShapes.count( shapeID );
2468
2469           SMESH_TNodeXYZ xyz( n );
2470
2471           // set edge data or find already refined _LayerEdge and get data from it
2472           if (( !noShrink                                                     ) &&
2473               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2474               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2475               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2476           {
2477             _LayerEdge* foundEdge = (*n2e2).second;
2478             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2479             foundEdge->_pos.push_back( lastPos );
2480             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2481             const_cast< SMDS_MeshNode* >
2482               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2483           }
2484           else
2485           {
2486             if ( !noShrink )
2487             {
2488               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2489             }
2490             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2491               return false;
2492
2493             if ( edge->_nodes.size() < 2 )
2494               edge->Block( data );
2495               //data._noShrinkShapes.insert( shapeID );
2496           }
2497           dumpMove(edge->_nodes.back());
2498
2499           if ( edge->_cosin > faceMaxCosin )
2500           {
2501             faceMaxCosin = edge->_cosin;
2502             maxCosinEdge = edge;
2503           }
2504         }
2505         newNodes[ i ] = n2e->second->_nodes.back();
2506
2507         if ( onDegenEdge )
2508           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2509       }
2510       if ( newNodes.size() - nbDegenNodes < 2 )
2511         continue;
2512
2513       // create a temporary face
2514       const SMDS_MeshElement* newFace =
2515         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId(), face->getIdInShape() );
2516       proxySub->AddElement( newFace );
2517
2518       // compute inflation step size by min size of element on a convex surface
2519       if ( faceMaxCosin > theMinSmoothCosin )
2520         limitStepSize( data, face, maxCosinEdge );
2521
2522     } // loop on 2D elements on a FACE
2523   } // loop on FACEs of a SOLID to create _LayerEdge's
2524
2525
2526   // Set _LayerEdge::_neibors
2527   TNode2Edge::iterator n2e;
2528   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2529   {
2530     _EdgesOnShape& eos = data._edgesOnShape[iS];
2531     for ( size_t i = 0; i < eos._edges.size(); ++i )
2532     {
2533       _LayerEdge* edge = eos._edges[i];
2534       TIDSortedNodeSet nearNodes;
2535       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2536       while ( fIt->more() )
2537       {
2538         const SMDS_MeshElement* f = fIt->next();
2539         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2540           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2541       }
2542       nearNodes.erase( edge->_nodes[0] );
2543       edge->_neibors.reserve( nearNodes.size() );
2544       TIDSortedNodeSet::iterator node = nearNodes.begin();
2545       for ( ; node != nearNodes.end(); ++node )
2546         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2547           edge->_neibors.push_back( n2e->second );
2548     }
2549   }
2550
2551   data._epsilon = 1e-7;
2552   if ( data._stepSize < 1. )
2553     data._epsilon *= data._stepSize;
2554
2555   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2556     return false;
2557
2558   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2559   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2560
2561   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2562   const SMDS_MeshNode* nn[2];
2563   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2564   {
2565     _EdgesOnShape& eos = data._edgesOnShape[iS];
2566     for ( size_t i = 0; i < eos._edges.size(); ++i )
2567     {
2568       _LayerEdge* edge = eos._edges[i];
2569       if ( edge->IsOnEdge() )
2570       {
2571         // get neighbor nodes
2572         bool hasData = ( edge->_2neibors->_edges[0] );
2573         if ( hasData ) // _LayerEdge is a copy of another one
2574         {
2575           nn[0] = edge->_2neibors->srcNode(0);
2576           nn[1] = edge->_2neibors->srcNode(1);
2577         }
2578         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2579         {
2580           return false;
2581         }
2582         // set neighbor _LayerEdge's
2583         for ( int j = 0; j < 2; ++j )
2584         {
2585           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2586             return error("_LayerEdge not found by src node", data._index);
2587           edge->_2neibors->_edges[j] = n2e->second;
2588         }
2589         if ( !hasData )
2590           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2591       }
2592
2593       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2594       {
2595         _Simplex& s = edge->_simplices[j];
2596         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2597         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2598       }
2599
2600       // For an _LayerEdge on a degenerated EDGE, copy some data from
2601       // a corresponding _LayerEdge on a VERTEX
2602       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2603       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2604       {
2605         // Generally we should not get here
2606         if ( eos.ShapeType() != TopAbs_EDGE )
2607           continue;
2608         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2609         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2610         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2611           continue;
2612         const _LayerEdge* vEdge = n2e->second;
2613         edge->_normal    = vEdge->_normal;
2614         edge->_lenFactor = vEdge->_lenFactor;
2615         edge->_cosin     = vEdge->_cosin;
2616       }
2617
2618     } // loop on data._edgesOnShape._edges
2619   } // loop on data._edgesOnShape
2620
2621   // fix _LayerEdge::_2neibors on EDGEs to smooth
2622   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2623   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2624   //   if ( !e2c->second.IsNull() )
2625   //   {
2626   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2627   //       data.Sort2NeiborsOnEdge( eos->_edges );
2628   //   }
2629
2630   dumpFunctionEnd();
2631   return true;
2632 }
2633
2634 //================================================================================
2635 /*!
2636  * \brief Compute inflation step size by min size of element on a convex surface
2637  */
2638 //================================================================================
2639
2640 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2641                                      const SMDS_MeshElement* face,
2642                                      const _LayerEdge*       maxCosinEdge )
2643 {
2644   int iN = 0;
2645   double minSize = 10 * data._stepSize;
2646   const int nbNodes = face->NbCornerNodes();
2647   for ( int i = 0; i < nbNodes; ++i )
2648   {
2649     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2650     const SMDS_MeshNode*  curN = face->GetNode( i );
2651     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2652          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2653     {
2654       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2655       if ( dist < minSize )
2656         minSize = dist, iN = i;
2657     }
2658   }
2659   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2660   if ( newStep < data._stepSize )
2661   {
2662     data._stepSize = newStep;
2663     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2664     data._stepSizeNodes[0] = face->GetNode( iN );
2665     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2666   }
2667 }
2668
2669 //================================================================================
2670 /*!
2671  * \brief Compute inflation step size by min size of element on a convex surface
2672  */
2673 //================================================================================
2674
2675 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2676 {
2677   if ( minSize < data._stepSize )
2678   {
2679     data._stepSize = minSize;
2680     if ( data._stepSizeNodes[0] )
2681     {
2682       double dist =
2683         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2684       data._stepSizeCoeff = data._stepSize / dist;
2685     }
2686   }
2687 }
2688
2689 //================================================================================
2690 /*!
2691  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2692  */
2693 //================================================================================
2694
2695 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2696 {
2697   SMESH_MesherHelper helper( *_mesh );
2698
2699   const int nbTestPnt = 5; // on a FACE sub-shape
2700
2701   BRepLProp_SLProps surfProp( 2, 1e-6 );
2702   data._convexFaces.clear();
2703
2704   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2705   {
2706     _EdgesOnShape& eof = data._edgesOnShape[iS];
2707     if ( eof.ShapeType() != TopAbs_FACE ||
2708          data._ignoreFaceIds.count( eof._shapeID ))
2709       continue;
2710
2711     TopoDS_Face        F = TopoDS::Face( eof._shape );
2712     SMESH_subMesh *   sm = eof._subMesh;
2713     const TGeomID faceID = eof._shapeID;
2714
2715     BRepAdaptor_Surface surface( F, false );
2716     surfProp.SetSurface( surface );
2717
2718     bool isTooCurved = false;
2719
2720     _ConvexFace cnvFace;
2721     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2722     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2723     while ( smIt->more() )
2724     {
2725       sm = smIt->next();
2726       const TGeomID subID = sm->GetId();
2727       // find _LayerEdge's of a sub-shape
2728       _EdgesOnShape* eos;
2729       if (( eos = data.GetShapeEdges( subID )))
2730         cnvFace._subIdToEOS.insert( make_pair( subID, eos ));
2731       else
2732         continue;
2733       // check concavity and curvature and limit data._stepSize
2734       const double minCurvature =
2735         1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2736       size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
2737       for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
2738       {
2739         gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
2740         surfProp.SetParameters( uv.X(), uv.Y() );
2741         if ( !surfProp.IsCurvatureDefined() )
2742           continue;
2743         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2744         {
2745           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2746           isTooCurved = true;
2747         }
2748         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2749         {
2750           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2751           isTooCurved = true;
2752         }
2753       }
2754     } // loop on sub-shapes of the FACE
2755
2756     if ( !isTooCurved ) continue;
2757
2758     _ConvexFace & convFace =
2759       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2760
2761     convFace._face = F;
2762     convFace._normalsFixed = false;
2763
2764     // skip a closed surface (data._convexFaces is useful anyway)
2765     bool isClosedF = false;
2766     helper.SetSubShape( F );
2767     if ( helper.HasRealSeam() )
2768     {
2769       // in the closed surface there must be a closed EDGE
2770       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2771         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2772     }
2773     if ( isClosedF )
2774     {
2775       // limit _LayerEdge::_maxLen on the FACE
2776       const double minCurvature =
2777         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2778       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2779       if ( id2eos != cnvFace._subIdToEOS.end() )
2780       {
2781         _EdgesOnShape& eos = * id2eos->second;
2782         for ( size_t i = 0; i < eos._edges.size(); ++i )
2783         {
2784           _LayerEdge* ledge = eos._edges[ i ];
2785           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2786           surfProp.SetParameters( uv.X(), uv.Y() );
2787           if ( !surfProp.IsCurvatureDefined() )
2788             continue;
2789
2790           if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2791             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MaxCurvature() * oriFactor );
2792
2793           if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2794             ledge->_maxLen = Min( ledge->_maxLen, 1. / surfProp.MinCurvature() * oriFactor );
2795         }
2796       }
2797       continue;
2798     }
2799
2800     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2801     // prism distortion.
2802     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2803     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2804     {
2805       // there are _LayerEdge's on the FACE it-self;
2806       // select _LayerEdge's near EDGEs
2807       _EdgesOnShape& eos = * id2eos->second;
2808       for ( size_t i = 0; i < eos._edges.size(); ++i )
2809       {
2810         _LayerEdge* ledge = eos._edges[ i ];
2811         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2812           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2813           {
2814             convFace._simplexTestEdges.push_back( ledge );
2815             break;
2816           }
2817       }
2818     }
2819     else
2820     {
2821       // where there are no _LayerEdge's on a _ConvexFace,
2822       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2823       // so that collision of viscous internal faces is not detected by check of
2824       // intersection of _LayerEdge's with the viscous internal faces.
2825
2826       set< const SMDS_MeshNode* > usedNodes;
2827
2828       // look for _LayerEdge's with null _sWOL
2829       id2eos = convFace._subIdToEOS.begin();
2830       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
2831       {
2832         _EdgesOnShape& eos = * id2eos->second;
2833         if ( !eos._sWOL.IsNull() )
2834           continue;
2835         for ( size_t i = 0; i < eos._edges.size(); ++i )
2836         {
2837           _LayerEdge* ledge = eos._edges[ i ];
2838           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2839           if ( !usedNodes.insert( srcNode ).second ) continue;
2840
2841           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2842           {
2843             usedNodes.insert( ledge->_simplices[i]._nPrev );
2844             usedNodes.insert( ledge->_simplices[i]._nNext );
2845           }
2846           convFace._simplexTestEdges.push_back( ledge );
2847         }
2848       }
2849     }
2850   } // loop on FACEs of data._solid
2851 }
2852
2853 //================================================================================
2854 /*!
2855  * \brief Detect shapes (and _LayerEdge's on them) to smooth
2856  */
2857 //================================================================================
2858
2859 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
2860 {
2861   // define allowed thickness
2862   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
2863
2864   data._maxThickness = 0;
2865   data._minThickness = 1e100;
2866   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2867   for ( ; hyp != data._hyps.end(); ++hyp )
2868   {
2869     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2870     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2871   }
2872   //const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2873
2874   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2875   // boundry inclined to the shape at a sharp angle
2876
2877   //list< TGeomID > shapesToSmooth;
2878   TopTools_MapOfShape edgesOfSmooFaces;
2879
2880   SMESH_MesherHelper helper( *_mesh );
2881   bool ok = true;
2882
2883   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2884   data._nbShapesToSmooth = 0;
2885
2886   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2887   {
2888     _EdgesOnShape& eos = edgesByGeom[iS];
2889     eos._toSmooth = false;
2890     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
2891       continue;
2892
2893     double tgtThick = eos._hyp.GetTotalThickness();
2894     TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE );
2895     for ( ; eExp.More() && !eos._toSmooth; eExp.Next() )
2896     {
2897       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2898       vector<_LayerEdge*>& eE = edgesByGeom[ iE ]._edges;
2899       if ( eE.empty() ) continue;
2900
2901       double faceSize;
2902       for ( size_t i = 0; i < eE.size() && !eos._toSmooth; ++i )
2903         if ( eE[i]->_cosin > theMinSmoothCosin )
2904         {
2905           SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2906           while ( fIt->more() && !eos._toSmooth )
2907           {
2908             const SMDS_MeshElement* face = fIt->next();
2909             if ( face->getshapeId() == eos._shapeID &&
2910                  getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2911             {
2912               eos._toSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2913             }
2914           }
2915         }
2916     }
2917     if ( eos._toSmooth )
2918     {
2919       for ( eExp.ReInit(); eExp.More(); eExp.Next() )
2920         edgesOfSmooFaces.Add( eExp.Current() );
2921
2922       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
2923     }
2924     data._nbShapesToSmooth += eos._toSmooth;
2925
2926   }  // check FACEs
2927
2928   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
2929   {
2930     _EdgesOnShape& eos = edgesByGeom[iS];
2931     eos._edgeSmoother = NULL;
2932     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
2933     if ( !eos._hyp.ToSmooth() ) continue;
2934
2935     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
2936     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2937       continue;
2938
2939     double tgtThick = eos._hyp.GetTotalThickness();
2940     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
2941     {
2942       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2943       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
2944       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
2945       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
2946       double angle    = eDir.Angle( eV[0]->_normal );
2947       double cosin    = Cos( angle );
2948       double cosinAbs = Abs( cosin );
2949       if ( cosinAbs > theMinSmoothCosin )
2950       {
2951         // always smooth analytic EDGEs
2952         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
2953         eos._toSmooth = ! curve.IsNull();
2954
2955         // compare tgtThick with the length of an end segment
2956         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2957         while ( eIt->more() && !eos._toSmooth )
2958         {
2959           const SMDS_MeshElement* endSeg = eIt->next();
2960           if ( endSeg->getshapeId() == (int) iS )
2961           {
2962             double segLen =
2963               SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2964             eos._toSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2965           }
2966         }
2967         if ( eos._toSmooth )
2968         {
2969           eos._edgeSmoother = new _Smoother1D( curve, eos );
2970
2971           for ( size_t i = 0; i < eos._edges.size(); ++i )
2972             eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
2973         }
2974       }
2975     }
2976     data._nbShapesToSmooth += eos._toSmooth;
2977
2978   } // check EDGEs
2979
2980   // Reset _cosin if no smooth is allowed by the user
2981   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2982   {
2983     _EdgesOnShape& eos = edgesByGeom[iS];
2984     if ( eos._edges.empty() ) continue;
2985
2986     if ( !eos._hyp.ToSmooth() )
2987       for ( size_t i = 0; i < eos._edges.size(); ++i )
2988         eos._edges[i]->SetCosin( 0 );
2989   }
2990
2991
2992   // Fill _eosC1 to make that C1 FACEs and EGDEs between them to be smoothed as a whole
2993
2994   TopTools_MapOfShape c1VV;
2995
2996   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
2997   {
2998     _EdgesOnShape& eos = edgesByGeom[iS];
2999     if ( eos._edges.empty() ||
3000          eos.ShapeType() != TopAbs_FACE ||
3001          !eos._toSmooth )
3002       continue;
3003
3004     // check EDGEs of a FACE
3005     TopTools_MapOfShape checkedEE, allVV;
3006     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3007     while ( !smQueue.empty() )
3008     {
3009       SMESH_subMesh* sm = smQueue.front();
3010       smQueue.pop_front();
3011       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3012       while ( smIt->more() )
3013       {
3014         sm = smIt->next();
3015         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3016           allVV.Add( sm->GetSubShape() );
3017         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3018              !checkedEE.Add( sm->GetSubShape() ))
3019           continue;
3020
3021         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3022         vector<_LayerEdge*>& eE = eoe->_edges;
3023         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3024           continue;
3025
3026         bool isC1 = true; // check continuity along an EDGE
3027         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3028           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3029         if ( !isC1 )
3030           continue;
3031
3032         // check that mesh faces are C1 as well
3033         {
3034           gp_XYZ norm1, norm2;
3035           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3036           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3037           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3038             continue;
3039           while ( fIt->more() && isC1 )
3040             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3041                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3042           if ( !isC1 )
3043             continue;
3044         }
3045
3046         // add the EDGE and an adjacent FACE to _eosC1
3047         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3048         while ( const TopoDS_Shape* face = fIt->next() )
3049         {
3050           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3051           if ( !eof ) continue; // other solid
3052           if ( !eos.HasC1( eoe ))
3053           {
3054             eos._eosC1.push_back( eoe );
3055             eoe->_toSmooth = false;
3056             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3057           }
3058           if ( eos._shapeID != eof->_shapeID && !eos.HasC1( eof )) 
3059           {
3060             eos._eosC1.push_back( eof );
3061             eof->_toSmooth = false;
3062             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3063             smQueue.push_back( eof->_subMesh );
3064           }
3065         }
3066       }
3067     }
3068     if ( eos._eosC1.empty() )
3069       continue;
3070
3071     // check VERTEXes of C1 FACEs
3072     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3073     for ( ; vIt.More(); vIt.Next() )
3074     {
3075       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3076       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3077         continue;
3078
3079       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3080       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3081       while ( const TopoDS_Shape* face = fIt->next() )
3082       {
3083         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3084         if ( !eof ) continue; // other solid
3085         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3086         if ( !isC1 )
3087           break;
3088       }
3089       if ( isC1 )
3090       {
3091         eos._eosC1.push_back( eov );
3092         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3093         c1VV.Add( eov->_shape );
3094       }
3095     }
3096
3097   } // fill _eosC1 of FACEs
3098
3099
3100   // Find C1 EDGEs
3101
3102   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3103
3104   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3105   {
3106     _EdgesOnShape& eov = edgesByGeom[iS];
3107     if ( eov._edges.empty() ||
3108          eov.ShapeType() != TopAbs_VERTEX ||
3109          c1VV.Contains( eov._shape ))
3110       continue;
3111     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3112
3113     // get directions of surrounding EDGEs
3114     dirOfEdges.clear();
3115     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3116     while ( const TopoDS_Shape* e = fIt->next() )
3117     {
3118       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3119       if ( !eoe ) continue; // other solid
3120       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3121       if ( !Precision::IsInfinite( eDir.X() ))
3122         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3123     }
3124
3125     // find EDGEs with C1 directions
3126     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3127       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3128         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3129         {
3130           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3131           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3132           if ( isC1 )
3133           {
3134             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3135             double eLen1 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[i].first->_shape ));
3136             double eLen2 = SMESH_Algo::EdgeLength( TopoDS::Edge( dirOfEdges[j].first->_shape ));
3137             if ( eLen1 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[i].first );
3138             if ( eLen2 < maxEdgeLen ) eov._eosC1.push_back( dirOfEdges[j].first );
3139             dirOfEdges[i].first = 0;
3140             dirOfEdges[j].first = 0;
3141           }
3142         }
3143   } // fill _eosC1 of VERTEXes
3144
3145
3146
3147   return ok;
3148 }
3149
3150 //================================================================================
3151 /*!
3152  * \brief initialize data of _EdgesOnShape
3153  */
3154 //================================================================================
3155
3156 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3157                                     SMESH_subMesh* sm,
3158                                     _SolidData&    data )
3159 {
3160   if ( !eos._shape.IsNull() ||
3161        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3162     return;
3163
3164   SMESH_MesherHelper helper( *_mesh );
3165
3166   eos._subMesh = sm;
3167   eos._shapeID = sm->GetId();
3168   eos._shape   = sm->GetSubShape();
3169   if ( eos.ShapeType() == TopAbs_FACE )
3170     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3171   eos._toSmooth = false;
3172   eos._data = &data;
3173
3174   // set _SWOL
3175   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3176     data._shrinkShape2Shape.find( eos._shapeID );
3177   if ( s2s != data._shrinkShape2Shape.end() )
3178     eos._sWOL = s2s->second;
3179
3180   eos._isRegularSWOL = true;
3181   if ( eos.SWOLType() == TopAbs_FACE )
3182   {
3183     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3184     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3185     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3186   }
3187
3188   // set _hyp
3189   if ( data._hyps.size() == 1 )
3190   {
3191     eos._hyp = data._hyps.back();
3192   }
3193   else
3194   {
3195     // compute average StdMeshers_ViscousLayers parameters
3196     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3197     if ( eos.ShapeType() == TopAbs_FACE )
3198     {
3199       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3200         eos._hyp = f2hyp->second;
3201     }
3202     else
3203     {
3204       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3205       while ( const TopoDS_Shape* face = fIt->next() )
3206       {
3207         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3208         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3209           eos._hyp.Add( f2hyp->second );
3210       }
3211     }
3212   }
3213
3214   // set _faceNormals
3215   if ( ! eos._hyp.UseSurfaceNormal() )
3216   {
3217     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3218     {
3219       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3220       eos._faceNormals.resize( smDS->NbElements() );
3221
3222       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3223       for ( int iF = 0; eIt->more(); ++iF )
3224       {
3225         const SMDS_MeshElement* face = eIt->next();
3226         if ( !SMESH_MeshAlgos::FaceNormal( face, eos._faceNormals[iF], /*normalized=*/true ))
3227           eos._faceNormals[iF].SetCoord( 0,0,0 );
3228       }
3229
3230       if ( !helper.IsReversedSubMesh( TopoDS::Face( eos._shape )))
3231         for ( size_t iF = 0; iF < eos._faceNormals.size(); ++iF )
3232           eos._faceNormals[iF].Reverse();
3233     }
3234     else // find EOS of adjacent FACEs
3235     {
3236       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3237       while ( const TopoDS_Shape* face = fIt->next() )
3238       {
3239         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3240         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3241         if ( eos._faceEOS.back()->_shape.IsNull() )
3242           // avoid using uninitialised _shapeID in GetNormal()
3243           eos._faceEOS.back()->_shapeID = faceID;
3244       }
3245     }
3246   }
3247 }
3248
3249 //================================================================================
3250 /*!
3251  * \brief Returns normal of a face
3252  */
3253 //================================================================================
3254
3255 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3256 {
3257   bool ok = false;
3258   const _EdgesOnShape* eos = 0;
3259
3260   if ( face->getshapeId() == _shapeID )
3261   {
3262     eos = this;
3263   }
3264   else
3265   {
3266     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3267       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3268         eos = _faceEOS[ iF ];
3269   }
3270
3271   if (( eos ) &&
3272       ( ok = ( face->getIdInShape() < (int) eos->_faceNormals.size() )))
3273   {
3274     norm = eos->_faceNormals[ face->getIdInShape() ];
3275   }
3276   else if ( !eos )
3277   {
3278     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3279               << " on _shape #" << _shapeID );
3280   }
3281   return ok;
3282 }
3283
3284
3285 //================================================================================
3286 /*!
3287  * \brief Set data of _LayerEdge needed for smoothing
3288  */
3289 //================================================================================
3290
3291 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3292                                   _EdgesOnShape&      eos,
3293                                   SMESH_MesherHelper& helper,
3294                                   _SolidData&         data)
3295 {
3296   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3297
3298   edge._len       = 0;
3299   edge._maxLen    = Precision::Infinite();
3300   edge._minAngle  = 0;
3301   edge._2neibors  = 0;
3302   edge._curvature = 0;
3303   edge._flags     = 0;
3304
3305   // --------------------------
3306   // Compute _normal and _cosin
3307   // --------------------------
3308
3309   edge._cosin     = 0;
3310   edge._lenFactor = 1.;
3311   edge._normal.SetCoord(0,0,0);
3312   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3313
3314   int totalNbFaces = 0;
3315   TopoDS_Face F;
3316   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3317   gp_Vec geomNorm;
3318   bool normOK = true;
3319
3320   const bool onShrinkShape = !eos._sWOL.IsNull();
3321   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3322                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3323
3324   // get geom FACEs the node lies on
3325   //if ( useGeometry )
3326   {
3327     set<TGeomID> faceIds;
3328     if  ( eos.ShapeType() == TopAbs_FACE )
3329     {
3330       faceIds.insert( eos._shapeID );
3331     }
3332     else
3333     {
3334       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3335       while ( fIt->more() )
3336         faceIds.insert( fIt->next()->getshapeId() );
3337     }
3338     set<TGeomID>::iterator id = faceIds.begin();
3339     for ( ; id != faceIds.end(); ++id )
3340     {
3341       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3342       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3343         continue;
3344       F = TopoDS::Face( s );
3345       face2Norm[ totalNbFaces ].first = F;
3346       totalNbFaces++;
3347     }
3348   }
3349
3350   // find _normal
3351   if ( useGeometry )
3352   {
3353     bool fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3354                       eos.SWOLType()  == TopAbs_FACE  &&
3355                       totalNbFaces > 1 );
3356
3357     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3358     {
3359       if ( eos.SWOLType() == TopAbs_EDGE )
3360       {
3361         // inflate from VERTEX along EDGE
3362         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3363       }
3364       else if ( eos.ShapeType() == TopAbs_VERTEX )
3365       {
3366         // inflate from VERTEX along FACE
3367         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3368                                    node, helper, normOK, &edge._cosin);
3369       }
3370       else
3371       {
3372         // inflate from EDGE along FACE
3373         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3374                                    node, helper, normOK);
3375       }
3376     }
3377     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3378     {
3379       if ( fromVonF )
3380         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3381
3382       int nbOkNorms = 0;
3383       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3384       {
3385         F = face2Norm[ iF ].first;
3386         geomNorm = getFaceNormal( node, F, helper, normOK );
3387         if ( !normOK ) continue;
3388         nbOkNorms++;
3389
3390         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3391           geomNorm.Reverse();
3392         face2Norm[ iF ].second = geomNorm.XYZ();
3393         edge._normal += geomNorm.XYZ();
3394       }
3395       if ( nbOkNorms == 0 )
3396         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3397
3398       if ( totalNbFaces >= 3 )
3399       {
3400         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3401       }
3402
3403       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3404       {
3405         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3406         edge._normal.SetCoord( 0,0,0 );
3407         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3408         {
3409           const TopoDS_Face& F = face2Norm[iF].first;
3410           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3411           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3412             geomNorm.Reverse();
3413           if ( normOK )
3414             face2Norm[ iF ].second = geomNorm.XYZ();
3415           edge._normal += face2Norm[ iF ].second;
3416         }
3417       }
3418     }
3419   }
3420   else // !useGeometry - get _normal using surrounding mesh faces
3421   {
3422     edge._normal = getWeigthedNormal( &edge );
3423
3424     // set<TGeomID> faceIds;
3425     //
3426     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3427     // while ( fIt->more() )
3428     // {
3429     //   const SMDS_MeshElement* face = fIt->next();
3430     //   if ( eos.GetNormal( face, geomNorm ))
3431     //   {
3432     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3433     //       continue; // use only one mesh face on FACE
3434     //     edge._normal += geomNorm.XYZ();
3435     //     totalNbFaces++;
3436     //   }
3437     // }
3438   }
3439
3440   // compute _cosin
3441   //if ( eos._hyp.UseSurfaceNormal() )
3442   {
3443     switch ( eos.ShapeType() )
3444     {
3445     case TopAbs_FACE: {
3446       edge._cosin = 0;
3447       break;
3448     }
3449     case TopAbs_EDGE: {
3450       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3451       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3452       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3453       edge._cosin      = Cos( angle );
3454       break;
3455     }
3456     case TopAbs_VERTEX: {
3457       //if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3458       {
3459         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3460         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3461         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3462         edge._cosin      = Cos( angle );
3463         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3464           for ( int iF = totalNbFaces-2; iF >=0; --iF )
3465           {
3466             F = face2Norm[ iF ].first;
3467             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3468             if ( normOK ) {
3469               double angle = inFaceDir.Angle( edge._normal );
3470               double cosin = Cos( angle );
3471               if ( Abs( cosin ) > Abs( edge._cosin ))
3472                 edge._cosin = cosin;
3473             }
3474           }
3475       }
3476       break;
3477     }
3478     default:
3479       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3480     }
3481   }
3482
3483   double normSize = edge._normal.SquareModulus();
3484   if ( normSize < numeric_limits<double>::min() )
3485     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3486
3487   edge._normal /= sqrt( normSize );
3488
3489   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3490   {
3491     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3492     edge._nodes.resize( 1 );
3493     edge._normal.SetCoord( 0,0,0 );
3494     edge._maxLen = 0;
3495   }
3496
3497   // Set the rest data
3498   // --------------------
3499
3500   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3501
3502   if ( onShrinkShape )
3503   {
3504     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3505     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3506       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
3507
3508     // set initial position which is parameters on _sWOL in this case
3509     if ( eos.SWOLType() == TopAbs_EDGE )
3510     {
3511       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3512       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3513       if ( edge._nodes.size() > 1 )
3514         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3515     }
3516     else // eos.SWOLType() == TopAbs_FACE
3517     {
3518       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3519       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3520       if ( edge._nodes.size() > 1 )
3521         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3522     }
3523
3524     if ( edge._nodes.size() > 1 )
3525     {
3526       // check if an angle between a FACE with layers and SWOL is sharp,
3527       // else the edge should not inflate
3528       F.Nullify();
3529       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3530         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3531           F = face2Norm[iF].first;
3532       if ( !F.IsNull())
3533       {
3534         geomNorm = getFaceNormal( node, F, helper, normOK );
3535         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3536           geomNorm.Reverse(); // inside the SOLID
3537         if ( geomNorm * edge._normal < -0.001 )
3538         {
3539           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3540           edge._nodes.resize( 1 );
3541         }
3542         else if ( edge._lenFactor > 3 )
3543         {
3544           edge._lenFactor = 2;
3545           edge.Set( _LayerEdge::RISKY_SWOL );
3546         }
3547       }
3548     }
3549   }
3550   else
3551   {
3552     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3553
3554     if ( eos.ShapeType() == TopAbs_FACE )
3555     {
3556       double angle;
3557       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3558       {
3559         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3560         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3561       }
3562     }
3563   }
3564
3565   // Set neighbor nodes for a _LayerEdge based on EDGE
3566
3567   if ( eos.ShapeType() == TopAbs_EDGE /*||
3568        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3569   {
3570     edge._2neibors = new _2NearEdges;
3571     // target nodes instead of source ones will be set later
3572   }
3573
3574   return true;
3575 }
3576
3577 //================================================================================
3578 /*!
3579  * \brief Return normal to a FACE at a node
3580  *  \param [in] n - node
3581  *  \param [in] face - FACE
3582  *  \param [in] helper - helper
3583  *  \param [out] isOK - true or false
3584  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3585  *  \return gp_XYZ - normal
3586  */
3587 //================================================================================
3588
3589 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3590                                       const TopoDS_Face&   face,
3591                                       SMESH_MesherHelper&  helper,
3592                                       bool&                isOK,
3593                                       bool                 shiftInside)
3594 {
3595   gp_XY uv;
3596   if ( shiftInside )
3597   {
3598     // get a shifted position
3599     gp_Pnt p = SMESH_TNodeXYZ( node );
3600     gp_XYZ shift( 0,0,0 );
3601     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3602     switch ( S.ShapeType() ) {
3603     case TopAbs_VERTEX:
3604     {
3605       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3606       break;
3607     }
3608     case TopAbs_EDGE:
3609     {
3610       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3611       break;
3612     }
3613     default:
3614       isOK = false;
3615     }
3616     if ( isOK )
3617       shift.Normalize();
3618     p.Translate( shift * 1e-5 );
3619
3620     TopLoc_Location loc;
3621     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3622
3623     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3624     
3625     projector.Perform( p );
3626     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3627     {
3628       isOK = false;
3629       return p.XYZ();
3630     }
3631     Quantity_Parameter U,V;
3632     projector.LowerDistanceParameters(U,V);
3633     uv.SetCoord( U,V );
3634   }
3635   else
3636   {
3637     uv = helper.GetNodeUV( face, node, 0, &isOK );
3638   }
3639
3640   gp_Dir normal;
3641   isOK = false;
3642
3643   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3644
3645   if ( !shiftInside &&
3646        helper.IsDegenShape( node->getshapeId() ) &&
3647        getFaceNormalAtSingularity( uv, face, helper, normal ))
3648   {
3649     isOK = true;
3650     return normal.XYZ();
3651   }
3652
3653   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3654   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3655
3656   if ( pointKind == IMPOSSIBLE &&
3657        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3658   {
3659     // probably NormEstim() failed due to a too high tolerance
3660     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3661     isOK = ( pointKind < IMPOSSIBLE );
3662   }
3663   if ( pointKind < IMPOSSIBLE )
3664   {
3665     if ( pointKind != REGULAR &&
3666          !shiftInside &&
3667          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3668     {
3669       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3670       if ( normShift * normal.XYZ() < 0. )
3671         normal = normShift;
3672     }
3673     isOK = true;
3674   }
3675
3676   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3677   {
3678     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3679
3680     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3681     while ( fIt->more() )
3682     {
3683       const SMDS_MeshElement* f = fIt->next();
3684       if ( f->getshapeId() == faceID )
3685       {
3686         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3687         if ( isOK )
3688         {
3689           TopoDS_Face ff = face;
3690           ff.Orientation( TopAbs_FORWARD );
3691           if ( helper.IsReversedSubMesh( ff ))
3692             normal.Reverse();
3693           break;
3694         }
3695       }
3696     }
3697   }
3698   return normal.XYZ();
3699 }
3700
3701 //================================================================================
3702 /*!
3703  * \brief Try to get normal at a singularity of a surface basing on it's nature
3704  */
3705 //================================================================================
3706
3707 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3708                                                   const TopoDS_Face&  face,
3709                                                   SMESH_MesherHelper& helper,
3710                                                   gp_Dir&             normal )
3711 {
3712   BRepAdaptor_Surface surface( face );
3713   gp_Dir axis;
3714   if ( !getRovolutionAxis( surface, axis ))
3715     return false;
3716
3717   double f,l, d, du, dv;
3718   f = surface.FirstUParameter();
3719   l = surface.LastUParameter();
3720   d = ( uv.X() - f ) / ( l - f );
3721   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3722   f = surface.FirstVParameter();
3723   l = surface.LastVParameter();
3724   d = ( uv.Y() - f ) / ( l - f );
3725   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3726
3727   gp_Dir refDir;
3728   gp_Pnt2d testUV = uv;
3729   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3730   double tol = 1e-5;
3731   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3732   for ( int iLoop = 0; true ; ++iLoop )
3733   {
3734     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3735     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3736       break;
3737     if ( iLoop > 20 )
3738       return false;
3739     tol /= 10.;
3740   }
3741
3742   if ( axis * refDir < 0. )
3743     axis.Reverse();
3744
3745   normal = axis;
3746
3747   return true;
3748 }
3749
3750 //================================================================================
3751 /*!
3752  * \brief Return a normal at a node weighted with angles taken by faces
3753  */
3754 //================================================================================
3755
3756 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
3757 {
3758   const SMDS_MeshNode* n = edge->_nodes[0];
3759
3760   gp_XYZ resNorm(0,0,0);
3761   SMESH_TNodeXYZ p0( n ), pP, pN;
3762   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3763   {
3764     pP.Set( edge->_simplices[i]._nPrev );
3765     pN.Set( edge->_simplices[i]._nNext );
3766     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
3767     double l0P = v0P.SquareMagnitude();
3768     double l0N = v0N.SquareMagnitude();
3769     double lPN = vPN.SquareMagnitude();
3770     if ( l0P < std::numeric_limits<double>::min() ||
3771          l0N < std::numeric_limits<double>::min() ||
3772          lPN < std::numeric_limits<double>::min() )
3773       continue;
3774     double lNorm = norm.SquareMagnitude();
3775     double  sin2 = lNorm / l0P / l0N;
3776     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
3777
3778     double weight = sin2 * angle / lPN;
3779     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
3780   }
3781
3782   return resNorm;
3783 }
3784
3785 //================================================================================
3786 /*!
3787  * \brief Return a normal at a node by getting a common point of offset planes
3788  *        defined by the FACE normals
3789  */
3790 //================================================================================
3791
3792 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
3793                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
3794                                            int                              nbFaces,
3795                                            bool                             lastNoOffset)
3796 {
3797   SMESH_TNodeXYZ p0 = edge->_nodes[0];
3798
3799   gp_XYZ resNorm(0,0,0);
3800   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
3801   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
3802   {
3803     for ( int i = 0; i < nbFaces; ++i )
3804       resNorm += f2Normal[i].second;
3805     return resNorm;
3806   }
3807
3808   // prepare _OffsetPlane's
3809   vector< _OffsetPlane > pln( nbFaces );
3810   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3811   {
3812     pln[i]._faceIndex = i;
3813     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
3814   }
3815   if ( lastNoOffset )
3816   {
3817     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
3818     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
3819   }
3820
3821   // intersect neighboring OffsetPlane's
3822   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
3823   while ( const TopoDS_Shape* edge = edgeIt->next() )
3824   {
3825     int f1 = -1, f2 = -1;
3826     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
3827       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
3828         (( f1 < 0 ) ? f1 : f2 ) = i;
3829
3830     if ( f2 >= 0 )
3831       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
3832   }
3833
3834   // get a common point
3835   gp_XYZ commonPnt( 0, 0, 0 );
3836   int nbPoints = 0;
3837   bool isPointFound;
3838   for ( int i = 0; i < nbFaces; ++i )
3839   {
3840     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
3841     nbPoints  += isPointFound;
3842   }
3843   gp_XYZ wgtNorm = getWeigthedNormal( edge );
3844   if ( nbPoints == 0 )
3845     return wgtNorm;
3846
3847   commonPnt /= nbPoints;
3848   resNorm = commonPnt - p0;
3849   if ( lastNoOffset )
3850     return resNorm;
3851
3852   // choose the best among resNorm and wgtNorm
3853   resNorm.Normalize();
3854   wgtNorm.Normalize();
3855   double resMinDot = std::numeric_limits<double>::max();
3856   double wgtMinDot = std::numeric_limits<double>::max();
3857   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
3858   {
3859     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
3860     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
3861   }
3862
3863   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
3864   {
3865     edge->Set( _LayerEdge::MULTI_NORMAL );
3866   }
3867
3868   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
3869 }
3870
3871 //================================================================================
3872 /*!
3873  * \brief Compute line of intersection of 2 planes
3874  */
3875 //================================================================================
3876
3877 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
3878                                             const TopoDS_Edge&   E,
3879                                             const TopoDS_Vertex& V )
3880 {
3881   int iNext = bool( _faceIndexNext[0] >= 0 );
3882   _faceIndexNext[ iNext ] = pln._faceIndex;
3883
3884   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
3885   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
3886
3887   gp_XYZ lineDir = n1 ^ n2;
3888
3889   double x = Abs( lineDir.X() );
3890   double y = Abs( lineDir.Y() );
3891   double z = Abs( lineDir.Z() );
3892
3893   int cooMax; // max coordinate
3894   if (x > y) {
3895     if (x > z) cooMax = 1;
3896     else       cooMax = 3;
3897   }
3898   else {
3899     if (y > z) cooMax = 2;
3900     else       cooMax = 3;
3901   }
3902
3903   gp_Pnt linePos;
3904   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
3905   {
3906     // parallel planes - intersection is an offset of the common EDGE
3907     gp_Pnt p = BRep_Tool::Pnt( V );
3908     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
3909     lineDir  = getEdgeDir( E, V );
3910   }
3911   else
3912   {
3913     // the constants in the 2 plane equations
3914     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
3915     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
3916
3917     switch ( cooMax ) {
3918     case 1:
3919       linePos.SetX(  0 );
3920       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
3921       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
3922       break;
3923     case 2:
3924       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
3925       linePos.SetY(  0 );
3926       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
3927       break;
3928     case 3:
3929       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
3930       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
3931       linePos.SetZ(  0 );
3932     }
3933   }
3934   gp_Lin& line = _lines[ iNext ];
3935   line.SetDirection( lineDir );
3936   line.SetLocation ( linePos );
3937
3938   _isLineOK[ iNext ] = true;
3939
3940
3941   iNext = bool( pln._faceIndexNext[0] >= 0 );
3942   pln._lines        [ iNext ] = line;
3943   pln._faceIndexNext[ iNext ] = this->_faceIndex;
3944   pln._isLineOK     [ iNext ] = true;
3945 }
3946
3947 //================================================================================
3948 /*!
3949  * \brief Computes intersection point of two _lines
3950  */
3951 //================================================================================
3952
3953 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
3954                                     const TopoDS_Vertex & V) const
3955 {
3956   gp_XYZ p( 0,0,0 );
3957   isFound = false;
3958
3959   if ( NbLines() == 2 )
3960   {
3961     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
3962     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
3963     if ( Abs( dot01 ) > 0.05 )
3964     {
3965       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
3966       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
3967       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
3968       isFound = true;
3969     }
3970     else
3971     {
3972       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
3973       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
3974       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
3975       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
3976       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
3977       isFound = true;
3978     }
3979   }
3980
3981   return p;
3982 }
3983
3984 //================================================================================
3985 /*!
3986  * \brief Find 2 neigbor nodes of a node on EDGE
3987  */
3988 //================================================================================
3989
3990 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3991                                         const SMDS_MeshNode*& n1,
3992                                         const SMDS_MeshNode*& n2,
3993                                         _EdgesOnShape&        eos,
3994                                         _SolidData&           data)
3995 {
3996   const SMDS_MeshNode* node = edge->_nodes[0];
3997   const int        shapeInd = eos._shapeID;
3998   SMESHDS_SubMesh*   edgeSM = 0;
3999   if ( eos.ShapeType() == TopAbs_EDGE )
4000   {
4001     edgeSM = eos._subMesh->GetSubMeshDS();
4002     if ( !edgeSM || edgeSM->NbElements() == 0 )
4003       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4004   }
4005   int iN = 0;
4006   n2 = 0;
4007   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4008   while ( eIt->more() && !n2 )
4009   {
4010     const SMDS_MeshElement* e = eIt->next();
4011     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4012     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4013     if ( edgeSM )
4014     {
4015       if (!edgeSM->Contains(e)) continue;
4016     }
4017     else
4018     {
4019       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4020       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4021     }
4022     ( iN++ ? n2 : n1 ) = nNeibor;
4023   }
4024   if ( !n2 )
4025     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4026   return true;
4027 }
4028
4029 //================================================================================
4030 /*!
4031  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
4032  */
4033 //================================================================================
4034
4035 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4036                                      const SMDS_MeshNode* n2,
4037                                      const _EdgesOnShape& eos,
4038                                      SMESH_MesherHelper&  helper)
4039 {
4040   if ( eos.ShapeType() != TopAbs_EDGE )
4041     return;
4042
4043   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4044   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4045   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4046
4047   // Set _curvature
4048
4049   double      sumLen = vec1.Modulus() + vec2.Modulus();
4050   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4051   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4052   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4053   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4054   if ( _curvature ) delete _curvature;
4055   _curvature = _Curvature::New( avgNormProj, avgLen );
4056   // if ( _curvature )
4057   //   debugMsg( _nodes[0]->GetID()
4058   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4059   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4060   //             << _curvature->lenDelta(0) );
4061
4062   // Set _plnNorm
4063
4064   if ( eos._sWOL.IsNull() )
4065   {
4066     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4067     // if ( SMESH_Algo::isDegenerated( E ))
4068     //   return;
4069     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4070     gp_XYZ plnNorm = dirE ^ _normal;
4071     double proj0   = plnNorm * vec1;
4072     double proj1   = plnNorm * vec2;
4073     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4074     {
4075       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4076       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4077     }
4078   }
4079 }
4080
4081 //================================================================================
4082 /*!
4083  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4084  * this and other _LayerEdge's are inflated along a FACE or an EDGE
4085  */
4086 //================================================================================
4087
4088 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4089                          _EdgesOnShape&      eos,
4090                          SMESH_MesherHelper& helper )
4091 {
4092   _nodes     = other._nodes;
4093   _normal    = other._normal;
4094   _len       = 0;
4095   _lenFactor = other._lenFactor;
4096   _cosin     = other._cosin;
4097   _2neibors  = other._2neibors;
4098   _curvature = 0; std::swap( _curvature, other._curvature );
4099   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
4100
4101   gp_XYZ lastPos( 0,0,0 );
4102   if ( eos.SWOLType() == TopAbs_EDGE )
4103   {
4104     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4105     _pos.push_back( gp_XYZ( u, 0, 0));
4106
4107     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4108     lastPos.SetX( u );
4109   }
4110   else // TopAbs_FACE
4111   {
4112     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4113     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4114
4115     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4116     lastPos.SetX( uv.X() );
4117     lastPos.SetY( uv.Y() );
4118   }
4119   return lastPos;
4120 }
4121
4122 //================================================================================
4123 /*!
4124  * \brief Set _cosin and _lenFactor
4125  */
4126 //================================================================================
4127
4128 void _LayerEdge::SetCosin( double cosin )
4129 {
4130   _cosin = cosin;
4131   cosin = Abs( _cosin );
4132   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4133   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4134 }
4135
4136 //================================================================================
4137 /*!
4138  * \brief Check if another _LayerEdge is a neighbor on EDGE
4139  */
4140 //================================================================================
4141
4142 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4143 {
4144   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4145           ( edge->_2neibors && edge->_2neibors->include( this )));
4146 }
4147
4148 //================================================================================
4149 /*!
4150  * \brief Fills a vector<_Simplex > 
4151  */
4152 //================================================================================
4153
4154 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4155                              vector<_Simplex>&    simplices,
4156                              const set<TGeomID>&  ingnoreShapes,
4157                              const _SolidData*    dataToCheckOri,
4158                              const bool           toSort)
4159 {
4160   simplices.clear();
4161   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4162   while ( fIt->more() )
4163   {
4164     const SMDS_MeshElement* f = fIt->next();
4165     const TGeomID    shapeInd = f->getshapeId();
4166     if ( ingnoreShapes.count( shapeInd )) continue;
4167     const int nbNodes = f->NbCornerNodes();
4168     const int  srcInd = f->GetNodeIndex( node );
4169     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4170     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4171     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4172     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4173       std::swap( nPrev, nNext );
4174     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4175   }
4176
4177   if ( toSort )
4178     SortSimplices( simplices );
4179 }
4180
4181 //================================================================================
4182 /*!
4183  * \brief Set neighbor simplices side by side
4184  */
4185 //================================================================================
4186
4187 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4188 {
4189   vector<_Simplex> sortedSimplices( simplices.size() );
4190   sortedSimplices[0] = simplices[0];
4191   size_t nbFound = 0;
4192   for ( size_t i = 1; i < simplices.size(); ++i )
4193   {
4194     for ( size_t j = 1; j < simplices.size(); ++j )
4195       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4196       {
4197         sortedSimplices[i] = simplices[j];
4198         nbFound++;
4199         break;
4200       }
4201   }
4202   if ( nbFound == simplices.size() - 1 )
4203     simplices.swap( sortedSimplices );
4204 }
4205
4206 //================================================================================
4207 /*!
4208  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
4209  */
4210 //================================================================================
4211
4212 void _ViscousBuilder::makeGroupOfLE()
4213 {
4214 #ifdef _DEBUG_
4215   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4216   {
4217     if ( _sdVec[i]._n2eMap.empty() ) continue;
4218
4219     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4220     TNode2Edge::iterator n2e;
4221     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4222     {
4223       _LayerEdge* le = n2e->second;
4224       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4225       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4226       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4227       if ( le ) {
4228         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4229                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4230       }
4231     }
4232     dumpFunctionEnd();
4233
4234     dumpFunction( SMESH_Comment("makeNormals") << i );
4235     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4236     {
4237       _LayerEdge* edge = n2e->second;
4238       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4239       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4240       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4241               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4242     }
4243     dumpFunctionEnd();
4244
4245     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4246     dumpCmd( "faceId1 = mesh.NbElements()" );
4247     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4248     for ( ; fExp.More(); fExp.Next() )
4249     {
4250       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4251       {
4252         if ( sm->NbElements() == 0 ) continue;
4253         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4254         while ( fIt->more())
4255         {
4256           const SMDS_MeshElement* e = fIt->next();
4257           SMESH_Comment cmd("mesh.AddFace([");
4258           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4259             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4260           dumpCmd( cmd );
4261         }
4262       }
4263     }
4264     dumpCmd( "faceId2 = mesh.NbElements()" );
4265     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4266              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4267              << "'%s-%s' % (faceId1+1, faceId2))");
4268     dumpFunctionEnd();
4269   }
4270 #endif
4271 }
4272
4273 //================================================================================
4274 /*!
4275  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4276  */
4277 //================================================================================
4278
4279 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4280 {
4281   data._geomSize = Precision::Infinite();
4282   double intersecDist;
4283   const SMDS_MeshElement* face;
4284   SMESH_MesherHelper helper( *_mesh );
4285
4286   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4287     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4288                                            data._proxyMesh->GetFaces( data._solid )));
4289
4290   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4291   {
4292     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4293     if ( eos._edges.empty() )
4294       continue;
4295     // get neighbor faces intersection with which should not be considered since
4296     // collisions are avoided by means of smoothing
4297     set< TGeomID > neighborFaces;
4298     if ( eos._hyp.ToSmooth() )
4299     {
4300       SMESH_subMeshIteratorPtr subIt =
4301         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4302       while ( subIt->more() )
4303       {
4304         SMESH_subMesh* sm = subIt->next();
4305         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4306         while ( const TopoDS_Shape* face = fIt->next() )
4307           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4308       }
4309     }
4310     // find intersections
4311     double thinkness = eos._hyp.GetTotalThickness();
4312     for ( size_t i = 0; i < eos._edges.size(); ++i )
4313     {
4314       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4315       eos._edges[i]->_maxLen = thinkness;
4316       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4317       if ( intersecDist > 0 && face )
4318       {
4319         data._geomSize = Min( data._geomSize, intersecDist );
4320         if ( !neighborFaces.count( face->getshapeId() ))
4321           eos._edges[i]->_maxLen = Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. ));
4322       }
4323     }
4324   }
4325 }
4326
4327 //================================================================================
4328 /*!
4329  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4330  */
4331 //================================================================================
4332
4333 bool _ViscousBuilder::inflate(_SolidData& data)
4334 {
4335   SMESH_MesherHelper helper( *_mesh );
4336
4337   // Limit inflation step size by geometry size found by itersecting
4338   // normals of _LayerEdge's with mesh faces
4339   if ( data._stepSize > 0.3 * data._geomSize )
4340     limitStepSize( data, 0.3 * data._geomSize );
4341
4342   const double tgtThick = data._maxThickness;
4343   if ( data._stepSize > data._minThickness )
4344     limitStepSize( data, data._minThickness );
4345
4346   if ( data._stepSize < 1. )
4347     data._epsilon = data._stepSize * 1e-7;
4348
4349   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4350
4351   findCollisionEdges( data, helper );
4352
4353   limitMaxLenByCurvature( data, helper );
4354
4355   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4356   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4357     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4358          data._edgesOnShape[i]._edges.size() > 0 &&
4359          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4360     {
4361       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4362       data._edgesOnShape[i]._edges[0]->Block( data );
4363     }
4364
4365   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4366
4367   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4368   int nbSteps = 0, nbRepeats = 0;
4369   while ( avgThick < 0.99 )
4370   {
4371     // new target length
4372     double prevThick = curThick;
4373     curThick += data._stepSize;
4374     if ( curThick > tgtThick )
4375     {
4376       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4377       nbRepeats++;
4378     }
4379
4380     double stepSize = curThick - prevThick;
4381     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4382
4383     // Elongate _LayerEdge's
4384     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4385     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4386     {
4387       _EdgesOnShape& eos = data._edgesOnShape[iS];
4388       if ( eos._edges.empty() ) continue;
4389
4390       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4391       for ( size_t i = 0; i < eos._edges.size(); ++i )
4392       {
4393         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4394       }
4395     }
4396     dumpFunctionEnd();
4397
4398     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4399       return false;
4400
4401     // Improve and check quality
4402     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4403     {
4404       if ( nbSteps > 0 )
4405       {
4406 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4407         debugMsg("NOT INVALIDATED STEP!");
4408         return error("Smoothing failed", data._index);
4409 #endif
4410         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4411         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4412         {
4413           _EdgesOnShape& eos = data._edgesOnShape[iS];
4414           for ( size_t i = 0; i < eos._edges.size(); ++i )
4415             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4416         }
4417         dumpFunctionEnd();
4418       }
4419       break; // no more inflating possible
4420     }
4421     nbSteps++;
4422
4423     // Evaluate achieved thickness
4424     avgThick = 0;
4425     int nbActiveEdges = 0;
4426     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4427     {
4428       _EdgesOnShape& eos = data._edgesOnShape[iS];
4429       if ( eos._edges.empty() ) continue;
4430
4431       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4432       for ( size_t i = 0; i < eos._edges.size(); ++i )
4433       {
4434         avgThick      += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4435         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4436       }
4437     }
4438     avgThick /= data._n2eMap.size();
4439     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4440
4441 #ifdef BLOCK_INFLATION
4442     if ( nbActiveEdges == 0 )
4443     {
4444       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4445       break;
4446     }
4447 #else
4448     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4449     {
4450       debugMsg( "-- Stop inflation since "
4451                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4452                 << tgtThick * avgThick << " ) * " << safeFactor );
4453       break;
4454     }
4455 #endif
4456     // new step size
4457     limitStepSize( data, 0.25 * distToIntersection );
4458     if ( data._stepSizeNodes[0] )
4459       data._stepSize = data._stepSizeCoeff *
4460         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4461
4462   } // while ( avgThick < 0.99 )
4463
4464   if ( nbSteps == 0 )
4465     return error("failed at the very first inflation step", data._index);
4466
4467   if ( avgThick < 0.99 )
4468   {
4469     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4470     {
4471       data._proxyMesh->_warning.reset
4472         ( new SMESH_ComputeError (COMPERR_WARNING,
4473                                   SMESH_Comment("Thickness ") << tgtThick <<
4474                                   " of viscous layers not reached,"
4475                                   " average reached thickness is " << avgThick*tgtThick));
4476     }
4477   }
4478
4479   // Restore position of src nodes moved by inflation on _noShrinkShapes
4480   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4481   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4482   {
4483     _EdgesOnShape& eos = data._edgesOnShape[iS];
4484     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4485       for ( size_t i = 0; i < eos._edges.size(); ++i )
4486       {
4487         restoreNoShrink( *eos._edges[ i ] );
4488       }
4489   }
4490   dumpFunctionEnd();
4491
4492   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4493 }
4494
4495 //================================================================================
4496 /*!
4497  * \brief Improve quality of layer inner surface and check intersection
4498  */
4499 //================================================================================
4500
4501 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4502                                      const int   infStep,
4503                                      double &    distToIntersection)
4504 {
4505   if ( data._nbShapesToSmooth == 0 )
4506     return true; // no shapes needing smoothing
4507
4508   bool moved, improved;
4509   double vol;
4510   vector< _LayerEdge* >    movedEdges, badEdges;
4511   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4512   vector< bool >           isConcaveFace;
4513
4514   SMESH_MesherHelper helper(*_mesh);
4515   Handle(ShapeAnalysis_Surface) surface;
4516   TopoDS_Face F;
4517
4518   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4519   {
4520     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4521
4522     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4523     {
4524       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4525       if ( !eos._toSmooth ||
4526            eos.ShapeType() != shapeType ||
4527            eos._edges.empty() )
4528         continue;
4529
4530       // already smoothed?
4531       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4532       // if ( !toSmooth ) continue;
4533
4534       if ( !eos._hyp.ToSmooth() )
4535       {
4536         // smooth disabled by the user; check validy only
4537         if ( !isFace ) continue;
4538         badEdges.clear();
4539         for ( size_t i = 0; i < eos._edges.size(); ++i )
4540         {
4541           _LayerEdge* edge = eos._edges[i];
4542           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4543             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4544             {
4545               // debugMsg( "-- Stop inflation. Bad simplex ("
4546               //           << " "<< edge->_nodes[0]->GetID()
4547               //           << " "<< edge->_nodes.back()->GetID()
4548               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4549               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4550               // return false;
4551               badEdges.push_back( edge );
4552             }
4553         }
4554         if ( !badEdges.empty() )
4555         {
4556           eosC1.resize(1);
4557           eosC1[0] = &eos;
4558           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4559           if ( nbBad > 0 )
4560             return false;
4561         }
4562         continue; // goto the next EDGE or FACE
4563       }
4564
4565       // prepare data
4566       if ( eos.SWOLType() == TopAbs_FACE )
4567       {
4568         if ( !F.IsSame( eos._sWOL )) {
4569           F = TopoDS::Face( eos._sWOL );
4570           helper.SetSubShape( F );
4571           surface = helper.GetSurface( F );
4572         }
4573       }
4574       else
4575       {
4576         F.Nullify(); surface.Nullify();
4577       }
4578       const TGeomID sInd = eos._shapeID;
4579
4580       // perform smoothing
4581
4582       if ( eos.ShapeType() == TopAbs_EDGE )
4583       {
4584         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4585
4586         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4587         {
4588           // smooth on EDGE's (normally we should not get here)
4589           int step = 0;
4590           do {
4591             moved = false;
4592             for ( size_t i = 0; i < eos._edges.size(); ++i )
4593             {
4594               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4595             }
4596             dumpCmd( SMESH_Comment("# end step ")<<step);
4597           }
4598           while ( moved && step++ < 5 );
4599         }
4600         dumpFunctionEnd();
4601       }
4602
4603       else // smooth on FACE
4604       {
4605         eosC1.clear();
4606         eosC1.push_back( & eos );
4607         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4608
4609         movedEdges.clear();
4610         isConcaveFace.resize( eosC1.size() );
4611         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4612         {
4613           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4614           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4615           for ( size_t i = 0; i < edges.size(); ++i )
4616             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4617                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4618               movedEdges.push_back( edges[i] );
4619
4620           makeOffsetSurface( *eosC1[ iEOS ], helper );
4621         }
4622
4623         int step = 0, stepLimit = 5, nbBad = 0;
4624         while (( ++step <= stepLimit ) || improved )
4625         {
4626           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4627                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4628           int oldBadNb = nbBad;
4629           badEdges.clear();
4630
4631 #ifdef INCREMENTAL_SMOOTH
4632           bool findBest = false; // ( step == stepLimit );
4633           for ( size_t i = 0; i < movedEdges.size(); ++i )
4634           {
4635             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4636             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4637               badEdges.push_back( movedEdges[i] );
4638           }
4639 #else
4640           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4641           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4642           {
4643             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4644             for ( size_t i = 0; i < edges.size(); ++i )
4645             {
4646               edges[i]->Unset( _LayerEdge::SMOOTHED );
4647               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4648                 badEdges.push_back( eos._edges[i] );
4649             }
4650           }
4651 #endif
4652           nbBad = badEdges.size();
4653
4654           if ( nbBad > 0 )
4655             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4656
4657           if ( !badEdges.empty() && step >= stepLimit / 2 )
4658           {
4659             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
4660               stepLimit = 9;
4661
4662             // resolve hard smoothing situation around concave VERTEXes
4663             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4664             {
4665               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
4666               for ( size_t i = 0; i < eosCoVe.size(); ++i )
4667                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
4668                                                          step, badEdges );
4669             }
4670             // look for the best smooth of _LayerEdge's neighboring badEdges
4671             nbBad = 0;
4672             for ( size_t i = 0; i < badEdges.size(); ++i )
4673             {
4674               _LayerEdge* ledge = badEdges[i];
4675               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
4676               {
4677                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
4678                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
4679               }
4680               ledge->Unset( _LayerEdge::SMOOTHED );
4681               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
4682             }
4683             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
4684           }
4685
4686           if ( nbBad == oldBadNb  &&
4687                nbBad > 0 &&
4688                step < stepLimit ) // smooth w/o chech of validity
4689           {
4690             dumpFunctionEnd();
4691             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
4692                          <<"_InfStep"<<infStep<<"_"<<step); // debug
4693             for ( size_t i = 0; i < movedEdges.size(); ++i )
4694             {
4695               movedEdges[i]->SmoothWoCheck();
4696             }
4697             if ( stepLimit < 9 )
4698               stepLimit++;
4699           }
4700
4701           improved = ( nbBad < oldBadNb );
4702
4703           dumpFunctionEnd();
4704
4705           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
4706             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4707             {
4708               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
4709             }
4710
4711         } // smoothing steps
4712
4713         // project -- to prevent intersections or fix bad simplices
4714         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4715         {
4716           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
4717             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
4718         }
4719
4720         //if ( !badEdges.empty() )
4721         {
4722           badEdges.clear();
4723           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4724           {
4725             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
4726             {
4727               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
4728
4729               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
4730               edge->CheckNeiborsOnBoundary( & badEdges );
4731               if (( nbBad > 0 ) ||
4732                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
4733               {
4734                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4735                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
4736                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4737                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4738                   {
4739                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
4740                              << " "<< tgtXYZ._node->GetID()
4741                              << " "<< edge->_simplices[j]._nPrev->GetID()
4742                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4743                     badEdges.push_back( edge );
4744                     break;
4745                   }
4746               }
4747             }
4748           }
4749
4750           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4751           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4752
4753           if ( nbBad > 0 )
4754             return false;
4755         }
4756
4757       } // // smooth on FACE's
4758     } // loop on shapes
4759   } // smooth on [ EDGEs, FACEs ]
4760
4761   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
4762   eosC1.resize(1);
4763   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4764   {
4765     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4766     if ( eos.ShapeType() == TopAbs_FACE ||
4767          eos._edges.empty() ||
4768          !eos._sWOL.IsNull() )
4769       continue;
4770
4771     badEdges.clear();
4772     for ( size_t i = 0; i < eos._edges.size(); ++i )
4773     {
4774       _LayerEdge*      edge = eos._edges[i];
4775       if ( edge->_nodes.size() < 2 ) continue;
4776       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
4777       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
4778       //const gp_XYZ& prevXYZ = edge->PrevPos();
4779       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4780         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
4781         {
4782           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
4783                    << " "<< tgtXYZ._node->GetID()
4784                    << " "<< edge->_simplices[j]._nPrev->GetID()
4785                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4786           badEdges.push_back( edge );
4787           break;
4788         }
4789     }
4790
4791     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4792     eosC1[0] = &eos;
4793     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4794     if ( nbBad > 0 )
4795       return false;
4796   }
4797
4798
4799   // Check if the last segments of _LayerEdge intersects 2D elements;
4800   // checked elements are either temporary faces or faces on surfaces w/o the layers
4801
4802   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4803     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4804                                            data._proxyMesh->GetFaces( data._solid )) );
4805
4806 #ifdef BLOCK_INFLATION
4807   const bool toBlockInfaltion = true;
4808 #else
4809   const bool toBlockInfaltion = false;
4810 #endif
4811   distToIntersection = Precision::Infinite();
4812   double dist;
4813   const SMDS_MeshElement* intFace = 0;
4814   const SMDS_MeshElement* closestFace = 0;
4815   _LayerEdge* le = 0;
4816   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4817   {
4818     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4819     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
4820       continue;
4821     for ( size_t i = 0; i < eos._edges.size(); ++i )
4822     {
4823       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
4824            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
4825         continue;
4826       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4827       {
4828         return false;
4829         // commented due to "Illegal hash-positionPosition" error in NETGEN
4830         // on Debian60 on viscous_layers_01/B2 case
4831         // Collision; try to deflate _LayerEdge's causing it
4832         // badEdges.clear();
4833         // badEdges.push_back( eos._edges[i] );
4834         // eosC1[0] = & eos;
4835         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4836         // if ( nbBad > 0 )
4837         //   return false;
4838
4839         // badEdges.clear();
4840         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4841         // {
4842         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4843         //   {
4844         //     const SMDS_MeshElement* srcFace =
4845         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4846         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4847         //     while ( nIt->more() )
4848         //     {
4849         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4850         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4851         //       if ( n2e != data._n2eMap.end() )
4852         //         badEdges.push_back( n2e->second );
4853         //     }
4854         //     eosC1[0] = eof;
4855         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4856         //     if ( nbBad > 0 )
4857         //       return false;
4858         //   }
4859         // }
4860         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
4861         //   return false;
4862         // else
4863         //   continue;
4864       }
4865       if ( !intFace )
4866       {
4867         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
4868         debugMsg( msg );
4869         continue;
4870       }
4871
4872       const bool isShorterDist = ( distToIntersection > dist );
4873       if ( toBlockInfaltion || isShorterDist )
4874       {
4875         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
4876         // lying on this _ConvexFace
4877         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
4878           if ( convFace->_subIdToEOS.count ( eos._shapeID ))
4879             continue;
4880
4881         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
4882         // ( avoid limiting the thickness on the case of issue 22576)
4883         if ( intFace->getshapeId() == eos._shapeID  )
4884           continue;
4885
4886         // ignore intersection with intFace of an adjacent FACE
4887         if ( dist > 0 )
4888         {
4889           bool toIgnore = false;
4890           if (  eos._edges[i]->Is( _LayerEdge::TO_SMOOTH ))
4891           {
4892             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
4893             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
4894             {
4895               TopExp_Explorer edge( eos._shape, TopAbs_EDGE );
4896               for ( ; !toIgnore && edge.More(); edge.Next() )
4897                 // is adjacent - has a common EDGE
4898                 toIgnore = ( helper.IsSubShape( edge.Current(), S ));
4899
4900               if ( toIgnore ) // check angle between normals
4901               {
4902                 gp_XYZ normal;
4903                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
4904                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
4905               }
4906             }
4907           }
4908           if ( !toIgnore ) // check if the edge is a neighbor of intFace
4909           {
4910             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
4911             {
4912               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
4913               toIgnore = ( nInd >= 0 );
4914             }
4915           }
4916           if ( toIgnore )
4917             continue;
4918         }
4919
4920         // intersection not ignored
4921
4922         if ( toBlockInfaltion &&
4923              dist < ( eos._edges[i]->_len * theThickToIntersection ))
4924         {
4925           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
4926           eos._edges[i]->Block( data );                  // not to inflate
4927
4928           if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
4929           {
4930             // block _LayerEdge's, on top of which intFace is
4931             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
4932             {
4933               const SMDS_MeshElement* srcFace =
4934                 eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
4935               SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
4936               while ( nIt->more() )
4937               {
4938                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
4939                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
4940                 if ( n2e != data._n2eMap.end() )
4941                   n2e->second->Block( data );
4942               }
4943             }
4944           }
4945         }
4946
4947         if ( isShorterDist )
4948         {
4949           distToIntersection = dist;
4950           le = eos._edges[i];
4951           closestFace = intFace;
4952         }
4953
4954       } // if ( toBlockInfaltion || isShorterDist )
4955     } // loop on eos._edges
4956   } // loop on data._edgesOnShape
4957
4958   if ( closestFace && le )
4959   {
4960 #ifdef __myDEBUG
4961     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
4962     cout << "Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
4963          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
4964          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4965          << ") distance = " << distToIntersection<< endl;
4966 #endif
4967   }
4968
4969   return true;
4970 }
4971
4972 //================================================================================
4973 /*!
4974  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
4975  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
4976  *  \return int - resulting nb of bad _LayerEdge's
4977  */
4978 //================================================================================
4979
4980 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
4981                                           SMESH_MesherHelper&       helper,
4982                                           vector< _LayerEdge* >&    badSmooEdges,
4983                                           vector< _EdgesOnShape* >& eosC1,
4984                                           const int                 infStep )
4985 {
4986   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
4987
4988   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
4989
4990   enum {
4991     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
4992     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
4993     ADDED         = _LayerEdge::UNUSED_FLAG * 4
4994   };
4995   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
4996
4997   double vol;
4998   bool haveInvalidated = true;
4999   while ( haveInvalidated )
5000   {
5001     haveInvalidated = false;
5002     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5003     {
5004       _LayerEdge*   edge = badSmooEdges[i];
5005       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5006       edge->Set( ADDED );
5007       bool invalidated = false;
5008       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5009       {
5010         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5011         edge->Block( data );
5012         edge->Set( INVALIDATED );
5013         edge->Unset( TO_INVALIDATE );
5014         invalidated = true;
5015         haveInvalidated = true;
5016       }
5017
5018       // look for _LayerEdge's of bad _simplices
5019       int nbBad = 0;
5020       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5021       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5022       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5023       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5024       {
5025         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5026             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5027           continue;
5028
5029         bool isBad = true;
5030         _LayerEdge* ee[2] = { 0,0 };
5031         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5032           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5033             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5034
5035         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5036         while ( maxNbSteps > edge->NbSteps() && isBad )
5037         {
5038           --maxNbSteps;
5039           for ( int iE = 0; iE < 2; ++iE )
5040           {
5041             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5042                  ee[ iE ]->NbSteps() > 1 )
5043             {
5044               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5045               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5046               ee[ iE ]->Block( data );
5047               ee[ iE ]->Set( INVALIDATED );
5048               haveInvalidated = true;
5049             }
5050           }
5051           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5052               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5053             isBad = false;
5054         }
5055         nbBad += isBad;
5056         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5057         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5058         ee[0]->Set( ADDED );
5059         ee[1]->Set( ADDED );
5060         if ( isBad )
5061         {
5062           ee[0]->Set( TO_INVALIDATE );
5063           ee[1]->Set( TO_INVALIDATE );
5064         }
5065       }
5066
5067       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5068       {
5069         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5070         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5071         edge->Block( data );
5072         edge->Set( INVALIDATED );
5073         edge->Unset( TO_INVALIDATE );
5074         haveInvalidated = true;
5075       }
5076     } // loop on badSmooEdges
5077   } // while ( haveInvalidated )
5078
5079   // re-smooth on analytical EDGEs
5080   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5081   {
5082     _LayerEdge* edge = badSmooEdges[i];
5083     if ( !edge->Is( INVALIDATED )) continue;
5084
5085     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5086     if ( eos->ShapeType() == TopAbs_VERTEX )
5087     {
5088       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5089       while ( const TopoDS_Shape* e = eIt->next() )
5090         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5091           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5092           {
5093             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5094             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5095             //   F       = TopoDS::Face( eoe->_sWOL );
5096             //   surface = helper.GetSurface( F );
5097             // }
5098             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5099             eoe->_edgeSmoother->_anaCurve.Nullify();
5100           }
5101     }
5102   }
5103
5104
5105   // check result of invalidation
5106
5107   int nbBad = 0;
5108   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5109   {
5110     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5111     {
5112       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5113       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5114       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5115       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5116       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5117         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5118         {
5119           ++nbBad;
5120           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5121                    << " "<< tgtXYZ._node->GetID()
5122                    << " "<< edge->_simplices[j]._nPrev->GetID()
5123                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5124         }
5125     }
5126   }
5127   dumpFunctionEnd();
5128
5129   return nbBad;
5130 }
5131
5132 //================================================================================
5133 /*!
5134  * \brief Create an offset surface
5135  */
5136 //================================================================================
5137
5138 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5139 {
5140   if ( eos._offsetSurf.IsNull() ||
5141        eos._edgeForOffset == 0 ||
5142        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5143     return;
5144
5145   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5146
5147   // find offset
5148   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5149   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5150   double offset = baseSurface->Gap();
5151
5152   eos._offsetSurf.Nullify();
5153
5154   try
5155   {
5156     BRepOffsetAPI_MakeOffsetShape offsetMaker( eos._shape, -offset, Precision::Confusion() );
5157     if ( !offsetMaker.IsDone() ) return;
5158
5159     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5160     if ( !fExp.More() ) return;
5161
5162     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5163     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5164     if ( surf.IsNull() ) return;
5165
5166     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5167   }
5168   catch ( Standard_Failure )
5169   {
5170   }
5171 }
5172
5173 //================================================================================
5174 /*!
5175  * \brief Put nodes of a curved FACE to its offset surface
5176  */
5177 //================================================================================
5178
5179 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5180                                           int                       infStep,
5181                                           vector< _EdgesOnShape* >& eosC1,
5182                                           int                       smooStep,
5183                                           bool                      moveAll )
5184 {
5185   _EdgesOnShape * eof = & eos;
5186   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5187   {
5188     eof = 0;
5189     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5190     {
5191       if ( eosC1[i]->_offsetSurf.IsNull() ||
5192            eosC1[i]->ShapeType() != TopAbs_FACE ||
5193            eosC1[i]->_edgeForOffset == 0 ||
5194            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5195         continue;
5196       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5197         eof = eosC1[i];
5198     }
5199   }
5200   if ( !eof ||
5201        eof->_offsetSurf.IsNull() ||
5202        eof->ShapeType() != TopAbs_FACE ||
5203        eof->_edgeForOffset == 0 ||
5204        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5205     return;
5206
5207   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5208   for ( size_t i = 0; i < eos._edges.size(); ++i )
5209   {
5210     _LayerEdge* edge = eos._edges[i];
5211     edge->Unset( _LayerEdge::MARKED );
5212     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5213       continue;
5214     if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5215         continue;
5216
5217     int nbBlockedAround = 0;
5218     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5219       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5220     if ( nbBlockedAround > 1 )
5221       continue;
5222
5223     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5224     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5225     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug 
5226     edge->_curvature->_uv = uv;
5227     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5228
5229     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5230     gp_XYZ prevP = edge->PrevCheckPos();
5231     bool      ok = true;
5232     if ( !moveAll )
5233       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5234       {
5235         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5236       }
5237     if ( ok )
5238     {
5239       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5240       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5241       edge->_pos.back() = newP;
5242
5243       edge->Set( _LayerEdge::MARKED );
5244     }
5245   }
5246
5247 #ifdef _DEBUG_
5248   // dumpMove() for debug
5249   size_t i = 0;
5250   for ( ; i < eos._edges.size(); ++i )
5251     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5252       break;
5253   if ( i < eos._edges.size() )
5254   {
5255     dumpFunction(SMESH_Comment("putOnOffsetSurface_F") << eos._shapeID
5256                  << "_InfStep" << infStep << "_" << smooStep );
5257     for ( ; i < eos._edges.size(); ++i )
5258     {
5259       if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5260         dumpMove( eos._edges[i]->_nodes.back() );
5261     }
5262     dumpFunctionEnd();
5263   }
5264 #endif
5265 }
5266
5267 //================================================================================
5268 /*!
5269  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5270  *        _LayerEdge's to be in a consequent order
5271  */
5272 //================================================================================
5273
5274 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5275                                                 _EdgesOnShape&      eos,
5276                                                 SMESH_MesherHelper& helper)
5277 {
5278   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5279
5280   TopLoc_Location loc; double f,l;
5281
5282   Handle(Geom_Line)   line;
5283   Handle(Geom_Circle) circle;
5284   bool isLine, isCirc;
5285   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5286   {
5287     // check if the EDGE is a line
5288     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5289     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5290       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5291
5292     line   = Handle(Geom_Line)::DownCast( curve );
5293     circle = Handle(Geom_Circle)::DownCast( curve );
5294     isLine = (!line.IsNull());
5295     isCirc = (!circle.IsNull());
5296
5297     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5298     {
5299       isLine = SMESH_Algo::IsStraight( E );
5300
5301       if ( isLine )
5302         line = new Geom_Line( gp::OX() ); // only type does matter
5303     }
5304     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5305     {
5306       // TODO
5307     }
5308   }
5309   else //////////////////////////////////////////////////////////////////////// 2D case
5310   {
5311     if ( !eos._isRegularSWOL ) // 23190
5312       return NULL;
5313
5314     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5315
5316     // check if the EDGE is a line
5317     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5318     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5319       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5320
5321     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5322     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5323     isLine = (!line2d.IsNull());
5324     isCirc = (!circle2d.IsNull());
5325
5326     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5327     {
5328       Bnd_B2d bndBox;
5329       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5330       while ( nIt->more() )
5331         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5332       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5333
5334       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5335       for ( int i = 0; i < 2 && !isLine; ++i )
5336         isLine = ( size.Coord( i+1 ) <= lineTol );
5337     }
5338     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5339     {
5340       // TODO
5341     }
5342     if ( isLine )
5343     {
5344       line = new Geom_Line( gp::OX() ); // only type does matter
5345     }
5346     else if ( isCirc )
5347     {
5348       gp_Pnt2d p = circle2d->Location();
5349       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5350       circle = new Geom_Circle( ax, 1.); // only center position does matter
5351     }
5352   }
5353
5354   if ( isLine )
5355     return line;
5356   if ( isCirc )
5357     return circle;
5358
5359   return Handle(Geom_Curve)();
5360 }
5361
5362 //================================================================================
5363 /*!
5364  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5365  */
5366 //================================================================================
5367
5368 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5369                                       Handle(ShapeAnalysis_Surface)& surface,
5370                                       const TopoDS_Face&             F,
5371                                       SMESH_MesherHelper&            helper)
5372 {
5373   if ( !isAnalytic() ) return false;
5374
5375   const size_t iFrom = 0, iTo = _eos._edges.size();
5376
5377   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5378   {
5379     if ( F.IsNull() ) // 3D
5380     {
5381       SMESH_TNodeXYZ p0   ( _eos._edges[iFrom]->_2neibors->tgtNode(0) );
5382       SMESH_TNodeXYZ p1   ( _eos._edges[iTo-1]->_2neibors->tgtNode(1) );
5383       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5384       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5385       gp_XYZ newPos, lineDir = pSrc1 - pSrc0;
5386       _LayerEdge* vLE0 = _eos._edges[iFrom]->_2neibors->_edges[0];
5387       _LayerEdge* vLE1 = _eos._edges[iTo-1]->_2neibors->_edges[1];
5388       bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5389                          vLE0->Is( _LayerEdge::BLOCKED ) ||
5390                          vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5391                          vLE1->Is( _LayerEdge::BLOCKED ));
5392       for ( size_t i = iFrom; i < iTo; ++i )
5393       {
5394         _LayerEdge*       edge = _eos._edges[i];
5395         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5396         newPos = p0 * ( 1. - _leParams[i] ) + p1 * _leParams[i];
5397
5398         if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5399         {
5400           gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5401           double  shift = ( lineDir * ( newPos - pSrc0 ) -
5402                             lineDir * ( curPos - pSrc0 ));
5403           newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5404         }
5405         if ( edge->Is( _LayerEdge::BLOCKED ))
5406         {
5407           SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5408           double curThick = pSrc.SquareDistance( tgtNode );
5409           double newThink = ( pSrc - newPos ).SquareModulus();
5410           if ( newThink > curThick )
5411             continue;
5412         }
5413         edge->_pos.back() = newPos;
5414         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5415         dumpMove( tgtNode );
5416       }
5417     }
5418     else // 2D
5419     {
5420       _LayerEdge* e0 = getLEdgeOnV( 0 );
5421       _LayerEdge* e1 = getLEdgeOnV( 1 );
5422       gp_XY uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ));
5423       gp_XY uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ));
5424       if ( e0->_nodes.back() == e1->_nodes.back() ) // closed edge
5425       {
5426         int iPeriodic = helper.GetPeriodicIndex();
5427         if ( iPeriodic == 1 || iPeriodic == 2 )
5428         {
5429           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
5430           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
5431             std::swap( uv0, uv1 );
5432         }
5433       }
5434       const gp_XY rangeUV = uv1 - uv0;
5435       for ( size_t i = iFrom; i < iTo; ++i )
5436       {
5437         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5438         gp_XY newUV = uv0 + _leParams[i] * rangeUV;
5439         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5440
5441         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5442         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5443         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5444         dumpMove( tgtNode );
5445
5446         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5447         pos->SetUParameter( newUV.X() );
5448         pos->SetVParameter( newUV.Y() );
5449       }
5450     }
5451     return true;
5452   }
5453
5454   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5455   {
5456     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5457     gp_Pnt center3D = circle->Location();
5458
5459     if ( F.IsNull() ) // 3D
5460     {
5461       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
5462         return true; // closed EDGE - nothing to do
5463
5464       // circle is a real curve of EDGE
5465       gp_Circ circ = circle->Circ();
5466
5467       // new center is shifted along its axis
5468       const gp_Dir& axis = circ.Axis().Direction();
5469       _LayerEdge*     e0 = getLEdgeOnV(0);
5470       _LayerEdge*     e1 = getLEdgeOnV(1);
5471       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
5472       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
5473       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
5474       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
5475       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
5476
5477       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
5478
5479       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
5480       gp_Circ newCirc( newAxis, newRadius );
5481       gp_Vec  vecC1  ( newCenter, p1 );
5482
5483       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
5484       if ( uLast < 0 )
5485         uLast += 2 * M_PI;
5486       
5487       for ( size_t i = iFrom; i < iTo; ++i )
5488       {
5489         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5490         double u = uLast * _leParams[i];
5491         gp_Pnt p = ElCLib::Value( u, newCirc );
5492         _eos._edges[i]->_pos.back() = p.XYZ();
5493
5494         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5495         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5496         dumpMove( tgtNode );
5497       }
5498       return true;
5499     }
5500     else // 2D
5501     {
5502       const gp_XY center( center3D.X(), center3D.Y() );
5503
5504       _LayerEdge* e0 = getLEdgeOnV(0);
5505       _LayerEdge* eM = _eos._edges[ 0 ];
5506       _LayerEdge* e1 = getLEdgeOnV(1);
5507       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
5508       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
5509       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
5510       gp_Vec2d vec0( center, uv0 );
5511       gp_Vec2d vecM( center, uvM );
5512       gp_Vec2d vec1( center, uv1 );
5513       double uLast = vec0.Angle( vec1 ); // -PI - +PI
5514       double uMidl = vec0.Angle( vecM );
5515       if ( uLast * uMidl <= 0. )
5516         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
5517       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
5518
5519       gp_Ax2d   axis( center, vec0 );
5520       gp_Circ2d circ( axis, radius );
5521       for ( size_t i = iFrom; i < iTo; ++i )
5522       {
5523         if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5524         double    newU = uLast * _leParams[i];
5525         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
5526         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
5527
5528         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5529         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5530         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5531         dumpMove( tgtNode );
5532
5533         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
5534         pos->SetUParameter( newUV.X() );
5535         pos->SetVParameter( newUV.Y() );
5536       }
5537     }
5538     return true;
5539   }
5540
5541   return false;
5542 }
5543
5544 //================================================================================
5545 /*!
5546  * \brief smooth _LayerEdge's on a an EDGE
5547  */
5548 //================================================================================
5549
5550 bool _Smoother1D::smoothComplexEdge( _SolidData&                    data,
5551                                      Handle(ShapeAnalysis_Surface)& surface,
5552                                      const TopoDS_Face&             F,
5553                                      SMESH_MesherHelper&            helper)
5554 {
5555   if ( _offPoints.empty() )
5556     return false;
5557
5558   // move _offPoints along normals of _LayerEdge's
5559
5560   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5561   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
5562     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
5563   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
5564     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
5565   _leOnV[0]._len = e[0]->_len;
5566   _leOnV[1]._len = e[1]->_len;
5567   for ( size_t i = 0; i < _offPoints.size(); i++ )
5568   {
5569     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5570     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5571     const double w0 = _offPoints[i]._2edges._wgt[0];
5572     const double w1 = _offPoints[i]._2edges._wgt[1];
5573     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
5574     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
5575     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
5576     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5577          e1->Is( _LayerEdge::NORMAL_UPDATED ))
5578       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
5579
5580     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
5581     _offPoints[i]._len  = avgLen;
5582   }
5583
5584   double fTol = 0;
5585   if ( !surface.IsNull() ) // project _offPoints to the FACE
5586   {
5587     fTol = 100 * BRep_Tool::Tolerance( F );
5588     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
5589
5590     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
5591     //if ( surface->Gap() < 0.5 * segLen )
5592       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
5593
5594     for ( size_t i = 1; i < _offPoints.size(); ++i )
5595     {
5596       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
5597       //if ( surface->Gap() < 0.5 * segLen )
5598         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
5599     }
5600   }
5601
5602   // project tgt nodes of extreme _LayerEdge's to the offset segments
5603
5604   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[0] = 0;
5605   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) _iSeg[1] = _offPoints.size()-2;
5606
5607   gp_Pnt pExtreme[2], pProj[2];
5608   for ( int is2nd = 0; is2nd < 2; ++is2nd )
5609   {
5610     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
5611     int  i = _iSeg[ is2nd ];
5612     int di = is2nd ? -1 : +1;
5613     bool projected = false;
5614     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
5615     int nbWorse = 0;
5616     do {
5617       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
5618       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
5619       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
5620       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
5621       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
5622       if ( dist < distMin || projected )
5623       {
5624         _iSeg[ is2nd ] = i;
5625         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
5626         distMin = dist;
5627       }
5628       else if ( dist > distPrev )
5629       {
5630         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
5631           break;
5632       }
5633       distPrev = dist;
5634       i += di;
5635     }
5636     while ( !projected &&
5637             i >= 0 && i+1 < (int)_offPoints.size() );
5638
5639     if ( !projected )
5640     {
5641       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
5642       {
5643         _iSeg[0] = 0;
5644         _iSeg[1] = _offPoints.size()-2;
5645         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
5646         return false;
5647       }
5648     }
5649   }
5650   if ( _iSeg[0] > _iSeg[1] )
5651   {
5652     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
5653     return false;
5654   }
5655
5656   // adjust length of extreme LE (test viscous_layers_01/B7)
5657   gp_Vec vDiv0( pExtreme[0], pProj[0] );
5658   gp_Vec vDiv1( pExtreme[1], pProj[1] );
5659   double d0 = vDiv0.Magnitude();
5660   double d1 = vDiv1.Magnitude();
5661   if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
5662   else                                   e[0]->_len -= d0;
5663   if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
5664   else                                   e[1]->_len -= d1;
5665
5666   // compute normalized length of the offset segments located between the projections
5667
5668   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
5669   vector< double > len( nbSeg + 1 );
5670   len[ iSeg++ ] = 0;
5671   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz )/* * e[0]->_lenFactor*/;
5672   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
5673   {
5674     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
5675   }
5676   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz )/* * e[1]->_lenFactor*/;
5677
5678   // d0 *= e[0]->_lenFactor;
5679   // d1 *= e[1]->_lenFactor;
5680   double fullLen = len.back() - d0 - d1;
5681   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
5682     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
5683
5684   // temporary replace extreme _offPoints by pExtreme
5685   gp_XYZ op[2] = { _offPoints[ _iSeg[0]   ]._xyz,
5686                    _offPoints[ _iSeg[1]+1 ]._xyz };
5687   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
5688   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
5689
5690   // distribute tgt nodes of _LayerEdge's between the projections
5691
5692   iSeg = 0;
5693   for ( size_t i = 0; i < _eos._edges.size(); ++i )
5694   {
5695     if ( _eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
5696     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
5697       iSeg++;
5698     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
5699     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
5700                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
5701
5702     if ( surface.IsNull() )
5703     {
5704       _eos._edges[i]->_pos.back() = p;
5705     }
5706     else // project a new node position to a FACE
5707     {
5708       gp_Pnt2d uv ( _eos._edges[i]->_pos.back().X(), _eos._edges[i]->_pos.back().Y() );
5709       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
5710
5711       p = surface->Value( uv2 ).XYZ();
5712       _eos._edges[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
5713     }
5714     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
5715     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
5716     dumpMove( tgtNode );
5717   }
5718
5719   _offPoints[ _iSeg[0]   ]._xyz = op[0];
5720   _offPoints[ _iSeg[1]+1 ]._xyz = op[1];
5721
5722   return true;
5723 }
5724
5725 //================================================================================
5726 /*!
5727  * \brief Prepare for smoothing
5728  */
5729 //================================================================================
5730
5731 void _Smoother1D::prepare(_SolidData& data)
5732 {
5733   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
5734   _curveLen = SMESH_Algo::EdgeLength( E );
5735
5736   // sort _LayerEdge's by position on the EDGE
5737   data.SortOnEdge( E, _eos._edges );
5738
5739   // compute normalized param of _eos._edges on EDGE
5740   _leParams.resize( _eos._edges.size() + 1 );
5741   {
5742     double curLen;
5743     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
5744     _leParams[0] = 0;
5745     for ( size_t i = 0; i < _eos._edges.size(); ++i )
5746     {
5747       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
5748       curLen         = p.Distance( pPrev );
5749       _leParams[i+1] = _leParams[i] + curLen;
5750       pPrev          = p;
5751     }
5752     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
5753     for ( size_t i = 0; i < _leParams.size()-1; ++i )
5754       _leParams[i] = _leParams[i+1] / fullLen;
5755   }
5756
5757   if ( isAnalytic() )
5758     return;
5759
5760   // divide E to have offset segments with low deflection
5761   BRepAdaptor_Curve c3dAdaptor( E );
5762   const double curDeflect = 0.1; //0.3; // 0.01; // Curvature deflection
5763   const double angDeflect = 0.1; //0.2; // 0.09; // Angular deflection
5764   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
5765   if ( discret.NbPoints() <= 2 )
5766   {
5767     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
5768     return;
5769   }
5770
5771   const double u0 = c3dAdaptor.FirstParameter();
5772   gp_Pnt p; gp_Vec tangent;
5773   _offPoints.resize( discret.NbPoints() );
5774   for ( size_t i = 0; i < _offPoints.size(); i++ )
5775   {
5776     double u = discret.Parameter( i+1 );
5777     c3dAdaptor.D1( u, p, tangent );
5778     _offPoints[i]._xyz     = p.XYZ();
5779     _offPoints[i]._edgeDir = tangent.XYZ();
5780     _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
5781   }
5782
5783   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5784
5785   // set _2edges
5786   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
5787   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
5788   _2NearEdges tmp2edges;
5789   tmp2edges._edges[1] = _eos._edges[0];
5790   _leOnV[0]._2neibors = & tmp2edges;
5791   _leOnV[0]._nodes    = leOnV[0]->_nodes;
5792   _leOnV[1]._nodes    = leOnV[1]->_nodes;
5793   _LayerEdge* eNext, *ePrev = & _leOnV[0];
5794   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
5795   {
5796     // find _LayerEdge's located before and after an offset point
5797     // (_eos._edges[ iLE ] is next after ePrev)
5798     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
5799       ePrev = _eos._edges[ iLE++ ];
5800     eNext = ePrev->_2neibors->_edges[1];
5801
5802     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
5803     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
5804     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
5805     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
5806   }
5807
5808   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
5809   for ( size_t i = 0; i < _offPoints.size(); i++ )
5810     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
5811       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
5812     else break;
5813   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
5814     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
5815       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
5816     else break;
5817
5818   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
5819
5820   int iLBO = _offPoints.size() - 2; // last but one
5821
5822   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
5823   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
5824
5825   _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal, _edgeDir[0] );
5826   _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal, _edgeDir[1] );
5827   _leOnV[ 0 ]._len = 0;
5828   _leOnV[ 1 ]._len = 0;
5829   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
5830   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
5831
5832   _iSeg[0] = 0;
5833   _iSeg[1] = _offPoints.size()-2;
5834
5835   // initialize OffPnt::_len
5836   for ( size_t i = 0; i < _offPoints.size(); ++i )
5837     _offPoints[i]._len = 0;
5838
5839   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
5840   {
5841     _leOnV[0]._len = leOnV[0]->_len;
5842     _leOnV[1]._len = leOnV[1]->_len;
5843     for ( size_t i = 0; i < _offPoints.size(); i++ )
5844     {
5845       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
5846       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
5847       const double w0 = _offPoints[i]._2edges._wgt[0];
5848       const double w1 = _offPoints[i]._2edges._wgt[1];
5849       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
5850       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
5851                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
5852       _offPoints[i]._xyz = avgXYZ;
5853       _offPoints[i]._len = avgLen;
5854     }
5855   }
5856 }
5857
5858 //================================================================================
5859 /*!
5860  * \brief set _normal of _leOnV[is2nd] to be normal to the EDGE
5861  */
5862 //================================================================================
5863
5864 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
5865                                      const gp_XYZ&  edgeDir)
5866 {
5867   gp_XYZ cross = normal ^ edgeDir;
5868   gp_XYZ  norm = edgeDir ^ cross;
5869   double  size = norm.Modulus();
5870
5871   return norm / size;
5872 }
5873
5874 //================================================================================
5875 /*!
5876  * \brief Sort _LayerEdge's by a parameter on a given EDGE
5877  */
5878 //================================================================================
5879
5880 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
5881                              vector< _LayerEdge* >& edges)
5882 {
5883   map< double, _LayerEdge* > u2edge;
5884   for ( size_t i = 0; i < edges.size(); ++i )
5885     u2edge.insert( u2edge.end(),
5886                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
5887
5888   ASSERT( u2edge.size() == edges.size() );
5889   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
5890   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
5891     edges[i] = u2e->second;
5892
5893   Sort2NeiborsOnEdge( edges );
5894 }
5895
5896 //================================================================================
5897 /*!
5898  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
5899  */
5900 //================================================================================
5901
5902 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
5903 {
5904   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
5905
5906   for ( size_t i = 0; i < edges.size()-1; ++i )
5907     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
5908       edges[i]->_2neibors->reverse();
5909
5910   const size_t iLast = edges.size() - 1;
5911   if ( edges.size() > 1 &&
5912        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
5913     edges[iLast]->_2neibors->reverse();
5914 }
5915
5916 //================================================================================
5917 /*!
5918  * \brief Return _EdgesOnShape* corresponding to the shape
5919  */
5920 //================================================================================
5921
5922 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
5923 {
5924   if ( shapeID < (int)_edgesOnShape.size() &&
5925        _edgesOnShape[ shapeID ]._shapeID == shapeID )
5926     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
5927
5928   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
5929     if ( _edgesOnShape[i]._shapeID == shapeID )
5930       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
5931
5932   return 0;
5933 }
5934
5935 //================================================================================
5936 /*!
5937  * \brief Return _EdgesOnShape* corresponding to the shape
5938  */
5939 //================================================================================
5940
5941 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
5942 {
5943   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
5944   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
5945 }
5946
5947 //================================================================================
5948 /*!
5949  * \brief Prepare data of the _LayerEdge for smoothing on FACE
5950  */
5951 //================================================================================
5952
5953 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
5954 {
5955   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
5956
5957   set< TGeomID > vertices;
5958   TopoDS_Face F;
5959   if ( eos->ShapeType() == TopAbs_FACE )
5960   {
5961     // check FACE concavity and get concave VERTEXes
5962     F = TopoDS::Face( eos->_shape );
5963     if ( isConcave( F, helper, &vertices ))
5964       _concaveFaces.insert( eos->_shapeID );
5965
5966     // set eos._eosConcaVer
5967     eos->_eosConcaVer.clear();
5968     eos->_eosConcaVer.reserve( vertices.size() );
5969     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
5970     {
5971       _EdgesOnShape* eov = GetShapeEdges( *v );
5972       if ( eov && eov->_edges.size() == 1 )
5973       {
5974         eos->_eosConcaVer.push_back( eov );
5975         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
5976           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
5977       }
5978     }
5979
5980     // SetSmooLen() to _LayerEdge's on FACE
5981     for ( size_t i = 0; i < eos->_edges.size(); ++i )
5982     {
5983       eos->_edges[i]->SetSmooLen( Precision::Infinite() );
5984     }
5985     SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
5986     while ( smIt->more() ) // loop on sub-shapes of the FACE
5987     {
5988       _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
5989       if ( !eoe ) continue;
5990
5991       vector<_LayerEdge*>& eE = eoe->_edges;
5992       for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
5993       {
5994         if ( eE[iE]->_cosin <= theMinSmoothCosin )
5995           continue;
5996
5997         SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
5998         while ( segIt->more() )
5999         {
6000           const SMDS_MeshElement* seg = segIt->next();
6001           if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6002             continue;
6003           if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6004             continue; // not to check a seg twice
6005           for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6006           {
6007             _LayerEdge* eN = eE[iE]->_neibors[iN];
6008             if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6009               continue;
6010             double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6011             double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6012             eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6013             eN->Set( _LayerEdge::NEAR_BOUNDARY );
6014           }
6015         }
6016       }
6017     }
6018   } // if ( eos->ShapeType() == TopAbs_FACE )
6019
6020   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6021   {
6022     eos->_edges[i]->_smooFunction = 0;
6023     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6024   }
6025   bool isCurved = false;
6026   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6027   {
6028     _LayerEdge* edge = eos->_edges[i];
6029
6030     // get simplices sorted
6031     _Simplex::SortSimplices( edge->_simplices );
6032
6033     // smoothing function
6034     edge->ChooseSmooFunction( vertices, _n2eMap );
6035
6036     // set _curvature
6037     double avgNormProj = 0, avgLen = 0;
6038     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6039     {
6040       _Simplex& s = edge->_simplices[iS];
6041
6042       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6043       avgNormProj += edge->_normal * vec;
6044       avgLen      += vec.Modulus();
6045       if ( substituteSrcNodes )
6046       {
6047         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6048         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6049       }
6050     }
6051     avgNormProj /= edge->_simplices.size();
6052     avgLen      /= edge->_simplices.size();
6053     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6054     {
6055       isCurved = true;
6056       SMDS_FacePosition* fPos = dynamic_cast<SMDS_FacePosition*>( edge->_nodes[0]->GetPosition() );
6057       if ( !fPos )
6058         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6059           fPos = dynamic_cast<SMDS_FacePosition*>( edge->_simplices[iS]._nPrev->GetPosition() );
6060       if ( fPos )
6061         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6062     }
6063   }
6064
6065   // prepare for putOnOffsetSurface()
6066   if (( eos->ShapeType() == TopAbs_FACE ) &&
6067       ( isCurved || !eos->_eosConcaVer.empty() ))
6068   {
6069     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6070     eos->_edgeForOffset = 0;
6071
6072     double maxCosin = -1;
6073     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6074     {
6075       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6076       if ( !eoe || eoe->_edges.empty() ) continue;
6077
6078       vector<_LayerEdge*>& eE = eoe->_edges;
6079       _LayerEdge* e = eE[ eE.size() / 2 ];
6080       if ( e->_cosin > maxCosin )
6081       {
6082         eos->_edgeForOffset = e;
6083         maxCosin = e->_cosin;
6084       }
6085     }
6086   }
6087 }
6088
6089 //================================================================================
6090 /*!
6091  * \brief Add faces for smoothing
6092  */
6093 //================================================================================
6094
6095 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6096                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6097 {
6098   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6099   for ( ; eos != eosToSmooth.end(); ++eos )
6100   {
6101     if ( !*eos || (*eos)->_toSmooth ) continue;
6102
6103     (*eos)->_toSmooth = true;
6104
6105     if ( (*eos)->ShapeType() == TopAbs_FACE )
6106     {
6107       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6108       (*eos)->_toSmooth = true;
6109     }
6110   }
6111
6112   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6113   if ( edgesNoAnaSmooth )
6114     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6115     {
6116       if ( (*eos)->_edgeSmoother )
6117         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6118     }
6119 }
6120
6121 //================================================================================
6122 /*!
6123  * \brief Limit _LayerEdge::_maxLen according to local curvature
6124  */
6125 //================================================================================
6126
6127 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper )
6128 {
6129   // find intersection of neighbor _LayerEdge's to limit _maxLen
6130   // according to local curvature (IPAL52648)
6131
6132   // This method must be called after findCollisionEdges() where _LayerEdge's
6133   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6134
6135   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6136   {
6137     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6138     if ( eosI._edges.empty() ) continue;
6139     if ( !eosI._hyp.ToSmooth() )
6140     {
6141       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6142       {
6143         _LayerEdge* eI = eosI._edges[i];
6144         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6145         {
6146           _LayerEdge* eN = eI->_neibors[iN];
6147           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6148           {
6149             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6150             limitMaxLenByCurvature( eI, eN, eosI, *eosN, helper );
6151           }
6152         }
6153       }
6154     }
6155     else if ( eosI.ShapeType() == TopAbs_EDGE )
6156     {
6157       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6158       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6159
6160       _LayerEdge* e0 = eosI._edges[0];
6161       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6162       {
6163         _LayerEdge* eI = eosI._edges[i];
6164         limitMaxLenByCurvature( eI, e0, eosI, eosI, helper );
6165         e0 = eI;
6166       }
6167     }
6168   }
6169 }
6170
6171 //================================================================================
6172 /*!
6173  * \brief Limit _LayerEdge::_maxLen according to local curvature
6174  */
6175 //================================================================================
6176
6177 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*         e1,
6178                                               _LayerEdge*         e2,
6179                                               _EdgesOnShape&      eos1,
6180                                               _EdgesOnShape&      eos2,
6181                                               SMESH_MesherHelper& helper )
6182 {
6183   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6184   double norSize = plnNorm.SquareModulus();
6185   if ( norSize < std::numeric_limits<double>::min() )
6186     return; // parallel normals
6187
6188   // find closest points of skew _LayerEdge's
6189   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6190   gp_XYZ dir12 = src2 - src1;
6191   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6192   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6193   double  dot1 = perp2 * e1->_normal;
6194   double  dot2 = perp1 * e2->_normal;
6195   double    u1 =   ( perp2 * dir12 ) / dot1;
6196   double    u2 = - ( perp1 * dir12 ) / dot2;
6197   if ( u1 > 0 && u2 > 0 )
6198   {
6199     double ovl = ( u1 * e1->_normal * dir12 -
6200                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6201     if ( ovl > theSmoothThickToElemSizeRatio )
6202     {    
6203       e1->_maxLen = Min( e1->_maxLen, 0.75 * u1 / e1->_lenFactor );
6204       e2->_maxLen = Min( e2->_maxLen, 0.75 * u2 / e2->_lenFactor );
6205     }
6206   }
6207 }
6208
6209 //================================================================================
6210 /*!
6211  * \brief Fill data._collisionEdges
6212  */
6213 //================================================================================
6214
6215 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6216 {
6217   data._collisionEdges.clear();
6218
6219   // set the full thickness of the layers to LEs
6220   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6221   {
6222     _EdgesOnShape& eos = data._edgesOnShape[iS];
6223     if ( eos._edges.empty() ) continue;
6224     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6225
6226     for ( size_t i = 0; i < eos._edges.size(); ++i )
6227     {
6228       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6229       double maxLen = eos._edges[i]->_maxLen;
6230       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6231       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6232       eos._edges[i]->_maxLen = maxLen;
6233     }
6234   }
6235
6236   // make temporary quadrangles got by extrusion of
6237   // mesh edges along _LayerEdge._normal's
6238
6239   vector< const SMDS_MeshElement* > tmpFaces;
6240
6241   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6242   {
6243     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6244     if ( eos.ShapeType() != TopAbs_EDGE )
6245       continue;
6246     if ( eos._edges.empty() )
6247     {
6248       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6249       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6250       while ( smIt->more() )
6251         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6252           if ( eov->_edges.size() == 1 )
6253             edge[ bool( edge[0]) ] = eov->_edges[0];
6254
6255       if ( edge[1] )
6256       {
6257         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6258         tmpFaces.push_back( f );
6259       }
6260     }
6261     for ( size_t i = 0; i < eos._edges.size(); ++i )
6262     {
6263       _LayerEdge* edge = eos._edges[i];
6264       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6265       {
6266         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6267         if ( src2->GetPosition()->GetDim() > 0 &&
6268              src2->GetID() < edge->_nodes[0]->GetID() )
6269           continue; // avoid using same segment twice
6270
6271         // a _LayerEdge containg tgt2
6272         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6273
6274         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6275         tmpFaces.push_back( f );
6276       }
6277     }
6278   }
6279
6280   // Find _LayerEdge's intersecting tmpFaces.
6281
6282   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6283                                                             tmpFaces.end()));
6284   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6285     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6286
6287   double dist1, dist2, segLen, eps = 0.5;
6288   _CollisionEdges collEdges;
6289   vector< const SMDS_MeshElement* > suspectFaces;
6290   const double angle45 = Cos( 45. * M_PI / 180. );
6291
6292   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6293   {
6294     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6295     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6296       continue;
6297     // find sub-shapes whose VL can influence VL on eos
6298     set< TGeomID > neighborShapes;
6299     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6300     while ( const TopoDS_Shape* face = fIt->next() )
6301     {
6302       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6303       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6304       {
6305         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6306         while ( subIt->more() )
6307           neighborShapes.insert( subIt->next()->GetId() );
6308       }
6309     }
6310     if ( eos.ShapeType() == TopAbs_VERTEX )
6311     {
6312       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6313       while ( const TopoDS_Shape* edge = eIt->next() )
6314         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6315     }
6316     // find intersecting _LayerEdge's
6317     for ( size_t i = 0; i < eos._edges.size(); ++i )
6318     {
6319       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6320       _LayerEdge*   edge = eos._edges[i];
6321       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6322       segLen *= 1.2;
6323
6324       gp_Vec eSegDir0, eSegDir1;
6325       if ( edge->IsOnEdge() )
6326       {
6327         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6328         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6329         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6330       }
6331       suspectFaces.clear();
6332       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6333                                      SMDSAbs_Face, suspectFaces );
6334       collEdges._intEdges.clear();
6335       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6336       {
6337         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6338         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6339         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6340         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6341         if ( edge->IsOnEdge() ) {
6342           if ( edge->_2neibors->include( f->_le1 ) ||
6343                edge->_2neibors->include( f->_le2 )) continue;
6344         }
6345         else {
6346           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6347               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6348         }
6349         dist1 = dist2 = Precision::Infinite();
6350         if ( !edge->SegTriaInter( lastSegment, f->_nn[0], f->_nn[1], f->_nn[2], dist1, eps ))
6351           dist1 = Precision::Infinite();
6352         if ( !edge->SegTriaInter( lastSegment, f->_nn[3], f->_nn[2], f->_nn[0], dist2, eps ))
6353           dist2 = Precision::Infinite();
6354         if (( dist1 > segLen ) && ( dist2 > segLen ))
6355           continue;
6356
6357         if ( edge->IsOnEdge() )
6358         {
6359           // skip perpendicular EDGEs
6360           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->_nn[0] ) - SMESH_TNodeXYZ( f->_nn[3] );
6361           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6362                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6363                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6364                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6365           if ( !isParallel )
6366             continue;
6367         }
6368
6369         // either limit inflation of edges or remember them for updating _normal
6370         // double dot = edge->_normal * f->GetDir();
6371         // if ( dot > 0.1 )
6372         {
6373           collEdges._intEdges.push_back( f->_le1 );
6374           collEdges._intEdges.push_back( f->_le2 );
6375         }
6376         // else
6377         // {
6378         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
6379         //   edge->_maxLen = Min( shortLen, edge->_maxLen );
6380         // }
6381       }
6382
6383       if ( !collEdges._intEdges.empty() )
6384       {
6385         collEdges._edge = edge;
6386         data._collisionEdges.push_back( collEdges );
6387       }
6388     }
6389   }
6390
6391   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
6392     delete tmpFaces[i];
6393
6394   // restore the zero thickness
6395   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6396   {
6397     _EdgesOnShape& eos = data._edgesOnShape[iS];
6398     if ( eos._edges.empty() ) continue;
6399     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6400
6401     for ( size_t i = 0; i < eos._edges.size(); ++i )
6402     {
6403       eos._edges[i]->InvalidateStep( 1, eos );
6404       eos._edges[i]->_len = 0;
6405     }
6406   }
6407 }
6408
6409 //================================================================================
6410 /*!
6411  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
6412  * _LayerEdge's on neighbor EDGE's
6413  */
6414 //================================================================================
6415
6416 bool _ViscousBuilder::updateNormals( _SolidData&         data,
6417                                      SMESH_MesherHelper& helper,
6418                                      int                 stepNb,
6419                                      double              stepSize)
6420 {
6421   updateNormalsOfC1Vertices( data );
6422
6423   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
6424     return false;
6425
6426   // map to store new _normal and _cosin for each intersected edge
6427   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
6428   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
6429   _LayerEdge zeroEdge;
6430   zeroEdge._normal.SetCoord( 0,0,0 );
6431   zeroEdge._maxLen = Precision::Infinite();
6432   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
6433
6434   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
6435
6436   double segLen, dist1, dist2, dist;
6437   vector< pair< _LayerEdge*, double > > intEdgesDist;
6438   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
6439
6440   for ( int iter = 0; iter < 5; ++iter )
6441   {
6442     edge2newEdge.clear();
6443
6444     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
6445     {
6446       _CollisionEdges& ce = data._collisionEdges[iE];
6447       _LayerEdge*   edge1 = ce._edge;
6448       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
6449       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6450       if ( !eos1 ) continue;
6451
6452       // detect intersections
6453       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
6454       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
6455       double     eps = 0.5;
6456       intEdgesDist.clear();
6457       double minIntDist = Precision::Infinite();
6458       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
6459       {
6460         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6461              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
6462              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
6463           continue;
6464         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
6465         double fact = ( 1.1 + dot * dot );
6466         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
6467         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
6468         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
6469         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
6470         dist1 = dist2 = Precision::Infinite();
6471         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
6472              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
6473           continue;
6474         dist = dist1;
6475         if ( dist > testLen || dist <= 0 )
6476         {
6477           dist = dist2;
6478           if ( dist > testLen || dist <= 0 )
6479             continue;
6480         }
6481         // choose a closest edge
6482         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
6483         double d1 = intP.SquareDistance( pSrc0 );
6484         double d2 = intP.SquareDistance( pSrc1 );
6485         int iClose = i + ( d2 < d1 );
6486         _LayerEdge* edge2 = ce._intEdges[iClose];
6487         edge2->Unset( _LayerEdge::MARKED );
6488
6489         // choose a closest edge among neighbors
6490         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
6491         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
6492         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
6493         {
6494           _LayerEdge * edgeJ = intEdgesDist[j].first;
6495           if ( edge2->IsNeiborOnEdge( edgeJ ))
6496           {
6497             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
6498             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
6499           }
6500         }
6501         intEdgesDist.push_back( make_pair( edge2, dist ));
6502         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
6503         // {
6504         //   iClose = i + !( d2 < d1 );
6505         //   intEdges.push_back( ce._intEdges[iClose] );
6506         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
6507         // }
6508         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
6509       }
6510
6511       //ce._edge = 0;
6512
6513       // compute new _normals
6514       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
6515       {
6516         _LayerEdge* edge2    = intEdgesDist[i].first;
6517         double       distWgt = edge1->_len / intEdgesDist[i].second;
6518         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
6519         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
6520         if ( edge2->Is( _LayerEdge::MARKED )) continue;
6521         edge2->Set( _LayerEdge::MARKED );
6522
6523         // get a new normal
6524         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
6525
6526         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
6527         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6528         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
6529         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
6530         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
6531         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6532         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
6533         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
6534         newNormal.Normalize();
6535
6536         // get new cosin
6537         double newCos;
6538         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
6539         if ( cos1 < theMinSmoothCosin )
6540         {
6541           newCos = cos2 * sgn1;
6542         }
6543         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
6544         {
6545           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
6546         }
6547         else
6548         {
6549           newCos = edge1->_cosin;
6550         }
6551
6552         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
6553         e2neIt->second._normal += distWgt * newNormal;
6554         e2neIt->second._cosin   = newCos;
6555         e2neIt->second._maxLen  = 0.7 * minIntDist / edge1->_lenFactor;
6556         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
6557           e2neIt->second._normal += dir2;
6558         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
6559         e2neIt->second._normal += distWgt * newNormal;
6560         e2neIt->second._cosin   = edge2->_cosin;
6561         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
6562           e2neIt->second._normal += dir1;
6563       }
6564     }
6565
6566     if ( edge2newEdge.empty() )
6567       break; //return true;
6568
6569     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
6570
6571     // Update data of edges depending on a new _normal
6572
6573     data.UnmarkEdges();
6574     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6575     {
6576       _LayerEdge*    edge = e2neIt->first;
6577       if ( edge->Is( _LayerEdge::BLOCKED )) continue;
6578       _LayerEdge& newEdge = e2neIt->second;
6579       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
6580
6581       // Check if a new _normal is OK:
6582       newEdge._normal.Normalize();
6583       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
6584       {
6585         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
6586         {
6587           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6588           edge->_maxLen = newEdge._maxLen;
6589           edge->SetNewLength( newEdge._maxLen, *eos, helper );
6590         }
6591         continue; // the new _normal is bad
6592       }
6593       // the new _normal is OK
6594
6595       // find shapes that need smoothing due to change of _normal
6596       if ( edge->_cosin   < theMinSmoothCosin &&
6597            newEdge._cosin > theMinSmoothCosin )
6598       {
6599         if ( eos->_sWOL.IsNull() )
6600         {
6601           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
6602           while ( fIt->more() )
6603             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
6604         }
6605         else // edge inflates along a FACE
6606         {
6607           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
6608           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
6609           while ( const TopoDS_Shape* E = eIt->next() )
6610           {
6611             if ( !helper.IsSubShape( *E, /*FACE=*/eos->_sWOL ))
6612               continue;
6613             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
6614             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
6615             if ( angle < M_PI / 2 )
6616               shapesToSmooth.insert( data.GetShapeEdges( *E ));
6617           }
6618         }
6619       }
6620
6621       double len = edge->_len;
6622       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6623       edge->SetNormal( newEdge._normal );
6624       edge->SetCosin( newEdge._cosin );
6625       edge->SetNewLength( len, *eos, helper );
6626       edge->Set( _LayerEdge::MARKED );
6627       edge->Set( _LayerEdge::NORMAL_UPDATED );
6628       edgesNoAnaSmooth.insert( eos );
6629     }
6630
6631     // Update normals and other dependent data of not intersecting _LayerEdge's
6632     // neighboring the intersecting ones
6633
6634     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
6635     {
6636       _LayerEdge*   edge1 = e2neIt->first;
6637       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
6638       if ( !edge1->Is( _LayerEdge::MARKED ))
6639         continue;
6640
6641       if ( edge1->IsOnEdge() )
6642       {
6643         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
6644         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
6645         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
6646       }
6647
6648       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
6649         continue;
6650       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
6651       {
6652         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
6653         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
6654           continue; // j-th neighbor is also intersected
6655         _LayerEdge* prevEdge = edge1;
6656         const int nbSteps = 10;
6657         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
6658         {
6659           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
6660                neighbor->Is( _LayerEdge::MARKED ))
6661             break;
6662           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
6663           if ( !eos ) continue;
6664           _LayerEdge* nextEdge = neighbor;
6665           if ( neighbor->_2neibors )
6666           {
6667             int iNext = 0;
6668             nextEdge = neighbor->_2neibors->_edges[iNext];
6669             if ( nextEdge == prevEdge )
6670               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
6671           }
6672           double r = double(step-1)/nbSteps/(iter+1);
6673           if ( !nextEdge->_2neibors )
6674             r = Min( r, 0.5 );
6675
6676           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
6677           newNorm.Normalize();
6678           if ( !isNewNormalOk( data, *neighbor, newNorm ))
6679             break;
6680
6681           double len = neighbor->_len;
6682           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
6683           neighbor->SetNormal( newNorm );
6684           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
6685           if ( neighbor->_2neibors )
6686             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
6687           neighbor->SetNewLength( len, *eos, helper );
6688           neighbor->Set( _LayerEdge::MARKED );
6689           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
6690           edgesNoAnaSmooth.insert( eos );
6691
6692           if ( !neighbor->_2neibors )
6693             break; // neighbor is on VERTEX
6694
6695           // goto the next neighbor
6696           prevEdge = neighbor;
6697           neighbor = nextEdge;
6698         }
6699       }
6700     }
6701     dumpFunctionEnd();
6702   } // iterations
6703
6704   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
6705
6706   return true;
6707 }
6708
6709 //================================================================================
6710 /*!
6711  * \brief Check if a new normal is OK
6712  */
6713 //================================================================================
6714
6715 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
6716                                      _LayerEdge&   edge,
6717                                      const gp_XYZ& newNormal)
6718 {
6719   // check a min angle between the newNormal and surrounding faces
6720   vector<_Simplex> simplices;
6721   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
6722   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
6723   double newMinDot = 1, curMinDot = 1;
6724   for ( size_t i = 0; i < simplices.size(); ++i )
6725   {
6726     n1.Set( simplices[i]._nPrev );
6727     n2.Set( simplices[i]._nNext );
6728     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
6729     double normLen2 = normFace.SquareModulus();
6730     if ( normLen2 < std::numeric_limits<double>::min() )
6731       continue;
6732     normFace /= Sqrt( normLen2 );
6733     newMinDot = Min( newNormal    * normFace, newMinDot );
6734     curMinDot = Min( edge._normal * normFace, curMinDot );
6735   }
6736   bool ok = true;
6737   if ( newMinDot < 0.5 )
6738   {
6739     ok = ( newMinDot >= curMinDot * 0.9 );
6740     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
6741     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
6742     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
6743   }
6744
6745   return ok;
6746 }
6747
6748 //================================================================================
6749 /*!
6750  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
6751  */
6752 //================================================================================
6753
6754 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
6755                                                SMESH_MesherHelper& helper,
6756                                                const int           nbSteps,
6757                                                const double        stepSize )
6758 {
6759   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
6760     return true; // no shapes needing smoothing
6761
6762   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6763   {
6764     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6765     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
6766          !eos._hyp.ToSmooth() ||
6767          eos.ShapeType() != TopAbs_FACE ||
6768          eos._edges.empty() )
6769       continue;
6770
6771     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
6772     if ( !toSmooth ) continue;
6773
6774     for ( size_t i = 0; i < eos._edges.size(); ++i )
6775     {
6776       _LayerEdge* edge = eos._edges[i];
6777       if ( !edge->Is( _LayerEdge::SMOOTHED ))
6778         continue;
6779       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
6780         continue;
6781
6782       const gp_XYZ& pPrev = edge->PrevPos();
6783       const gp_XYZ& pLast = edge->_pos.back();
6784       gp_XYZ      stepVec = pLast - pPrev;
6785       double realStepSize = stepVec.Modulus();
6786       if ( realStepSize < numeric_limits<double>::min() )
6787         continue;
6788
6789       edge->_lenFactor = realStepSize / stepSize;
6790       edge->_normal    = stepVec / realStepSize;
6791       edge->Set( _LayerEdge::NORMAL_UPDATED );
6792     }
6793   }
6794
6795   return true;
6796 }
6797
6798 //================================================================================
6799 /*!
6800  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
6801  */
6802 //================================================================================
6803
6804 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
6805 {
6806   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6807   {
6808     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
6809     if ( eov._eosC1.empty() ||
6810          eov.ShapeType() != TopAbs_VERTEX ||
6811          eov._edges.empty() )
6812       continue;
6813
6814     gp_XYZ newNorm   = eov._edges[0]->_normal;
6815     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
6816     bool normChanged = false;
6817
6818     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
6819     {
6820       _EdgesOnShape*   eoe = eov._eosC1[i];
6821       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
6822       const double    eLen = SMESH_Algo::EdgeLength( e );
6823       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
6824       if ( oppV.IsSame( eov._shape ))
6825         oppV = SMESH_MesherHelper::IthVertex( 1, e );
6826       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
6827       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
6828       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
6829
6830       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
6831       if ( curThickOpp + curThick < eLen )
6832         continue;
6833
6834       double wgt = 2. * curThick / eLen;
6835       newNorm += wgt * eovOpp->_edges[0]->_normal;
6836       normChanged = true;
6837     }
6838     if ( normChanged )
6839     {
6840       eov._edges[0]->SetNormal( newNorm.Normalized() );
6841       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
6842     }
6843   }
6844 }
6845
6846 //================================================================================
6847 /*!
6848  * \brief Modify normals of _LayerEdge's on _ConvexFace's
6849  */
6850 //================================================================================
6851
6852 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
6853                                                   SMESH_MesherHelper& helper,
6854                                                   int                 stepNb )
6855 {
6856   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
6857   bool isOK;
6858
6859   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
6860   for ( ; id2face != data._convexFaces.end(); ++id2face )
6861   {
6862     _ConvexFace & convFace = (*id2face).second;
6863     if ( convFace._normalsFixed )
6864       continue; // already fixed
6865     if ( convFace.CheckPrisms() )
6866       continue; // nothing to fix
6867
6868     convFace._normalsFixed = true;
6869
6870     BRepAdaptor_Surface surface ( convFace._face, false );
6871     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
6872
6873     // check if the convex FACE is of spherical shape
6874
6875     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
6876     Bnd_B3d nodesBox;
6877     gp_Pnt  center;
6878
6879     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
6880     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6881     {
6882       _EdgesOnShape& eos = *(id2eos->second);
6883       if ( eos.ShapeType() == TopAbs_VERTEX )
6884       {
6885         _LayerEdge* ledge = eos._edges[ 0 ];
6886         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
6887           centersBox.Add( center );
6888       }
6889       for ( size_t i = 0; i < eos._edges.size(); ++i )
6890         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
6891     }
6892     if ( centersBox.IsVoid() )
6893     {
6894       debugMsg( "Error: centersBox.IsVoid()" );
6895       return false;
6896     }
6897     const bool isSpherical =
6898       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
6899
6900     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
6901     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
6902
6903     if ( isSpherical )
6904     {
6905       // set _LayerEdge::_normal as average of all normals
6906
6907       // WARNING: different density of nodes on EDGEs is not taken into account that
6908       // can lead to an improper new normal
6909
6910       gp_XYZ avgNormal( 0,0,0 );
6911       nbEdges = 0;
6912       id2eos = convFace._subIdToEOS.begin();
6913       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6914       {
6915         _EdgesOnShape& eos = *(id2eos->second);
6916         // set data of _CentralCurveOnEdge
6917         if ( eos.ShapeType() == TopAbs_EDGE )
6918         {
6919           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
6920           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
6921           if ( !eos._sWOL.IsNull() )
6922             ceCurve._adjFace.Nullify();
6923           else
6924             ceCurve._ledges.insert( ceCurve._ledges.end(),
6925                                     eos._edges.begin(), eos._edges.end());
6926         }
6927         // summarize normals
6928         for ( size_t i = 0; i < eos._edges.size(); ++i )
6929           avgNormal += eos._edges[ i ]->_normal;
6930       }
6931       double normSize = avgNormal.SquareModulus();
6932       if ( normSize < 1e-200 )
6933       {
6934         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
6935         return false;
6936       }
6937       avgNormal /= Sqrt( normSize );
6938
6939       // compute new _LayerEdge::_cosin on EDGEs
6940       double avgCosin = 0;
6941       int     nbCosin = 0;
6942       gp_Vec inFaceDir;
6943       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
6944       {
6945         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
6946         if ( ceCurve._adjFace.IsNull() )
6947           continue;
6948         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
6949         {
6950           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
6951           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
6952           if ( isOK )
6953           {
6954             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
6955             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
6956             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
6957             nbCosin++;
6958           }
6959         }
6960       }
6961       if ( nbCosin > 0 )
6962         avgCosin /= nbCosin;
6963
6964       // set _LayerEdge::_normal = avgNormal
6965       id2eos = convFace._subIdToEOS.begin();
6966       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
6967       {
6968         _EdgesOnShape& eos = *(id2eos->second);
6969         if ( eos.ShapeType() != TopAbs_EDGE )
6970           for ( size_t i = 0; i < eos._edges.size(); ++i )
6971             eos._edges[ i ]->_cosin = avgCosin;
6972
6973         for ( size_t i = 0; i < eos._edges.size(); ++i )
6974         {
6975           eos._edges[ i ]->SetNormal( avgNormal );
6976           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
6977         }
6978       }
6979     }
6980     else // if ( isSpherical )
6981     {
6982       // We suppose that centers of curvature at all points of the FACE
6983       // lie on some curve, let's call it "central curve". For all _LayerEdge's
6984       // having a common center of curvature we define the same new normal
6985       // as a sum of normals of _LayerEdge's on EDGEs among them.
6986
6987       // get all centers of curvature for each EDGE
6988
6989       helper.SetSubShape( convFace._face );
6990       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
6991
6992       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
6993       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
6994       {
6995         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
6996
6997         // set adjacent FACE
6998         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
6999
7000         // get _LayerEdge's of the EDGE
7001         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7002         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7003         if ( !eos || eos->_edges.empty() )
7004         {
7005           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7006           for ( int iV = 0; iV < 2; ++iV )
7007           {
7008             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7009             TGeomID     vID = meshDS->ShapeToIndex( v );
7010             eos = data.GetShapeEdges( vID );
7011             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7012           }
7013           edgeLEdge    = &vertexLEdges[0];
7014           edgeLEdgeEnd = edgeLEdge + 2;
7015
7016           centerCurves[ iE ]._adjFace.Nullify();
7017         }
7018         else
7019         {
7020           if ( ! eos->_toSmooth )
7021             data.SortOnEdge( edge, eos->_edges );
7022           edgeLEdge    = &eos->_edges[ 0 ];
7023           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7024           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7025           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7026
7027           if ( ! eos->_sWOL.IsNull() )
7028             centerCurves[ iE ]._adjFace.Nullify();
7029         }
7030
7031         // Get curvature centers
7032
7033         centersBox.Clear();
7034
7035         if ( edgeLEdge[0]->IsOnEdge() &&
7036              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7037         { // 1st VERTEX
7038           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7039           centersBox.Add( center );
7040         }
7041         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7042           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7043           { // EDGE or VERTEXes
7044             centerCurves[ iE ].Append( center, *edgeLEdge );
7045             centersBox.Add( center );
7046           }
7047         if ( edgeLEdge[-1]->IsOnEdge() &&
7048              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7049         { // 2nd VERTEX
7050           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7051           centersBox.Add( center );
7052         }
7053         centerCurves[ iE ]._isDegenerated =
7054           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7055
7056       } // loop on EDGES of convFace._face to set up data of centerCurves
7057
7058       // Compute new normals for _LayerEdge's on EDGEs
7059
7060       double avgCosin = 0;
7061       int     nbCosin = 0;
7062       gp_Vec inFaceDir;
7063       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7064       {
7065         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7066         if ( ceCurve._isDegenerated )
7067           continue;
7068         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7069         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7070         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7071         {
7072           isOK = false;
7073           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7074           {
7075             if ( iE1 != iE2 )
7076               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7077           }
7078           if ( isOK && !ceCurve._adjFace.IsNull() )
7079           {
7080             // compute new _LayerEdge::_cosin
7081             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7082             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7083             if ( isOK )
7084             {
7085               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7086               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7087               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7088               nbCosin++;
7089             }
7090           }
7091         }
7092       }
7093       // set new normals to _LayerEdge's of NOT degenerated central curves
7094       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7095       {
7096         if ( centerCurves[ iE ]._isDegenerated )
7097           continue;
7098         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7099         {
7100           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7101           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7102         }
7103       }
7104       // set new normals to _LayerEdge's of     degenerated central curves
7105       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7106       {
7107         if ( !centerCurves[ iE ]._isDegenerated ||
7108              centerCurves[ iE ]._ledges.size() < 3 )
7109           continue;
7110         // new normal is an average of new normals at VERTEXes that
7111         // was computed on non-degenerated _CentralCurveOnEdge's
7112         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7113                            centerCurves[ iE ]._ledges.back ()->_normal );
7114         double sz = newNorm.Modulus();
7115         if ( sz < 1e-200 )
7116           continue;
7117         newNorm /= sz;
7118         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7119                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7120         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7121         {
7122           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7123           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7124           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7125         }
7126       }
7127
7128       // Find new normals for _LayerEdge's based on FACE
7129
7130       if ( nbCosin > 0 )
7131         avgCosin /= nbCosin;
7132       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7133       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7134       if ( id2eos != convFace._subIdToEOS.end() )
7135       {
7136         int iE = 0;
7137         gp_XYZ newNorm;
7138         _EdgesOnShape& eos = * ( id2eos->second );
7139         for ( size_t i = 0; i < eos._edges.size(); ++i )
7140         {
7141           _LayerEdge* ledge = eos._edges[ i ];
7142           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7143             continue;
7144           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7145           {
7146             iE = iE % centerCurves.size();
7147             if ( centerCurves[ iE ]._isDegenerated )
7148               continue;
7149             newNorm.SetCoord( 0,0,0 );
7150             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7151             {
7152               ledge->SetNormal( newNorm );
7153               ledge->_cosin  = avgCosin;
7154               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7155               break;
7156             }
7157           }
7158         }
7159       }
7160
7161     } // not a quasi-spherical FACE
7162
7163     // Update _LayerEdge's data according to a new normal
7164
7165     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7166                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7167
7168     id2eos = convFace._subIdToEOS.begin();
7169     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7170     {
7171       _EdgesOnShape& eos = * ( id2eos->second );
7172       for ( size_t i = 0; i < eos._edges.size(); ++i )
7173       {
7174         _LayerEdge* & ledge = eos._edges[ i ];
7175         double len = ledge->_len;
7176         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7177         ledge->SetCosin( ledge->_cosin );
7178         ledge->SetNewLength( len, eos, helper );
7179       }
7180       if ( eos.ShapeType() != TopAbs_FACE )
7181         for ( size_t i = 0; i < eos._edges.size(); ++i )
7182         {
7183           _LayerEdge* ledge = eos._edges[ i ];
7184           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7185           {
7186             _LayerEdge* neibor = ledge->_neibors[iN];
7187             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7188             {
7189               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7190               neibor->Set( _LayerEdge::MOVED );
7191               neibor->SetSmooLen( neibor->_len );
7192             }
7193           }
7194         }
7195     } // loop on sub-shapes of convFace._face
7196
7197     // Find FACEs adjacent to convFace._face that got necessity to smooth
7198     // as a result of normals modification
7199
7200     set< _EdgesOnShape* > adjFacesToSmooth;
7201     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7202     {
7203       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7204            centerCurves[ iE ]._adjFaceToSmooth )
7205         continue;
7206       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7207       {
7208         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7209         {
7210           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7211           break;
7212         }
7213       }
7214     }
7215     data.AddShapesToSmooth( adjFacesToSmooth );
7216
7217     dumpFunctionEnd();
7218
7219
7220   } // loop on data._convexFaces
7221
7222   return true;
7223 }
7224
7225 //================================================================================
7226 /*!
7227  * \brief Finds a center of curvature of a surface at a _LayerEdge
7228  */
7229 //================================================================================
7230
7231 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7232                                         BRepLProp_SLProps&  surfProp,
7233                                         SMESH_MesherHelper& helper,
7234                                         gp_Pnt &            center ) const
7235 {
7236   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
7237   surfProp.SetParameters( uv.X(), uv.Y() );
7238   if ( !surfProp.IsCurvatureDefined() )
7239     return false;
7240
7241   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7242   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
7243   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
7244   if ( surfCurvatureMin > surfCurvatureMax )
7245     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
7246   else
7247     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
7248
7249   return true;
7250 }
7251
7252 //================================================================================
7253 /*!
7254  * \brief Check that prisms are not distorted
7255  */
7256 //================================================================================
7257
7258 bool _ConvexFace::CheckPrisms() const
7259 {
7260   double vol = 0;
7261   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
7262   {
7263     const _LayerEdge* edge = _simplexTestEdges[i];
7264     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
7265     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
7266       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
7267       {
7268         debugMsg( "Bad simplex of _simplexTestEdges ("
7269                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
7270                   << " "<< edge->_simplices[j]._nPrev->GetID()
7271                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
7272         return false;
7273       }
7274   }
7275   return true;
7276 }
7277
7278 //================================================================================
7279 /*!
7280  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
7281  *        stored in this _CentralCurveOnEdge.
7282  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
7283  *  \param [in,out] newNormal - current normal at this point, to be redefined
7284  *  \return bool - true if succeeded.
7285  */
7286 //================================================================================
7287
7288 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
7289 {
7290   if ( this->_isDegenerated )
7291     return false;
7292
7293   // find two centers the given one lies between
7294
7295   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
7296   {
7297     double sl2 = 1.001 * _segLength2[ i ];
7298
7299     double d1 = center.SquareDistance( _curvaCenters[ i ]);
7300     if ( d1 > sl2 )
7301       continue;
7302     
7303     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
7304     if ( d2 > sl2 || d2 + d1 < 1e-100 )
7305       continue;
7306
7307     d1 = Sqrt( d1 );
7308     d2 = Sqrt( d2 );
7309     double r = d1 / ( d1 + d2 );
7310     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
7311                    (      r ) * _ledges[ i+1 ]->_normal );
7312     norm.Normalize();
7313
7314     newNormal += norm;
7315     double sz = newNormal.Modulus();
7316     if ( sz < 1e-200 )
7317       break;
7318     newNormal /= sz;
7319     return true;
7320   }
7321   return false;
7322 }
7323
7324 //================================================================================
7325 /*!
7326  * \brief Set shape members
7327  */
7328 //================================================================================
7329
7330 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
7331                                      const _ConvexFace&  convFace,
7332                                      _SolidData&         data,
7333                                      SMESH_MesherHelper& helper)
7334 {
7335   _edge = edge;
7336
7337   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
7338   while ( const TopoDS_Shape* F = fIt->next())
7339     if ( !convFace._face.IsSame( *F ))
7340     {
7341       _adjFace = TopoDS::Face( *F );
7342       _adjFaceToSmooth = false;
7343       // _adjFace already in a smoothing queue ?
7344       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
7345         _adjFaceToSmooth = eos->_toSmooth;
7346       break;
7347     }
7348 }
7349
7350 //================================================================================
7351 /*!
7352  * \brief Looks for intersection of it's last segment with faces
7353  *  \param distance - returns shortest distance from the last node to intersection
7354  */
7355 //================================================================================
7356
7357 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
7358                                    double &                 distance,
7359                                    const double&            epsilon,
7360                                    _EdgesOnShape&           eos,
7361                                    const SMDS_MeshElement** intFace)
7362 {
7363   vector< const SMDS_MeshElement* > suspectFaces;
7364   double segLen;
7365   gp_Ax1 lastSegment = LastSegment( segLen, eos );
7366   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
7367
7368   bool segmentIntersected = false;
7369   distance = Precision::Infinite();
7370   int iFace = -1; // intersected face
7371   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
7372   {
7373     const SMDS_MeshElement* face = suspectFaces[j];
7374     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
7375          face->GetNodeIndex( _nodes[0]     ) >= 0 )
7376       continue; // face sharing _LayerEdge node
7377     const int nbNodes = face->NbCornerNodes();
7378     bool intFound = false;
7379     double dist;
7380     SMDS_MeshElement::iterator nIt = face->begin_nodes();
7381     if ( nbNodes == 3 )
7382     {
7383       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
7384     }
7385     else
7386     {
7387       const SMDS_MeshNode* tria[3];
7388       tria[0] = *nIt++;
7389       tria[1] = *nIt++;
7390       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
7391       {
7392         tria[2] = *nIt++;
7393         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
7394         tria[1] = tria[2];
7395       }
7396     }
7397     if ( intFound )
7398     {
7399       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
7400         segmentIntersected = true;
7401       if ( distance > dist )
7402         distance = dist, iFace = j;
7403     }
7404   }
7405   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
7406
7407   distance -= segLen;
7408
7409   if ( segmentIntersected )
7410   {
7411 #ifdef __myDEBUG
7412     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
7413     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
7414     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
7415          << ", intersection with face ("
7416          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
7417          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
7418          << ") distance = " << distance << endl;
7419 #endif
7420   }
7421
7422   return segmentIntersected;
7423 }
7424
7425 //================================================================================
7426 /*!
7427  * \brief Returns a point used to check orientation of _simplices
7428  */
7429 //================================================================================
7430
7431 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
7432 {
7433   size_t i = Is( NORMAL_UPDATED ) ? _pos.size()-2 : 0;
7434
7435   if ( !eos || eos->_sWOL.IsNull() )
7436     return _pos[ i ];
7437
7438   if ( eos->SWOLType() == TopAbs_EDGE )
7439   {
7440     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
7441   }
7442   //else //  TopAbs_FACE
7443
7444   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
7445 }
7446
7447 //================================================================================
7448 /*!
7449  * \brief Returns size and direction of the last segment
7450  */
7451 //================================================================================
7452
7453 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
7454 {
7455   // find two non-coincident positions
7456   gp_XYZ orig = _pos.back();
7457   gp_XYZ vec;
7458   int iPrev = _pos.size() - 2;
7459   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
7460   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
7461   while ( iPrev >= 0 )
7462   {
7463     vec = orig - _pos[iPrev];
7464     if ( vec.SquareModulus() > tol*tol )
7465       break;
7466     else
7467       iPrev--;
7468   }
7469
7470   // make gp_Ax1
7471   gp_Ax1 segDir;
7472   if ( iPrev < 0 )
7473   {
7474     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
7475     segDir.SetDirection( _normal );
7476     segLen = 0;
7477   }
7478   else
7479   {
7480     gp_Pnt pPrev = _pos[ iPrev ];
7481     if ( !eos._sWOL.IsNull() )
7482     {
7483       TopLoc_Location loc;
7484       if ( eos.SWOLType() == TopAbs_EDGE )
7485       {
7486         double f,l;
7487         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
7488         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
7489       }
7490       else
7491       {
7492         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
7493         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
7494       }
7495       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
7496     }
7497     segDir.SetLocation( pPrev );
7498     segDir.SetDirection( vec );
7499     segLen = vec.Modulus();
7500   }
7501
7502   return segDir;
7503 }
7504
7505 //================================================================================
7506 /*!
7507  * \brief Return the last position of the target node on a FACE. 
7508  *  \param [in] F - the FACE this _LayerEdge is inflated along
7509  *  \return gp_XY - result UV
7510  */
7511 //================================================================================
7512
7513 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos ) const
7514 {
7515   if ( F.IsSame( eos._sWOL )) // F is my FACE
7516     return gp_XY( _pos.back().X(), _pos.back().Y() );
7517
7518   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
7519     return gp_XY( 1e100, 1e100 );
7520
7521   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
7522   double f, l, u = _pos.back().X();
7523   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
7524   if ( !C2d.IsNull() && f <= u && u <= l )
7525     return C2d->Value( u ).XY();
7526
7527   return gp_XY( 1e100, 1e100 );
7528 }
7529
7530 //================================================================================
7531 /*!
7532  * \brief Test intersection of the last segment with a given triangle
7533  *   using Moller-Trumbore algorithm
7534  * Intersection is detected if distance to intersection is less than _LayerEdge._len
7535  */
7536 //================================================================================
7537
7538 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
7539                                const gp_XYZ& vert0,
7540                                const gp_XYZ& vert1,
7541                                const gp_XYZ& vert2,
7542                                double&       t,
7543                                const double& EPSILON) const
7544 {
7545   const gp_Pnt& orig = lastSegment.Location();
7546   const gp_Dir& dir  = lastSegment.Direction();
7547
7548   /* calculate distance from vert0 to ray origin */
7549   //gp_XYZ tvec = orig.XYZ() - vert0;
7550
7551   //if ( tvec * dir > EPSILON )
7552     // intersected face is at back side of the temporary face this _LayerEdge belongs to
7553     //return false;
7554
7555   gp_XYZ edge1 = vert1 - vert0;
7556   gp_XYZ edge2 = vert2 - vert0;
7557
7558   /* begin calculating determinant - also used to calculate U parameter */
7559   gp_XYZ pvec = dir.XYZ() ^ edge2;
7560
7561   /* if determinant is near zero, ray lies in plane of triangle */
7562   double det = edge1 * pvec;
7563
7564   const double ANGL_EPSILON = 1e-12;
7565   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
7566     return false;
7567
7568   /* calculate distance from vert0 to ray origin */
7569   gp_XYZ tvec = orig.XYZ() - vert0;
7570
7571   /* calculate U parameter and test bounds */
7572   double u = ( tvec * pvec ) / det;
7573   //if (u < 0.0 || u > 1.0)
7574   if ( u < -EPSILON || u > 1.0 + EPSILON )
7575     return false;
7576
7577   /* prepare to test V parameter */
7578   gp_XYZ qvec = tvec ^ edge1;
7579
7580   /* calculate V parameter and test bounds */
7581   double v = (dir.XYZ() * qvec) / det;
7582   //if ( v < 0.0 || u + v > 1.0 )
7583   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
7584     return false;
7585
7586   /* calculate t, ray intersects triangle */
7587   t = (edge2 * qvec) / det;
7588
7589   //return true;
7590   return t > 0.;
7591 }
7592
7593 //================================================================================
7594 /*!
7595  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
7596  *        neighbor _LayerEdge's by it's own inflation vector.
7597  *  \param [in] eov - EOS of the VERTEX
7598  *  \param [in] eos - EOS of the FACE
7599  *  \param [in] step - inflation step
7600  *  \param [in,out] badSmooEdges - not untangled _LayerEdge's
7601  */
7602 //================================================================================
7603
7604 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
7605                                    const _EdgesOnShape*    eos,
7606                                    const int               step,
7607                                    vector< _LayerEdge* > & badSmooEdges )
7608 {
7609   // check if any of _neibors is in badSmooEdges
7610   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
7611                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
7612     return;
7613
7614   // get all edges to move
7615
7616   set< _LayerEdge* > edges;
7617
7618   // find a distance between _LayerEdge on VERTEX and its neighbors
7619   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
7620   double dist2 = 0;
7621   for ( size_t i = 0; i < _neibors.size(); ++i )
7622   {
7623     _LayerEdge* nEdge = _neibors[i];
7624     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
7625     {
7626       edges.insert( nEdge );
7627       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
7628     }
7629   }
7630   // add _LayerEdge's close to curPosV
7631   size_t nbE;
7632   do {
7633     nbE = edges.size();
7634     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7635     {
7636       _LayerEdge* edgeF = *e;
7637       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
7638       {
7639         _LayerEdge* nEdge = edgeF->_neibors[i];
7640         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
7641              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
7642           edges.insert( nEdge );
7643       }
7644     }
7645   }
7646   while ( nbE < edges.size() );
7647
7648   // move the target node of the got edges
7649
7650   gp_XYZ prevPosV = PrevPos();
7651   if ( eov->SWOLType() == TopAbs_EDGE )
7652   {
7653     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
7654     prevPosV = curve.Value( prevPosV.X() ).XYZ();
7655   }
7656   else if ( eov->SWOLType() == TopAbs_FACE )
7657   {
7658     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
7659     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
7660   }
7661
7662   SMDS_FacePosition* fPos;
7663   //double r = 1. - Min( 0.9, step / 10. );
7664   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7665   {
7666     _LayerEdge*       edgeF = *e;
7667     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
7668     const gp_XYZ    newPosF = curPosV + prevVF;
7669     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7670     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
7671     edgeF->_pos.back() = newPosF;
7672     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
7673
7674     // set _curvature to make edgeF updated by putOnOffsetSurface()
7675     if ( !edgeF->_curvature )
7676       if (( fPos = dynamic_cast<SMDS_FacePosition*>( edgeF->_nodes[0]->GetPosition() )))
7677       {
7678         edgeF->_curvature = new _Curvature;
7679         edgeF->_curvature->_r = 0;
7680         edgeF->_curvature->_k = 0;
7681         edgeF->_curvature->_h2lenRatio = 0;
7682         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
7683       }
7684   }
7685   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
7686   //                      SMESH_TNodeXYZ( _nodes[0]    ));
7687   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7688   // {
7689   //   _LayerEdge*      edgeF = *e;
7690   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7691   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7692   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7693   //   edgeF->_pos.back() = newPosF;
7694   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
7695   // }
7696
7697   // smooth _LayerEdge's around moved nodes
7698   //size_t nbBadBefore = badSmooEdges.size();
7699   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
7700   {
7701     _LayerEdge* edgeF = *e;
7702     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
7703       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
7704         //&& !edges.count( edgeF->_neibors[j] ))
7705       {
7706         _LayerEdge* edgeFN = edgeF->_neibors[j];
7707         edgeFN->Unset( SMOOTHED );
7708         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
7709         // if ( nbBad > 0 )
7710         // {
7711         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
7712         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
7713         //   int        nbBadAfter = edgeFN->_simplices.size();
7714         //   double vol;
7715         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
7716         //   {
7717         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
7718         //   }
7719         //   if ( nbBadAfter <= nbBad )
7720         //   {
7721         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
7722         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7723         //     edgeF->_pos.back() = newPosF;
7724         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7725         //     nbBad = nbBadAfter;
7726         //   }
7727         // }
7728         if ( nbBad > 0 )
7729           badSmooEdges.push_back( edgeFN );
7730       }
7731   }
7732     // move a bit not smoothed around moved nodes
7733   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
7734   //   {
7735   //   _LayerEdge*      edgeF = badSmooEdges[i];
7736   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
7737   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
7738   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
7739   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
7740   //   edgeF->_pos.back() = newPosF;
7741   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
7742   // }
7743 }
7744
7745 //================================================================================
7746 /*!
7747  * \brief Perform smooth of _LayerEdge's based on EDGE's
7748  *  \retval bool - true if node has been moved
7749  */
7750 //================================================================================
7751
7752 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
7753                               const TopoDS_Face&             F,
7754                               SMESH_MesherHelper&            helper)
7755 {
7756   ASSERT( IsOnEdge() );
7757
7758   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
7759   SMESH_TNodeXYZ oldPos( tgtNode );
7760   double dist01, distNewOld;
7761   
7762   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
7763   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
7764   dist01 = p0.Distance( _2neibors->tgtNode(1) );
7765
7766   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
7767   double lenDelta = 0;
7768   if ( _curvature )
7769   {
7770     //lenDelta = _curvature->lenDelta( _len );
7771     lenDelta = _curvature->lenDeltaByDist( dist01 );
7772     newPos.ChangeCoord() += _normal * lenDelta;
7773   }
7774
7775   distNewOld = newPos.Distance( oldPos );
7776
7777   if ( F.IsNull() )
7778   {
7779     if ( _2neibors->_plnNorm )
7780     {
7781       // put newPos on the plane defined by source node and _plnNorm
7782       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
7783       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
7784       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
7785     }
7786     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7787     _pos.back() = newPos.XYZ();
7788   }
7789   else
7790   {
7791     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7792     gp_XY uv( Precision::Infinite(), 0 );
7793     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
7794     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
7795
7796     newPos = surface->Value( uv );
7797     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
7798   }
7799
7800   // commented for IPAL0052478
7801   // if ( _curvature && lenDelta < 0 )
7802   // {
7803   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
7804   //   _len -= prevPos.Distance( oldPos );
7805   //   _len += prevPos.Distance( newPos );
7806   // }
7807   bool moved = distNewOld > dist01/50;
7808   //if ( moved )
7809   dumpMove( tgtNode ); // debug
7810
7811   return moved;
7812 }
7813
7814 //================================================================================
7815 /*!
7816  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
7817  */
7818 //================================================================================
7819
7820 void _LayerEdge::SmoothWoCheck()
7821 {
7822   if ( Is( DIFFICULT ))
7823     return;
7824
7825   bool moved = Is( SMOOTHED );
7826   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
7827     moved = _neibors[i]->Is( SMOOTHED );
7828   if ( !moved )
7829     return;
7830
7831   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7832
7833   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
7834   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
7835   _pos.back() = newPos;
7836
7837   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
7838 }
7839
7840 //================================================================================
7841 /*!
7842  * \brief Checks validity of _neibors on EDGEs and VERTEXes
7843  */
7844 //================================================================================
7845
7846 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
7847 {
7848   if ( ! Is( NEAR_BOUNDARY ))
7849     return 0;
7850
7851   int nbBad = 0;
7852   double vol;
7853   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
7854   {
7855     _LayerEdge* eN = _neibors[iN];
7856     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
7857       continue;
7858     if ( needSmooth )
7859       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
7860                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
7861                        eN->_pos.size() != _pos.size() );
7862
7863     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
7864     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
7865     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
7866       if ( eN->_nodes.size() > 1 &&
7867            eN->_simplices[i].Includes( _nodes.back() ) &&
7868            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
7869       {
7870         ++nbBad;
7871         if ( badNeibors )
7872         {
7873           badNeibors->push_back( eN );
7874           debugMsg("Bad boundary simplex ( "
7875                    << " "<< eN->_nodes[0]->GetID()
7876                    << " "<< eN->_nodes.back()->GetID()
7877                    << " "<< eN->_simplices[i]._nPrev->GetID()
7878                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
7879         }
7880         else
7881         {
7882           break;
7883         }
7884       }
7885   }
7886   return nbBad;
7887 }
7888
7889 //================================================================================
7890 /*!
7891  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
7892  *  \retval int - nb of bad simplices around this _LayerEdge
7893  */
7894 //================================================================================
7895
7896 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
7897 {
7898   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
7899     return 0; // shape of simplices not changed
7900   if ( _simplices.size() < 2 )
7901     return 0; // _LayerEdge inflated along EDGE or FACE
7902
7903   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
7904     findBest = true;
7905
7906   const gp_XYZ& curPos  = _pos.back();
7907   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
7908
7909   // quality metrics (orientation) of tetras around _tgtNode
7910   int nbOkBefore = 0;
7911   double vol, minVolBefore = 1e100;
7912   for ( size_t i = 0; i < _simplices.size(); ++i )
7913   {
7914     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
7915     minVolBefore = Min( minVolBefore, vol );
7916   }
7917   int nbBad = _simplices.size() - nbOkBefore;
7918
7919   bool bndNeedSmooth = false;
7920   if ( nbBad == 0 )
7921     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
7922   if ( nbBad > 0 )
7923     Set( DISTORTED );
7924
7925   // evaluate min angle
7926   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
7927   {
7928     size_t nbGoodAngles = _simplices.size();
7929     double angle;
7930     for ( size_t i = 0; i < _simplices.size(); ++i )
7931     {
7932       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
7933         --nbGoodAngles;
7934     }
7935     if ( nbGoodAngles == _simplices.size() )
7936     {
7937       Unset( MOVED );
7938       return 0;
7939     }
7940   }
7941   if ( Is( ON_CONCAVE_FACE ))
7942     findBest = true;
7943
7944   if ( step % 2 == 0 )
7945     findBest = false;
7946
7947   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
7948   {
7949     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
7950       _smooFunction = _funs[ FUN_CENTROIDAL ];
7951     else
7952       _smooFunction = _funs[ FUN_LAPLACIAN ];
7953   }
7954
7955   // compute new position for the last _pos using different _funs
7956   gp_XYZ newPos;
7957   bool moved = false;
7958   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
7959   {
7960     if ( iFun < 0 )
7961       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
7962     else if ( _funs[ iFun ] == _smooFunction )
7963       continue; // _smooFunction again
7964     else if ( step > 1 )
7965       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
7966     else
7967       break; // let "easy" functions improve elements around distorted ones
7968
7969     if ( _curvature )
7970     {
7971       double delta  = _curvature->lenDelta( _len );
7972       if ( delta > 0 )
7973         newPos += _normal * delta;
7974       else
7975       {
7976         double segLen = _normal * ( newPos - prevPos );
7977         if ( segLen + delta > 0 )
7978           newPos += _normal * delta;
7979       }
7980       // double segLenChange = _normal * ( curPos - newPos );
7981       // newPos += 0.5 * _normal * segLenChange;
7982     }
7983
7984     int nbOkAfter = 0;
7985     double minVolAfter = 1e100;
7986     for ( size_t i = 0; i < _simplices.size(); ++i )
7987     {
7988       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
7989       minVolAfter = Min( minVolAfter, vol );
7990     }
7991     // get worse?
7992     if ( nbOkAfter < nbOkBefore )
7993       continue;
7994
7995     if (( findBest ) &&
7996         ( nbOkAfter == nbOkBefore ) &&
7997         ( minVolAfter <= minVolBefore ))
7998       continue;
7999
8000     nbBad        = _simplices.size() - nbOkAfter;
8001     minVolBefore = minVolAfter;
8002     nbOkBefore   = nbOkAfter;
8003     moved        = true;
8004
8005     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8006     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8007     _pos.back() = newPos;
8008
8009     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8010                   << (nbBad ? " --BAD" : ""));
8011
8012     if ( iFun > -1 )
8013     {
8014       continue; // look for a better function
8015     }
8016
8017     if ( !findBest )
8018       break;
8019
8020   } // loop on smoothing functions
8021
8022   if ( moved ) // notify _neibors
8023   {
8024     Set( SMOOTHED );
8025     for ( size_t i = 0; i < _neibors.size(); ++i )
8026       if ( !_neibors[i]->Is( MOVED ))
8027       {
8028         _neibors[i]->Set( MOVED );
8029         toSmooth.push_back( _neibors[i] );
8030       }
8031   }
8032
8033   return nbBad;
8034 }
8035
8036 //================================================================================
8037 /*!
8038  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8039  *  \retval int - nb of bad simplices around this _LayerEdge
8040  */
8041 //================================================================================
8042
8043 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8044 {
8045   if ( !_smooFunction )
8046     return 0; // _LayerEdge inflated along EDGE or FACE
8047   if ( Is( BLOCKED ))
8048     return 0; // not inflated
8049
8050   const gp_XYZ& curPos  = _pos.back();
8051   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8052
8053   // quality metrics (orientation) of tetras around _tgtNode
8054   int nbOkBefore = 0;
8055   double vol, minVolBefore = 1e100;
8056   for ( size_t i = 0; i < _simplices.size(); ++i )
8057   {
8058     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8059     minVolBefore = Min( minVolBefore, vol );
8060   }
8061   int nbBad = _simplices.size() - nbOkBefore;
8062
8063   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8064   {
8065     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8066       _smooFunction = _funs[ FUN_LAPLACIAN ];
8067     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8068       _smooFunction = _funs[ FUN_CENTROIDAL ];
8069   }
8070
8071   // compute new position for the last _pos using different _funs
8072   gp_XYZ newPos;
8073   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8074   {
8075     if ( iFun < 0 )
8076       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8077     else if ( _funs[ iFun ] == _smooFunction )
8078       continue; // _smooFunction again
8079     else if ( step > 1 )
8080       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8081     else
8082       break; // let "easy" functions improve elements around distorted ones
8083
8084     if ( _curvature )
8085     {
8086       double delta  = _curvature->lenDelta( _len );
8087       if ( delta > 0 )
8088         newPos += _normal * delta;
8089       else
8090       {
8091         double segLen = _normal * ( newPos - prevPos );
8092         if ( segLen + delta > 0 )
8093           newPos += _normal * delta;
8094       }
8095       // double segLenChange = _normal * ( curPos - newPos );
8096       // newPos += 0.5 * _normal * segLenChange;
8097     }
8098
8099     int nbOkAfter = 0;
8100     double minVolAfter = 1e100;
8101     for ( size_t i = 0; i < _simplices.size(); ++i )
8102     {
8103       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8104       minVolAfter = Min( minVolAfter, vol );
8105     }
8106     // get worse?
8107     if ( nbOkAfter < nbOkBefore )
8108       continue;
8109     if (( isConcaveFace || findBest ) &&
8110         ( nbOkAfter == nbOkBefore ) &&
8111         ( minVolAfter <= minVolBefore )
8112         )
8113       continue;
8114
8115     nbBad        = _simplices.size() - nbOkAfter;
8116     minVolBefore = minVolAfter;
8117     nbOkBefore   = nbOkAfter;
8118
8119     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8120     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8121     _pos.back() = newPos;
8122
8123     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8124                   << ( nbBad ? "--BAD" : ""));
8125
8126     // commented for IPAL0052478
8127     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8128     // _len += prevPos.Distance(newPos);
8129
8130     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8131     {
8132       //_smooFunction = _funs[ iFun ];
8133       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8134       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8135       // << " minVol: " << minVolAfter
8136       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8137       // << endl;
8138       continue; // look for a better function
8139     }
8140
8141     if ( !findBest )
8142       break;
8143
8144   } // loop on smoothing functions
8145
8146   return nbBad;
8147 }
8148
8149 //================================================================================
8150 /*!
8151  * \brief Chooses a smoothing technic giving a position most close to an initial one.
8152  *        For a correct result, _simplices must contain nodes lying on geometry.
8153  */
8154 //================================================================================
8155
8156 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8157                                      const TNode2Edge&     n2eMap)
8158 {
8159   if ( _smooFunction ) return;
8160
8161   // use smoothNefPolygon() near concaveVertices
8162   if ( !concaveVertices.empty() )
8163   {
8164     _smooFunction = _funs[ FUN_CENTROIDAL ];
8165
8166     Set( ON_CONCAVE_FACE );
8167
8168     for ( size_t i = 0; i < _simplices.size(); ++i )
8169     {
8170       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8171       {
8172         _smooFunction = _funs[ FUN_NEFPOLY ];
8173
8174         // set FUN_CENTROIDAL to neighbor edges
8175         for ( i = 0; i < _neibors.size(); ++i )
8176         {
8177           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8178           {
8179             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8180           }
8181         }
8182         return;
8183       }
8184     }
8185
8186     // // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8187     // // where the nodes are smoothed too far along a sphere thus creating
8188     // // inverted _simplices
8189     // double dist[theNbSmooFuns];
8190     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8191     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8192
8193     // double minDist = Precision::Infinite();
8194     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8195     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8196     // {
8197     //   gp_Pnt newP = (this->*_funs[i])();
8198     //   dist[i] = p.SquareDistance( newP );
8199     //   if ( dist[i]*coef[i] < minDist )
8200     //   {
8201     //     _smooFunction = _funs[i];
8202     //     minDist = dist[i]*coef[i];
8203     //   }
8204     // }
8205   }
8206   else
8207   {
8208     _smooFunction = _funs[ FUN_LAPLACIAN ];
8209   }
8210   // int minDim = 3;
8211   // for ( size_t i = 0; i < _simplices.size(); ++i )
8212   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8213   // if ( minDim == 0 )
8214   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8215   // else if ( minDim == 1 )
8216   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8217
8218
8219   // int iMin;
8220   // for ( int i = 0; i < FUN_NB; ++i )
8221   // {
8222   //   //cout << dist[i] << " ";
8223   //   if ( _smooFunction == _funs[i] ) {
8224   //     iMin = i;
8225   //     //debugMsg( fNames[i] );
8226   //     break;
8227   //   }
8228   // }
8229   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8230 }
8231
8232 //================================================================================
8233 /*!
8234  * \brief Returns a name of _SmooFunction
8235  */
8236 //================================================================================
8237
8238 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
8239 {
8240   if ( !fun )
8241     fun = _smooFunction;
8242   for ( int i = 0; i < theNbSmooFuns; ++i )
8243     if ( fun == _funs[i] )
8244       return i;
8245
8246   return theNbSmooFuns;
8247 }
8248
8249 //================================================================================
8250 /*!
8251  * \brief Computes a new node position using Laplacian smoothing
8252  */
8253 //================================================================================
8254
8255 gp_XYZ _LayerEdge::smoothLaplacian()
8256 {
8257   gp_XYZ newPos (0,0,0);
8258   for ( size_t i = 0; i < _simplices.size(); ++i )
8259     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8260   newPos /= _simplices.size();
8261
8262   return newPos;
8263 }
8264
8265 //================================================================================
8266 /*!
8267  * \brief Computes a new node position using angular-based smoothing
8268  */
8269 //================================================================================
8270
8271 gp_XYZ _LayerEdge::smoothAngular()
8272 {
8273   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
8274   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
8275   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
8276
8277   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8278   gp_XYZ pN( 0,0,0 );
8279   for ( size_t i = 0; i < _simplices.size(); ++i )
8280   {
8281     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8282     edgeDir.push_back( p - pPrev );
8283     edgeSize.push_back( edgeDir.back().Magnitude() );
8284     if ( edgeSize.back() < numeric_limits<double>::min() )
8285     {
8286       edgeDir.pop_back();
8287       edgeSize.pop_back();
8288     }
8289     else
8290     {
8291       edgeDir.back() /= edgeSize.back();
8292       points.push_back( p );
8293       pN += p;
8294     }
8295     pPrev = p;
8296   }
8297   edgeDir.push_back ( edgeDir[0] );
8298   edgeSize.push_back( edgeSize[0] );
8299   pN /= points.size();
8300
8301   gp_XYZ newPos(0,0,0);
8302   double sumSize = 0;
8303   for ( size_t i = 0; i < points.size(); ++i )
8304   {
8305     gp_Vec toN    = pN - points[i];
8306     double toNLen = toN.Magnitude();
8307     if ( toNLen < numeric_limits<double>::min() )
8308     {
8309       newPos += pN;
8310       continue;
8311     }
8312     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
8313     double bisecLen = bisec.SquareMagnitude();
8314     if ( bisecLen < numeric_limits<double>::min() )
8315     {
8316       gp_Vec norm = edgeDir[i] ^ toN;
8317       bisec = norm ^ edgeDir[i];
8318       bisecLen = bisec.SquareMagnitude();
8319     }
8320     bisecLen = Sqrt( bisecLen );
8321     bisec /= bisecLen;
8322
8323 #if 1
8324     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
8325     sumSize += bisecLen;
8326 #else
8327     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
8328     sumSize += ( edgeSize[i] + edgeSize[i+1] );
8329 #endif
8330     newPos += pNew;
8331   }
8332   newPos /= sumSize;
8333
8334   // project newPos to an average plane
8335
8336   gp_XYZ norm(0,0,0); // plane normal
8337   points.push_back( points[0] );
8338   for ( size_t i = 1; i < points.size(); ++i )
8339   {
8340     gp_XYZ vec1 = points[ i-1 ] - pN;
8341     gp_XYZ vec2 = points[ i   ] - pN;
8342     gp_XYZ cross = vec1 ^ vec2;
8343     try {
8344       cross.Normalize();
8345       if ( cross * norm < numeric_limits<double>::min() )
8346         norm += cross.Reversed();
8347       else
8348         norm += cross;
8349     }
8350     catch (Standard_Failure) { // if |cross| == 0.
8351     }
8352   }
8353   gp_XYZ vec = newPos - pN;
8354   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
8355   newPos     = newPos - r * norm;
8356
8357   return newPos;
8358 }
8359
8360 //================================================================================
8361 /*!
8362  * \brief Computes a new node position using weigthed node positions
8363  */
8364 //================================================================================
8365
8366 gp_XYZ _LayerEdge::smoothLengthWeighted()
8367 {
8368   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
8369   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
8370
8371   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
8372   for ( size_t i = 0; i < _simplices.size(); ++i )
8373   {
8374     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8375     edgeSize.push_back( ( p - pPrev ).Modulus() );
8376     if ( edgeSize.back() < numeric_limits<double>::min() )
8377     {
8378       edgeSize.pop_back();
8379     }
8380     else
8381     {
8382       points.push_back( p );
8383     }
8384     pPrev = p;
8385   }
8386   edgeSize.push_back( edgeSize[0] );
8387
8388   gp_XYZ newPos(0,0,0);
8389   double sumSize = 0;
8390   for ( size_t i = 0; i < points.size(); ++i )
8391   {
8392     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
8393     sumSize += edgeSize[i] + edgeSize[i+1];
8394   }
8395   newPos /= sumSize;
8396   return newPos;
8397 }
8398
8399 //================================================================================
8400 /*!
8401  * \brief Computes a new node position using angular-based smoothing
8402  */
8403 //================================================================================
8404
8405 gp_XYZ _LayerEdge::smoothCentroidal()
8406 {
8407   gp_XYZ newPos(0,0,0);
8408   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
8409   double sumSize = 0;
8410   for ( size_t i = 0; i < _simplices.size(); ++i )
8411   {
8412     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
8413     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
8414     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
8415     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
8416
8417     sumSize += size;
8418     newPos += gc * size;
8419   }
8420   newPos /= sumSize;
8421
8422   return newPos;
8423 }
8424
8425 //================================================================================
8426 /*!
8427  * \brief Computes a new node position located inside a Nef polygon
8428  */
8429 //================================================================================
8430
8431 gp_XYZ _LayerEdge::smoothNefPolygon()
8432 #ifdef OLD_NEF_POLYGON
8433 {
8434   gp_XYZ newPos(0,0,0);
8435
8436   // get a plane to seach a solution on
8437
8438   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8439   size_t i;
8440   const double tol = numeric_limits<double>::min();
8441   gp_XYZ center(0,0,0);
8442   for ( i = 0; i < _simplices.size(); ++i )
8443   {
8444     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
8445                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
8446     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8447   }
8448   vecs.back() = vecs[0];
8449   center /= _simplices.size();
8450
8451   gp_XYZ zAxis(0,0,0);
8452   for ( i = 0; i < _simplices.size(); ++i )
8453     zAxis += vecs[i] ^ vecs[i+1];
8454
8455   gp_XYZ yAxis;
8456   for ( i = 0; i < _simplices.size(); ++i )
8457   {
8458     yAxis = vecs[i];
8459     if ( yAxis.SquareModulus() > tol )
8460       break;
8461   }
8462   gp_XYZ xAxis = yAxis ^ zAxis;
8463   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8464   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8465   //                             p0.Distance( _simplices[2]._nPrev ));
8466   // gp_XYZ center = smoothLaplacian();
8467   // gp_XYZ xAxis, yAxis, zAxis;
8468   // for ( i = 0; i < _simplices.size(); ++i )
8469   // {
8470   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8471   //   if ( xAxis.SquareModulus() > tol*tol )
8472   //     break;
8473   // }
8474   // for ( i = 1; i < _simplices.size(); ++i )
8475   // {
8476   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8477   //   zAxis = xAxis ^ yAxis;
8478   //   if ( zAxis.SquareModulus() > tol*tol )
8479   //     break;
8480   // }
8481   // if ( i == _simplices.size() ) return newPos;
8482
8483   yAxis = zAxis ^ xAxis;
8484   xAxis /= xAxis.Modulus();
8485   yAxis /= yAxis.Modulus();
8486
8487   // get half-planes of _simplices
8488
8489   vector< _halfPlane > halfPlns( _simplices.size() );
8490   int nbHP = 0;
8491   for ( size_t i = 0; i < _simplices.size(); ++i )
8492   {
8493     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8494     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
8495     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8496     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8497     gp_XY  vec12 = p2 - p1;
8498     double dist12 = vec12.Modulus();
8499     if ( dist12 < tol )
8500       continue;
8501     vec12 /= dist12;
8502     halfPlns[ nbHP ]._pos = p1;
8503     halfPlns[ nbHP ]._dir = vec12;
8504     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8505     ++nbHP;
8506   }
8507
8508   // intersect boundaries of half-planes, define state of intersection points
8509   // in relation to all half-planes and calculate internal point of a 2D polygon
8510
8511   double sumLen = 0;
8512   gp_XY newPos2D (0,0);
8513
8514   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8515   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8516   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8517
8518   vector< vector< TIntPntState > > allIntPnts( nbHP );
8519   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8520   {
8521     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8522     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8523
8524     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8525     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8526
8527     int nbNotOut = 0;
8528     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8529
8530     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8531     {
8532       if ( iHP1 == iHP2 ) continue;
8533
8534       TIntPntState & ips1 = intPnts1[ iHP2 ];
8535       if ( ips1.second == UNDEF )
8536       {
8537         // find an intersection point of boundaries of iHP1 and iHP2
8538
8539         if ( iHP2 == iPrev ) // intersection with neighbors is known
8540           ips1.first = halfPlns[ iHP1 ]._pos;
8541         else if ( iHP2 == iNext )
8542           ips1.first = halfPlns[ iHP2 ]._pos;
8543         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8544           ips1.second = NO_INT;
8545
8546         // classify the found intersection point
8547         if ( ips1.second != NO_INT )
8548         {
8549           ips1.second = NOT_OUT;
8550           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8551             if ( i != iHP1 && i != iHP2 &&
8552                  halfPlns[ i ].IsOut( ips1.first, tol ))
8553               ips1.second = IS_OUT;
8554         }
8555         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8556         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8557         TIntPntState & ips2 = intPnts2[ iHP1 ];
8558         ips2 = ips1;
8559       }
8560       if ( ips1.second == NOT_OUT )
8561       {
8562         ++nbNotOut;
8563         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8564       }
8565     }
8566
8567     // find a NOT_OUT segment of boundary which is located between
8568     // two NOT_OUT int points
8569
8570     if ( nbNotOut < 2 )
8571       continue; // no such a segment
8572
8573     if ( nbNotOut > 2 )
8574     {
8575       // sort points along the boundary
8576       map< double, TIntPntState* > ipsByParam;
8577       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8578       {
8579         TIntPntState & ips1 = intPnts1[ iHP2 ];
8580         if ( ips1.second != NO_INT )
8581         {
8582           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8583           double param = op * halfPlns[ iHP1 ]._dir;
8584           ipsByParam.insert( make_pair( param, & ips1 ));
8585         }
8586       }
8587       // look for two neighboring NOT_OUT points
8588       nbNotOut = 0;
8589       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8590       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8591       {
8592         TIntPntState & ips1 = *(u2ips->second);
8593         if ( ips1.second == NOT_OUT )
8594           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8595         else if ( nbNotOut >= 2 )
8596           break;
8597         else
8598           nbNotOut = 0;
8599       }
8600     }
8601
8602     if ( nbNotOut >= 2 )
8603     {
8604       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8605       sumLen += len;
8606
8607       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8608     }
8609   }
8610
8611   if ( sumLen > 0 )
8612   {
8613     newPos2D /= sumLen;
8614     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8615   }
8616   else
8617   {
8618     newPos = center;
8619   }
8620
8621   return newPos;
8622 }
8623 #else // OLD_NEF_POLYGON
8624 { ////////////////////////////////// NEW
8625   gp_XYZ newPos(0,0,0);
8626
8627   // get a plane to seach a solution on
8628
8629   size_t i;
8630   gp_XYZ center(0,0,0);
8631   for ( i = 0; i < _simplices.size(); ++i )
8632     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
8633   center /= _simplices.size();
8634
8635   vector< gp_XYZ > vecs( _simplices.size() + 1 );
8636   for ( i = 0; i < _simplices.size(); ++i )
8637     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8638   vecs.back() = vecs[0];
8639
8640   const double tol = numeric_limits<double>::min();
8641   gp_XYZ zAxis(0,0,0);
8642   for ( i = 0; i < _simplices.size(); ++i )
8643   {
8644     gp_XYZ cross = vecs[i] ^ vecs[i+1];
8645     try {
8646       cross.Normalize();
8647       if ( cross * zAxis < tol )
8648         zAxis += cross.Reversed();
8649       else
8650         zAxis += cross;
8651     }
8652     catch (Standard_Failure) { // if |cross| == 0.
8653     }
8654   }
8655
8656   gp_XYZ yAxis;
8657   for ( i = 0; i < _simplices.size(); ++i )
8658   {
8659     yAxis = vecs[i];
8660     if ( yAxis.SquareModulus() > tol )
8661       break;
8662   }
8663   gp_XYZ xAxis = yAxis ^ zAxis;
8664   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
8665   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
8666   //                             p0.Distance( _simplices[2]._nPrev ));
8667   // gp_XYZ center = smoothLaplacian();
8668   // gp_XYZ xAxis, yAxis, zAxis;
8669   // for ( i = 0; i < _simplices.size(); ++i )
8670   // {
8671   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8672   //   if ( xAxis.SquareModulus() > tol*tol )
8673   //     break;
8674   // }
8675   // for ( i = 1; i < _simplices.size(); ++i )
8676   // {
8677   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
8678   //   zAxis = xAxis ^ yAxis;
8679   //   if ( zAxis.SquareModulus() > tol*tol )
8680   //     break;
8681   // }
8682   // if ( i == _simplices.size() ) return newPos;
8683
8684   yAxis = zAxis ^ xAxis;
8685   xAxis /= xAxis.Modulus();
8686   yAxis /= yAxis.Modulus();
8687
8688   // get half-planes of _simplices
8689
8690   vector< _halfPlane > halfPlns( _simplices.size() );
8691   int nbHP = 0;
8692   for ( size_t i = 0; i < _simplices.size(); ++i )
8693   {
8694     const gp_XYZ& OP1 = vecs[ i   ];
8695     const gp_XYZ& OP2 = vecs[ i+1 ];
8696     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
8697     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
8698     gp_XY  vec12 = p2 - p1;
8699     double dist12 = vec12.Modulus();
8700     if ( dist12 < tol )
8701       continue;
8702     vec12 /= dist12;
8703     halfPlns[ nbHP ]._pos = p1;
8704     halfPlns[ nbHP ]._dir = vec12;
8705     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
8706     ++nbHP;
8707   }
8708
8709   // intersect boundaries of half-planes, define state of intersection points
8710   // in relation to all half-planes and calculate internal point of a 2D polygon
8711
8712   double sumLen = 0;
8713   gp_XY newPos2D (0,0);
8714
8715   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
8716   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
8717   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
8718
8719   vector< vector< TIntPntState > > allIntPnts( nbHP );
8720   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
8721   {
8722     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
8723     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
8724
8725     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
8726     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
8727
8728     int nbNotOut = 0;
8729     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
8730
8731     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8732     {
8733       if ( iHP1 == iHP2 ) continue;
8734
8735       TIntPntState & ips1 = intPnts1[ iHP2 ];
8736       if ( ips1.second == UNDEF )
8737       {
8738         // find an intersection point of boundaries of iHP1 and iHP2
8739
8740         if ( iHP2 == iPrev ) // intersection with neighbors is known
8741           ips1.first = halfPlns[ iHP1 ]._pos;
8742         else if ( iHP2 == iNext )
8743           ips1.first = halfPlns[ iHP2 ]._pos;
8744         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
8745           ips1.second = NO_INT;
8746
8747         // classify the found intersection point
8748         if ( ips1.second != NO_INT )
8749         {
8750           ips1.second = NOT_OUT;
8751           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
8752             if ( i != iHP1 && i != iHP2 &&
8753                  halfPlns[ i ].IsOut( ips1.first, tol ))
8754               ips1.second = IS_OUT;
8755         }
8756         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
8757         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
8758         TIntPntState & ips2 = intPnts2[ iHP1 ];
8759         ips2 = ips1;
8760       }
8761       if ( ips1.second == NOT_OUT )
8762       {
8763         ++nbNotOut;
8764         segEnds[ bool(segEnds[0]) ] = & ips1.first;
8765       }
8766     }
8767
8768     // find a NOT_OUT segment of boundary which is located between
8769     // two NOT_OUT int points
8770
8771     if ( nbNotOut < 2 )
8772       continue; // no such a segment
8773
8774     if ( nbNotOut > 2 )
8775     {
8776       // sort points along the boundary
8777       map< double, TIntPntState* > ipsByParam;
8778       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
8779       {
8780         TIntPntState & ips1 = intPnts1[ iHP2 ];
8781         if ( ips1.second != NO_INT )
8782         {
8783           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
8784           double param = op * halfPlns[ iHP1 ]._dir;
8785           ipsByParam.insert( make_pair( param, & ips1 ));
8786         }
8787       }
8788       // look for two neighboring NOT_OUT points
8789       nbNotOut = 0;
8790       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
8791       for ( ; u2ips != ipsByParam.end(); ++u2ips )
8792       {
8793         TIntPntState & ips1 = *(u2ips->second);
8794         if ( ips1.second == NOT_OUT )
8795           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
8796         else if ( nbNotOut >= 2 )
8797           break;
8798         else
8799           nbNotOut = 0;
8800       }
8801     }
8802
8803     if ( nbNotOut >= 2 )
8804     {
8805       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
8806       sumLen += len;
8807
8808       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
8809     }
8810   }
8811
8812   if ( sumLen > 0 )
8813   {
8814     newPos2D /= sumLen;
8815     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
8816   }
8817   else
8818   {
8819     newPos = center;
8820   }
8821
8822   return newPos;
8823 }
8824 #endif // OLD_NEF_POLYGON
8825
8826 //================================================================================
8827 /*!
8828  * \brief Add a new segment to _LayerEdge during inflation
8829  */
8830 //================================================================================
8831
8832 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
8833 {
8834   if ( Is( BLOCKED ))
8835     return;
8836
8837   if ( len > _maxLen )
8838   {
8839     len = _maxLen;
8840     Block( eos.GetData() );
8841   }
8842   const double lenDelta = len - _len;
8843   if ( lenDelta < len * 1e-3  )
8844   {
8845     Block( eos.GetData() );
8846     return;
8847   }
8848
8849   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
8850   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
8851   gp_XYZ newXYZ;
8852   if ( eos._hyp.IsOffsetMethod() )
8853   {
8854     newXYZ = oldXYZ;
8855     gp_Vec faceNorm;
8856     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
8857     while ( faceIt->more() )
8858     {
8859       const SMDS_MeshElement* face = faceIt->next();
8860       if ( !eos.GetNormal( face, faceNorm ))
8861         continue;
8862
8863       // translate plane of a face
8864       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
8865
8866       // find point of intersection of the face plane located at baryCenter
8867       // and _normal located at newXYZ
8868       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
8869       double dot =  ( faceNorm.XYZ() * _normal );
8870       if ( dot < std::numeric_limits<double>::min() )
8871         dot = lenDelta * 1e-3;
8872       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
8873       newXYZ += step * _normal;
8874     }
8875     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
8876   }
8877   else
8878   {
8879     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
8880   }
8881
8882   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
8883   _pos.push_back( newXYZ );
8884
8885   if ( !eos._sWOL.IsNull() )
8886   {
8887     double distXYZ[4];
8888     bool uvOK = false;
8889     if ( eos.SWOLType() == TopAbs_EDGE )
8890     {
8891       double u = Precision::Infinite(); // to force projection w/o distance check
8892       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
8893                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8894       _pos.back().SetCoord( u, 0, 0 );
8895       if ( _nodes.size() > 1 && uvOK )
8896       {
8897         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
8898         pos->SetUParameter( u );
8899       }
8900     }
8901     else //  TopAbs_FACE
8902     {
8903       gp_XY uv( Precision::Infinite(), 0 );
8904       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
8905                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
8906       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8907       if ( _nodes.size() > 1 && uvOK )
8908       {
8909         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
8910         pos->SetUParameter( uv.X() );
8911         pos->SetVParameter( uv.Y() );
8912       }
8913     }
8914     if ( uvOK )
8915     {
8916       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
8917     }
8918     else
8919     {
8920       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
8921       _pos.pop_back();
8922       Block( eos.GetData() );
8923       return;
8924     }
8925   }
8926
8927   _len = len;
8928
8929   // notify _neibors
8930   if ( eos.ShapeType() != TopAbs_FACE )
8931   {
8932     for ( size_t i = 0; i < _neibors.size(); ++i )
8933       //if (  _len > _neibors[i]->GetSmooLen() )
8934         _neibors[i]->Set( MOVED );
8935
8936     Set( MOVED );
8937   }
8938   dumpMove( n ); //debug
8939 }
8940
8941 //================================================================================
8942 /*!
8943  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
8944  */
8945 //================================================================================
8946
8947 void _LayerEdge::Block( _SolidData& data )
8948 {
8949   //if ( Is( BLOCKED )) return;
8950   Set( BLOCKED );
8951
8952   _maxLen = _len;
8953   std::queue<_LayerEdge*> queue;
8954   queue.push( this );
8955
8956   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
8957   while ( !queue.empty() )
8958   {
8959     _LayerEdge* edge = queue.front(); queue.pop();
8960     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
8961     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
8962     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
8963     {
8964       _LayerEdge* neibor = edge->_neibors[iN];
8965       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
8966         continue;
8967       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
8968       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
8969       double minDist = pSrc.SquareDistance( pSrcN );
8970       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
8971       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
8972       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
8973       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
8974       if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() )
8975       {
8976         newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
8977       }
8978       if ( neibor->_maxLen > newMaxLen )
8979       {
8980         neibor->_maxLen = newMaxLen;
8981         if ( neibor->_maxLen < neibor->_len )
8982         {
8983           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
8984           while ( neibor->_len > neibor->_maxLen &&
8985                   neibor->NbSteps() > 1 )
8986             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
8987           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
8988           //neibor->Block( data );
8989         }
8990         queue.push( neibor );
8991       }
8992     }
8993   }
8994 }
8995
8996 //================================================================================
8997 /*!
8998  * \brief Remove last inflation step
8999  */
9000 //================================================================================
9001
9002 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9003 {
9004   if ( _pos.size() > curStep && _nodes.size() > 1 )
9005   {
9006     _pos.resize( curStep );
9007
9008     gp_Pnt      nXYZ = _pos.back();
9009     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9010     SMESH_TNodeXYZ curXYZ( n );
9011     if ( !eos._sWOL.IsNull() )
9012     {
9013       TopLoc_Location loc;
9014       if ( eos.SWOLType() == TopAbs_EDGE )
9015       {
9016         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
9017         pos->SetUParameter( nXYZ.X() );
9018         double f,l;
9019         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9020         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9021       }
9022       else
9023       {
9024         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
9025         pos->SetUParameter( nXYZ.X() );
9026         pos->SetVParameter( nXYZ.Y() );
9027         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9028         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9029       }
9030     }
9031     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9032     dumpMove( n );
9033
9034     if ( restoreLength )
9035     {
9036       _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9037     }
9038   }
9039 }
9040
9041 //================================================================================
9042 /*!
9043  * \brief Return index of a _pos distant from _normal
9044  */
9045 //================================================================================
9046
9047 int _LayerEdge::GetSmoothedPos( const double tol )
9048 {
9049   int iSmoothed = 0;
9050   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9051   {
9052     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9053     if ( normDist > tol * tol )
9054       iSmoothed = i;
9055   }
9056   return iSmoothed;
9057 }
9058
9059 //================================================================================
9060 /*!
9061  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9062  */
9063 //================================================================================
9064
9065 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9066 {
9067   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9068     return;
9069
9070   // find the 1st smoothed _pos
9071   int iSmoothed = GetSmoothedPos( tol );
9072   if ( !iSmoothed ) return;
9073
9074   //if ( 1 || Is( DISTORTED ))
9075   {
9076     gp_XYZ normal = _normal;
9077     if ( Is( NORMAL_UPDATED ))
9078       for ( size_t i = 1; i < _pos.size(); ++i )
9079       {
9080         normal = _pos[i] - _pos[0];
9081         double size = normal.Modulus();
9082         if ( size > RealSmall() )
9083         {
9084           normal /= size;
9085           break;
9086         }
9087       }
9088     const double r = 0.2;
9089     for ( int iter = 0; iter < 50; ++iter )
9090     {
9091       double minDot = 1;
9092       for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9093       {
9094         gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9095         gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9096         _pos[i] = newPos;
9097         double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9098         double newLen = ( 1-r ) * midLen + r * segLen[i];
9099         const_cast< double& >( segLen[i] ) = newLen;
9100         // check angle between normal and (_pos[i+1], _pos[i] )
9101         gp_XYZ posDir = _pos[i+1] - _pos[i];
9102         double size   = posDir.SquareModulus();
9103         if ( size > RealSmall() )
9104           minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9105       }
9106       if ( minDot > 0.5 * 0.5 )
9107         break;
9108     }
9109   }
9110   // else
9111   // {
9112   //   for ( size_t i = 1; i < _pos.size()-1; ++i )
9113   //   {
9114   //     if ((int) i < iSmoothed  &&  ( segLen[i] / segLen.back() < 0.5 ))
9115   //       continue;
9116
9117   //     double     wgt = segLen[i] / segLen.back();
9118   //     gp_XYZ normPos = _pos[0] + _normal * wgt * _len;
9119   //     gp_XYZ tgtPos  = ( 1 - wgt ) * _pos[0] +  wgt * _pos.back();
9120   //     gp_XYZ newPos  = ( 1 - wgt ) * normPos +  wgt * tgtPos;
9121   //     _pos[i] = newPos;
9122   //   }
9123   // }
9124 }
9125
9126 //================================================================================
9127 /*!
9128  * \brief Create layers of prisms
9129  */
9130 //================================================================================
9131
9132 bool _ViscousBuilder::refine(_SolidData& data)
9133 {
9134   SMESH_MesherHelper& helper = data.GetHelper();
9135   helper.SetElementsOnShape(false);
9136
9137   Handle(Geom_Curve) curve;
9138   Handle(ShapeAnalysis_Surface) surface;
9139   TopoDS_Edge geomEdge;
9140   TopoDS_Face geomFace;
9141   TopLoc_Location loc;
9142   double f,l, u = 0;
9143   gp_XY uv;
9144   vector< gp_XYZ > pos3D;
9145   bool isOnEdge;
9146   TGeomID prevBaseId = -1;
9147   TNode2Edge* n2eMap = 0;
9148   TNode2Edge::iterator n2e;
9149
9150   // Create intermediate nodes on each _LayerEdge
9151
9152   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9153   {
9154     _EdgesOnShape& eos = data._edgesOnShape[iS];
9155     if ( eos._edges.empty() ) continue;
9156
9157     if ( eos._edges[0]->_nodes.size() < 2 )
9158       continue; // on _noShrinkShapes
9159
9160     // get data of a shrink shape
9161     isOnEdge = false;
9162     geomEdge.Nullify(); geomFace.Nullify();
9163     curve.Nullify(); surface.Nullify();
9164     if ( !eos._sWOL.IsNull() )
9165     {
9166       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9167       if ( isOnEdge )
9168       {
9169         geomEdge = TopoDS::Edge( eos._sWOL );
9170         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9171       }
9172       else
9173       {
9174         geomFace = TopoDS::Face( eos._sWOL );
9175         surface  = helper.GetSurface( geomFace );
9176       }
9177     }
9178     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9179     {
9180       geomFace = TopoDS::Face( eos._shape );
9181       surface  = helper.GetSurface( geomFace );
9182       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
9183       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
9184       {
9185         eos._eosC1[ i ]->_toSmooth = true;
9186         for ( size_t j = 0; j < eos._eosC1[i]->_edges.size(); ++j )
9187           eos._eosC1[i]->_edges[j]->Set( _LayerEdge::SMOOTHED_C1 );
9188       }
9189     }
9190
9191     vector< double > segLen;
9192     for ( size_t i = 0; i < eos._edges.size(); ++i )
9193     {
9194       _LayerEdge& edge = *eos._edges[i];
9195       if ( edge._pos.size() < 2 )
9196         continue;
9197
9198       // get accumulated length of segments
9199       segLen.resize( edge._pos.size() );
9200       segLen[0] = 0.0;
9201       if ( eos._sWOL.IsNull() )
9202       {
9203         bool useNormal = true;
9204         bool   usePos  = false;
9205         bool smoothed  = false;
9206         double   preci = 0.1 * edge._len;
9207         if ( eos._toSmooth && edge._pos.size() > 2 )
9208         {
9209           smoothed = edge.GetSmoothedPos( preci );
9210         }
9211         if ( smoothed )
9212         {
9213           if ( !surface.IsNull() &&
9214                !data._convexFaces.count( eos._shapeID )) // edge smoothed on FACE
9215           {
9216             useNormal = usePos = false;
9217             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
9218             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
9219             {
9220               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
9221               if ( surface->Gap() < 2. * edge._len )
9222                 segLen[j] = surface->Gap();
9223               else
9224                 useNormal = true;
9225             }
9226           }
9227         }
9228         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
9229         {
9230 #ifndef __NODES_AT_POS
9231           useNormal = usePos = false;
9232           edge._pos[1] = edge._pos.back();
9233           edge._pos.resize( 2 );
9234           segLen.resize( 2 );
9235           segLen[ 1 ] = edge._len;
9236 #endif
9237         }
9238         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
9239         {
9240           useNormal = usePos = false;
9241           _LayerEdge tmpEdge; // get original _normal
9242           tmpEdge._nodes.push_back( edge._nodes[0] );
9243           if ( !setEdgeData( tmpEdge, eos, helper, data ))
9244             usePos = true;
9245           else
9246             for ( size_t j = 1; j < edge._pos.size(); ++j )
9247               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
9248         }
9249         if ( useNormal )
9250         {
9251           for ( size_t j = 1; j < edge._pos.size(); ++j )
9252             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
9253         }
9254         if ( usePos )
9255         {
9256           for ( size_t j = 1; j < edge._pos.size(); ++j )
9257             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
9258         }
9259         else
9260         {
9261           bool swapped = ( edge._pos.size() > 2 );
9262           while ( swapped )
9263           {
9264             swapped = false;
9265             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
9266               if ( segLen[j] > segLen.back() )
9267               {
9268                 segLen.erase( segLen.begin() + j );
9269                 edge._pos.erase( edge._pos.begin() + j );
9270                 --j;
9271               }
9272               else if ( segLen[j] < segLen[j-1] )
9273               {
9274                 std::swap( segLen[j], segLen[j-1] );
9275                 std::swap( edge._pos[j], edge._pos[j-1] );
9276                 swapped = true;
9277               }
9278           }
9279         }
9280         // smooth a path formed by edge._pos
9281 #ifndef __NODES_AT_POS
9282         if (( smoothed ) /*&&
9283             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
9284           edge.SmoothPos( segLen, preci );
9285 #endif
9286       }
9287       else if ( eos._isRegularSWOL ) // usual SWOL
9288       {
9289         for ( size_t j = 1; j < edge._pos.size(); ++j )
9290           segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
9291       }
9292       else if ( !surface.IsNull() ) // SWOL surface with singularities
9293       {
9294         pos3D.resize( edge._pos.size() );
9295         for ( size_t j = 0; j < edge._pos.size(); ++j )
9296           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
9297
9298         for ( size_t j = 1; j < edge._pos.size(); ++j )
9299           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
9300       }
9301
9302       // allocate memory for new nodes if it is not yet refined
9303       const SMDS_MeshNode* tgtNode = edge._nodes.back();
9304       if ( edge._nodes.size() == 2 )
9305       {
9306 #ifdef __NODES_AT_POS
9307         int nbNodes = edge._pos.size();
9308 #else
9309         int nbNodes = eos._hyp.GetNumberLayers() + 1;
9310 #endif
9311         edge._nodes.resize( nbNodes, 0 );
9312         edge._nodes[1] = 0;
9313         edge._nodes.back() = tgtNode;
9314       }
9315       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
9316       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
9317       if ( baseShapeId != prevBaseId )
9318       {
9319         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
9320         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
9321         prevBaseId = baseShapeId;
9322       }
9323       _LayerEdge* edgeOnSameNode = 0;
9324       bool        useExistingPos = false;
9325       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
9326       {
9327         edgeOnSameNode = n2e->second;
9328         useExistingPos = ( edgeOnSameNode->_len < edge._len );
9329         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
9330         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
9331         if ( isOnEdge )
9332         {
9333           SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
9334           epos->SetUParameter( otherTgtPos.X() );
9335         }
9336         else
9337         {
9338           SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
9339           fpos->SetUParameter( otherTgtPos.X() );
9340           fpos->SetVParameter( otherTgtPos.Y() );
9341         }
9342       }
9343       // calculate height of the first layer
9344       double h0;
9345       const double T = segLen.back(); //data._hyp.GetTotalThickness();
9346       const double f = eos._hyp.GetStretchFactor();
9347       const int    N = eos._hyp.GetNumberLayers();
9348       const double fPowN = pow( f, N );
9349       if ( fPowN - 1 <= numeric_limits<double>::min() )
9350         h0 = T / N;
9351       else
9352         h0 = T * ( f - 1 )/( fPowN - 1 );
9353
9354       const double zeroLen = std::numeric_limits<double>::min();
9355
9356       // create intermediate nodes
9357       double hSum = 0, hi = h0/f;
9358       size_t iSeg = 1;
9359       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
9360       {
9361         // compute an intermediate position
9362         hi *= f;
9363         hSum += hi;
9364         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
9365           ++iSeg;
9366         int iPrevSeg = iSeg-1;
9367         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
9368           --iPrevSeg;
9369         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
9370         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
9371 #ifdef __NODES_AT_POS
9372         pos = edge._pos[ iStep ];
9373 #endif
9374         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
9375         if ( !eos._sWOL.IsNull() )
9376         {
9377           // compute XYZ by parameters <pos>
9378           if ( isOnEdge )
9379           {
9380             u = pos.X();
9381             if ( !node )
9382               pos = curve->Value( u ).Transformed(loc);
9383           }
9384           else if ( eos._isRegularSWOL )
9385           {
9386             uv.SetCoord( pos.X(), pos.Y() );
9387             if ( !node )
9388               pos = surface->Value( pos.X(), pos.Y() );
9389           }
9390           else
9391           {
9392             uv.SetCoord( pos.X(), pos.Y() );
9393             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
9394             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
9395             if ( !node )
9396               pos = surface->Value( uv );
9397           }
9398         }
9399         // create or update the node
9400         if ( !node )
9401         {
9402           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
9403           if ( !eos._sWOL.IsNull() )
9404           {
9405             if ( isOnEdge )
9406               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
9407             else
9408               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
9409           }
9410           else
9411           {
9412             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
9413           }
9414         }
9415         else
9416         {
9417           if ( !eos._sWOL.IsNull() )
9418           {
9419             // make average pos from new and current parameters
9420             if ( isOnEdge )
9421             {
9422               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
9423               if ( useExistingPos )
9424                 u = helper.GetNodeU( geomEdge, node );
9425               pos = curve->Value( u ).Transformed(loc);
9426
9427               SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
9428               epos->SetUParameter( u );
9429             }
9430             else
9431             {
9432               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
9433               if ( useExistingPos )
9434                 uv = helper.GetNodeUV( geomFace, node );
9435               pos = surface->Value( uv );
9436
9437               SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
9438               fpos->SetUParameter( uv.X() );
9439               fpos->SetVParameter( uv.Y() );
9440             }
9441           }
9442           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
9443         }
9444       } // loop on edge._nodes
9445
9446       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
9447       {
9448         if ( isOnEdge )
9449           edge._pos.back().SetCoord( u, 0,0);
9450         else
9451           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
9452
9453         if ( edgeOnSameNode )
9454           edgeOnSameNode->_pos.back() = edge._pos.back();
9455       }
9456
9457     } // loop on eos._edges to create nodes
9458
9459
9460     if ( !getMeshDS()->IsEmbeddedMode() )
9461       // Log node movement
9462       for ( size_t i = 0; i < eos._edges.size(); ++i )
9463       {
9464         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
9465         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
9466       }
9467   }
9468
9469
9470   // Create volumes
9471
9472   helper.SetElementsOnShape(true);
9473
9474   vector< vector<const SMDS_MeshNode*>* > nnVec;
9475   set< vector<const SMDS_MeshNode*>* >    nnSet;
9476   set< int >                       degenEdgeInd;
9477   vector<const SMDS_MeshElement*>     degenVols;
9478   vector<int>                       isRiskySWOL;
9479
9480   TopExp_Explorer exp( data._solid, TopAbs_FACE );
9481   for ( ; exp.More(); exp.Next() )
9482   {
9483     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
9484     if ( data._ignoreFaceIds.count( faceID ))
9485       continue;
9486     const bool isReversedFace = data._reversedFaceIds.count( faceID );
9487     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
9488     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
9489     while ( fIt->more() )
9490     {
9491       const SMDS_MeshElement* face = fIt->next();
9492       const int            nbNodes = face->NbCornerNodes();
9493       nnVec.resize( nbNodes );
9494       nnSet.clear();
9495       degenEdgeInd.clear();
9496       isRiskySWOL.resize( nbNodes );
9497       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
9498       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
9499       for ( int iN = 0; iN < nbNodes; ++iN )
9500       {
9501         const SMDS_MeshNode* n = nIt->next();
9502         _LayerEdge*       edge = data._n2eMap[ n ];
9503         const int i = isReversedFace ? nbNodes-1-iN : iN;
9504         nnVec[ i ] = & edge->_nodes;
9505         maxZ = std::max( maxZ, nnVec[ i ]->size() );
9506         minZ = std::min( minZ, nnVec[ i ]->size() );
9507         //isRiskySWOL[ i ] = edge->Is( _LayerEdge::RISKY_SWOL );
9508
9509         if ( helper.HasDegeneratedEdges() )
9510           nnSet.insert( nnVec[ i ]);
9511       }
9512
9513       if ( maxZ == 0 )
9514         continue;
9515       if ( 0 < nnSet.size() && nnSet.size() < 3 )
9516         continue;
9517
9518       switch ( nbNodes )
9519       {
9520       case 3: // TRIA
9521       {
9522         // PENTA
9523         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9524           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
9525                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
9526
9527         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9528         {
9529           for ( int iN = 0; iN < nbNodes; ++iN )
9530             if ( nnVec[ iN ]->size() < iZ+1 )
9531               degenEdgeInd.insert( iN );
9532
9533           if ( degenEdgeInd.size() == 1 )  // PYRAM
9534           {
9535             int i2 = *degenEdgeInd.begin();
9536             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
9537             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
9538             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
9539                               (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
9540           }
9541           else  // TETRA
9542           {
9543             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
9544             helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
9545                               (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
9546                               (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
9547                               (*nnVec[ i3 ])[ iZ ]);
9548           }
9549         }
9550         break; // TRIA
9551       }
9552       case 4: // QUAD
9553       {
9554         // HEX
9555         for ( size_t iZ = 1; iZ < minZ; ++iZ )
9556           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
9557                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
9558                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
9559                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
9560
9561         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
9562         {
9563           for ( int iN = 0; iN < nbNodes; ++iN )
9564             if ( nnVec[ iN ]->size() < iZ+1 )
9565               degenEdgeInd.insert( iN );
9566
9567           switch ( degenEdgeInd.size() )
9568           {
9569           case 2: // PENTA
9570           {
9571             int i2 = *degenEdgeInd.begin();
9572             int i3 = *degenEdgeInd.rbegin();
9573             bool ok = ( i3 - i2 == 1 );
9574             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
9575             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
9576             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
9577
9578             const SMDS_MeshElement* vol =
9579               helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
9580                                 nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
9581             if ( !ok && vol )
9582               degenVols.push_back( vol );
9583           }
9584           break;
9585
9586           default: // degen HEX
9587           {
9588             const SMDS_MeshElement* vol =
9589               helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
9590                                 nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
9591                                 nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
9592                                 nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
9593                                 nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
9594                                 nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
9595                                 nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
9596                                 nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
9597             degenVols.push_back( vol );
9598           }
9599           }
9600         }
9601         break; // HEX
9602       }
9603       default:
9604         return error("Not supported type of element", data._index);
9605
9606       } // switch ( nbNodes )
9607     } // while ( fIt->more() )
9608   } // loop on FACEs
9609
9610   if ( !degenVols.empty() )
9611   {
9612     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
9613     if ( !err || err->IsOK() )
9614     {
9615       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
9616                                          "Degenerated volumes created" ));
9617       err->myBadElements.insert( err->myBadElements.end(),
9618                                  degenVols.begin(),degenVols.end() );
9619     }
9620   }
9621
9622   return true;
9623 }
9624
9625 //================================================================================
9626 /*!
9627  * \brief Shrink 2D mesh on faces to let space for inflated layers
9628  */
9629 //================================================================================
9630
9631 bool _ViscousBuilder::shrink()
9632 {
9633   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
9634   // inflated along FACE or EDGE)
9635   map< TGeomID, _SolidData* > f2sdMap;
9636   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9637   {
9638     _SolidData& data = _sdVec[i];
9639     TopTools_MapOfShape FFMap;
9640     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
9641     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
9642       if ( s2s->second.ShapeType() == TopAbs_FACE )
9643       {
9644         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
9645
9646         if ( FFMap.Add( (*s2s).second ))
9647           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
9648           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
9649           // by StdMeshers_QuadToTriaAdaptor
9650           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
9651           {
9652             SMESH_ProxyMesh::SubMesh* proxySub =
9653               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
9654             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9655             while ( fIt->more() )
9656               proxySub->AddElement( fIt->next() );
9657             // as a result 3D algo will use elements from proxySub and not from smDS
9658           }
9659       }
9660   }
9661
9662   SMESH_MesherHelper helper( *_mesh );
9663   helper.ToFixNodeParameters( true );
9664
9665   // EDGE's to shrink
9666   map< TGeomID, _Shrinker1D > e2shrMap;
9667   vector< _EdgesOnShape* > subEOS;
9668   vector< _LayerEdge* > lEdges;
9669
9670   // loop on FACES to srink mesh on
9671   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
9672   for ( ; f2sd != f2sdMap.end(); ++f2sd )
9673   {
9674     _SolidData&      data = *f2sd->second;
9675     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
9676     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
9677     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
9678
9679     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
9680
9681     helper.SetSubShape(F);
9682
9683     // ===========================
9684     // Prepare data for shrinking
9685     // ===========================
9686
9687     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
9688     // and hence all nodes on a FACE connected to 2d elements are to be smoothed
9689     vector < const SMDS_MeshNode* > smoothNodes;
9690     {
9691       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
9692       while ( nIt->more() )
9693       {
9694         const SMDS_MeshNode* n = nIt->next();
9695         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
9696           smoothNodes.push_back( n );
9697       }
9698     }
9699     // Find out face orientation
9700     double refSign = 1;
9701     const set<TGeomID> ignoreShapes;
9702     bool isOkUV;
9703     if ( !smoothNodes.empty() )
9704     {
9705       vector<_Simplex> simplices;
9706       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
9707       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
9708       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
9709       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
9710       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
9711         refSign = -1;
9712     }
9713
9714     // Find _LayerEdge's inflated along F
9715     subEOS.clear();
9716     lEdges.clear();
9717     {
9718       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
9719                                                                 /*complexFirst=*/true); //!!!
9720       while ( subIt->more() )
9721       {
9722         const TGeomID subID = subIt->next()->GetId();
9723         if ( data._noShrinkShapes.count( subID ))
9724           continue;
9725         _EdgesOnShape* eos = data.GetShapeEdges( subID );
9726         if ( !eos || eos->_sWOL.IsNull() ) continue;
9727
9728         subEOS.push_back( eos );
9729
9730         for ( size_t i = 0; i < eos->_edges.size(); ++i )
9731         {
9732           lEdges.push_back( eos->_edges[ i ] );
9733           prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
9734         }
9735       }
9736     }
9737
9738     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
9739     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9740     while ( fIt->more() )
9741       if ( const SMDS_MeshElement* f = fIt->next() )
9742         dumpChangeNodes( f );
9743     dumpFunctionEnd();
9744
9745     // Replace source nodes by target nodes in mesh faces to shrink
9746     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
9747     const SMDS_MeshNode* nodes[20];
9748     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9749     {
9750       _EdgesOnShape& eos = * subEOS[ iS ];
9751       for ( size_t i = 0; i < eos._edges.size(); ++i )
9752       {
9753         _LayerEdge& edge = *eos._edges[i];
9754         const SMDS_MeshNode* srcNode = edge._nodes[0];
9755         const SMDS_MeshNode* tgtNode = edge._nodes.back();
9756         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
9757         while ( fIt->more() )
9758         {
9759           const SMDS_MeshElement* f = fIt->next();
9760           if ( !smDS->Contains( f ))
9761             continue;
9762           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
9763           for ( int iN = 0; nIt->more(); ++iN )
9764           {
9765             const SMDS_MeshNode* n = nIt->next();
9766             nodes[iN] = ( n == srcNode ? tgtNode : n );
9767           }
9768           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
9769           dumpChangeNodes( f );
9770         }
9771       }
9772     }
9773     dumpFunctionEnd();
9774
9775     // find out if a FACE is concave
9776     const bool isConcaveFace = isConcave( F, helper );
9777
9778     // Create _SmoothNode's on face F
9779     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
9780     {
9781       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
9782       const bool sortSimplices = isConcaveFace;
9783       for ( size_t i = 0; i < smoothNodes.size(); ++i )
9784       {
9785         const SMDS_MeshNode* n = smoothNodes[i];
9786         nodesToSmooth[ i ]._node = n;
9787         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
9788         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
9789         // fix up incorrect uv of nodes on the FACE
9790         helper.GetNodeUV( F, n, 0, &isOkUV);
9791         dumpMove( n );
9792       }
9793       dumpFunctionEnd();
9794     }
9795     //if ( nodesToSmooth.empty() ) continue;
9796
9797     // Find EDGE's to shrink and set simpices to LayerEdge's
9798     set< _Shrinker1D* > eShri1D;
9799     {
9800       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9801       {
9802         _EdgesOnShape& eos = * subEOS[ iS ];
9803         if ( eos.SWOLType() == TopAbs_EDGE )
9804         {
9805           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
9806           _Shrinker1D& srinker  = e2shrMap[ edgeSM->GetId() ];
9807           eShri1D.insert( & srinker );
9808           srinker.AddEdge( eos._edges[0], eos, helper );
9809           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
9810           // restore params of nodes on EGDE if the EDGE has been already
9811           // srinked while srinking other FACE
9812           srinker.RestoreParams();
9813         }
9814         for ( size_t i = 0; i < eos._edges.size(); ++i )
9815         {
9816           _LayerEdge& edge = * eos._edges[i];
9817           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
9818         }
9819       }
9820     }
9821
9822     bool toFixTria = false; // to improve quality of trias by diagonal swap
9823     if ( isConcaveFace )
9824     {
9825       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
9826       if ( hasTria != hasQuad ) {
9827         toFixTria = hasTria;
9828       }
9829       else {
9830         set<int> nbNodesSet;
9831         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
9832         while ( fIt->more() && nbNodesSet.size() < 2 )
9833           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
9834         toFixTria = ( *nbNodesSet.begin() == 3 );
9835       }
9836     }
9837
9838     // ==================
9839     // Perform shrinking
9840     // ==================
9841
9842     bool shrinked = true;
9843     int nbBad, shriStep=0, smooStep=0;
9844     _SmoothNode::SmoothType smoothType
9845       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
9846     SMESH_Comment errMsg;
9847     while ( shrinked )
9848     {
9849       shriStep++;
9850       // Move boundary nodes (actually just set new UV)
9851       // -----------------------------------------------
9852       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
9853       shrinked = false;
9854       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9855       {
9856         _EdgesOnShape& eos = * subEOS[ iS ];
9857         for ( size_t i = 0; i < eos._edges.size(); ++i )
9858         {
9859           shrinked |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
9860         }
9861       }
9862       dumpFunctionEnd();
9863
9864       // Move nodes on EDGE's
9865       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
9866       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
9867       for ( ; shr != eShri1D.end(); ++shr )
9868         (*shr)->Compute( /*set3D=*/false, helper );
9869
9870       // Smoothing in 2D
9871       // -----------------
9872       int nbNoImpSteps = 0;
9873       bool       moved = true;
9874       nbBad = 1;
9875       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
9876       {
9877         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9878
9879         int oldBadNb = nbBad;
9880         nbBad = 0;
9881         moved = false;
9882         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
9883         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
9884         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9885         {
9886           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
9887                                             smooTy, /*set3D=*/isConcaveFace);
9888         }
9889         if ( nbBad < oldBadNb )
9890           nbNoImpSteps = 0;
9891         else
9892           nbNoImpSteps++;
9893
9894         dumpFunctionEnd();
9895       }
9896
9897       errMsg.clear();
9898       if ( nbBad > 0 )
9899         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
9900       if ( shriStep > 200 )
9901         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
9902       if ( !errMsg.empty() )
9903         break;
9904
9905       // Fix narrow triangles by swapping diagonals
9906       // ---------------------------------------
9907       if ( toFixTria )
9908       {
9909         set<const SMDS_MeshNode*> usedNodes;
9910         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
9911
9912         // update working data
9913         set<const SMDS_MeshNode*>::iterator n;
9914         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
9915         {
9916           n = usedNodes.find( nodesToSmooth[ i ]._node );
9917           if ( n != usedNodes.end())
9918           {
9919             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
9920                                     nodesToSmooth[ i ]._simplices,
9921                                     ignoreShapes, NULL,
9922                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
9923             usedNodes.erase( n );
9924           }
9925         }
9926         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
9927         {
9928           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
9929           if ( n != usedNodes.end())
9930           {
9931             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
9932                                     lEdges[i]->_simplices,
9933                                     ignoreShapes );
9934             usedNodes.erase( n );
9935           }
9936         }
9937       }
9938       // TODO: check effect of this additional smooth
9939       // additional laplacian smooth to increase allowed shrink step
9940       // for ( int st = 1; st; --st )
9941       // {
9942       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
9943       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
9944       //   {
9945       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
9946       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
9947       //   }
9948       // }
9949
9950     } // while ( shrinked )
9951
9952     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
9953     {
9954       // remove faces
9955       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
9956       {
9957         vector< const SMDS_MeshElement* > facesToRm;
9958         if ( psm )
9959         {
9960           facesToRm.reserve( psm->NbElements() );
9961           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
9962             facesToRm.push_back( ite->next() );
9963
9964           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
9965             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
9966               psm->Clear();
9967         }
9968         for ( size_t i = 0; i < facesToRm.size(); ++i )
9969           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
9970       }
9971       // remove nodes
9972       {
9973         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
9974         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
9975           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9976             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
9977                                 subEOS[iS]->_edges[i]->_nodes.end() );
9978         }
9979         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
9980         while ( itn->more() ) {
9981           const SMDS_MeshNode* n = itn->next();
9982           if ( !nodesToKeep.count( n ))
9983             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
9984         }
9985       }
9986       // restore position and UV of target nodes
9987       gp_Pnt p;
9988       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
9989         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
9990         {
9991           _LayerEdge*       edge = subEOS[iS]->_edges[i];
9992           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
9993           if ( edge->_pos.empty() ) continue;
9994           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
9995           {
9996             SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
9997             pos->SetUParameter( edge->_pos[0].X() );
9998             pos->SetVParameter( edge->_pos[0].Y() );
9999             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
10000           }
10001           else
10002           {
10003             SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10004             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
10005             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
10006           }
10007           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10008           dumpMove( tgtNode );
10009         }
10010       // shrink EDGE sub-meshes and set proxy sub-meshes
10011       UVPtStructVec uvPtVec;
10012       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
10013       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
10014       {
10015         _Shrinker1D* shr = (*shrIt);
10016         shr->Compute( /*set3D=*/true, helper );
10017
10018         // set proxy mesh of EDGEs w/o layers
10019         map< double, const SMDS_MeshNode* > nodes;
10020         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
10021         // remove refinement nodes
10022         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
10023         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
10024         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
10025         if ( u2n->second == sn0 || u2n->second == sn1 )
10026         {
10027           while ( u2n->second != tn0 && u2n->second != tn1 )
10028             ++u2n;
10029           nodes.erase( nodes.begin(), u2n );
10030         }
10031         u2n = --nodes.end();
10032         if ( u2n->second == sn0 || u2n->second == sn1 )
10033         {
10034           while ( u2n->second != tn0 && u2n->second != tn1 )
10035             --u2n;
10036           nodes.erase( ++u2n, nodes.end() );
10037         }
10038         // set proxy sub-mesh
10039         uvPtVec.resize( nodes.size() );
10040         u2n = nodes.begin();
10041         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
10042         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
10043         {
10044           uvPtVec[ i ].node = u2n->second;
10045           uvPtVec[ i ].param = u2n->first;
10046           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
10047         }
10048         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
10049         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10050       }
10051
10052       // set proxy mesh of EDGEs with layers
10053       vector< _LayerEdge* > edges;
10054       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
10055       {
10056         _EdgesOnShape& eos = * subEOS[ iS ];
10057         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
10058
10059         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
10060         data.SortOnEdge( E, eos._edges );
10061
10062         edges.clear();
10063         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
10064           if ( !eov->_edges.empty() )
10065             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
10066
10067         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
10068
10069         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
10070           if ( !eov->_edges.empty() )
10071             edges.push_back( eov->_edges[0] ); // on last VERTEX
10072
10073         uvPtVec.resize( edges.size() );
10074         for ( size_t i = 0; i < edges.size(); ++i )
10075         {
10076           uvPtVec[ i ].node = edges[i]->_nodes.back();
10077           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
10078           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
10079         }
10080         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
10081         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
10082         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
10083       }
10084       // temporary clear the FACE sub-mesh from faces made by refine()
10085       vector< const SMDS_MeshElement* > elems;
10086       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
10087       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10088         elems.push_back( ite->next() );
10089       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
10090         elems.push_back( ite->next() );
10091       smDS->Clear();
10092
10093       // compute the mesh on the FACE
10094       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
10095       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
10096
10097       // re-fill proxy sub-meshes of the FACE
10098       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10099         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
10100           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
10101             psm->AddElement( ite->next() );
10102
10103       // re-fill smDS
10104       for ( size_t i = 0; i < elems.size(); ++i )
10105         smDS->AddElement( elems[i] );
10106
10107       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
10108         return error( errMsg );
10109
10110     } // end of re-meshing in case of failed smoothing
10111     else
10112     {
10113       // No wrongly shaped faces remain; final smooth. Set node XYZ.
10114       bool isStructuredFixed = false;
10115       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
10116         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
10117       if ( !isStructuredFixed )
10118       {
10119         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
10120           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
10121
10122         for ( int st = 3; st; --st )
10123         {
10124           switch( st ) {
10125           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
10126           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
10127           case 3: smoothType = _SmoothNode::ANGULAR; break;
10128           }
10129           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
10130           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10131           {
10132             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
10133                                      smoothType,/*set3D=*/st==1 );
10134           }
10135           dumpFunctionEnd();
10136         }
10137       }
10138       if ( !getMeshDS()->IsEmbeddedMode() )
10139         // Log node movement
10140         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
10141         {
10142           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
10143           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
10144         }
10145     }
10146
10147     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
10148     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
10149
10150   } // loop on FACES to srink mesh on
10151
10152
10153   // Replace source nodes by target nodes in shrinked mesh edges
10154
10155   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
10156   for ( ; e2shr != e2shrMap.end(); ++e2shr )
10157     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
10158
10159   return true;
10160 }
10161
10162 //================================================================================
10163 /*!
10164  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
10165  */
10166 //================================================================================
10167
10168 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
10169                                            _EdgesOnShape&         eos,
10170                                            SMESH_MesherHelper&    helper,
10171                                            const SMESHDS_SubMesh* faceSubMesh)
10172 {
10173   const SMDS_MeshNode* srcNode = edge._nodes[0];
10174   const SMDS_MeshNode* tgtNode = edge._nodes.back();
10175
10176   if ( eos.SWOLType() == TopAbs_FACE )
10177   {
10178     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
10179     {
10180       edge._pos.clear();
10181       return srcNode == tgtNode;
10182     }
10183     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
10184     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
10185     gp_Vec2d uvDir( srcUV, tgtUV );
10186     double uvLen = uvDir.Magnitude();
10187     uvDir /= uvLen;
10188     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
10189     edge._len = uvLen;
10190
10191     edge._pos.resize(1);
10192     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
10193
10194     // set UV of source node to target node
10195     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10196     pos->SetUParameter( srcUV.X() );
10197     pos->SetVParameter( srcUV.Y() );
10198   }
10199   else // _sWOL is TopAbs_EDGE
10200   {
10201     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
10202     {
10203       edge._pos.clear();
10204       return srcNode == tgtNode;
10205     }
10206     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
10207     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
10208     if ( !edgeSM || edgeSM->NbElements() == 0 )
10209       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10210
10211     const SMDS_MeshNode* n2 = 0;
10212     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10213     while ( eIt->more() && !n2 )
10214     {
10215       const SMDS_MeshElement* e = eIt->next();
10216       if ( !edgeSM->Contains(e)) continue;
10217       n2 = e->GetNode( 0 );
10218       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
10219     }
10220     if ( !n2 )
10221       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
10222
10223     double uSrc = helper.GetNodeU( E, srcNode, n2 );
10224     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
10225     double u2   = helper.GetNodeU( E, n2, srcNode );
10226
10227     edge._pos.clear();
10228
10229     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
10230     {
10231       // tgtNode is located so that it does not make faces with wrong orientation
10232       return true;
10233     }
10234     edge._pos.resize(1);
10235     edge._pos[0].SetCoord( U_TGT, uTgt );
10236     edge._pos[0].SetCoord( U_SRC, uSrc );
10237     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
10238
10239     edge._simplices.resize( 1 );
10240     edge._simplices[0]._nPrev = n2;
10241
10242     // set U of source node to the target node
10243     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10244     pos->SetUParameter( uSrc );
10245   }
10246   return true;
10247 }
10248
10249 //================================================================================
10250 /*!
10251  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
10252  */
10253 //================================================================================
10254
10255 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
10256 {
10257   if ( edge._nodes.size() == 1 )
10258   {
10259     edge._pos.clear();
10260     edge._len = 0;
10261
10262     const SMDS_MeshNode* srcNode = edge._nodes[0];
10263     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
10264     if ( S.IsNull() ) return;
10265
10266     gp_Pnt p;
10267
10268     switch ( S.ShapeType() )
10269     {
10270     case TopAbs_EDGE:
10271     {
10272       double f,l;
10273       TopLoc_Location loc;
10274       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
10275       if ( curve.IsNull() ) return;
10276       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
10277       p = curve->Value( ePos->GetUParameter() );
10278       break;
10279     }
10280     case TopAbs_VERTEX:
10281     {
10282       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
10283       break;
10284     }
10285     default: return;
10286     }
10287     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
10288     dumpMove( srcNode );
10289   }
10290 }
10291
10292 //================================================================================
10293 /*!
10294  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
10295  */
10296 //================================================================================
10297
10298 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
10299                                   SMESH_MesherHelper&         helper,
10300                                   const bool                  is2D,
10301                                   const int                   step,
10302                                   set<const SMDS_MeshNode*> * involvedNodes)
10303 {
10304   SMESH::Controls::AspectRatio qualifier;
10305   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
10306   const double maxAspectRatio = is2D ? 4. : 2;
10307   _NodeCoordHelper xyz( F, helper, is2D );
10308
10309   // find bad triangles
10310
10311   vector< const SMDS_MeshElement* > badTrias;
10312   vector< double >                  badAspects;
10313   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
10314   SMDS_ElemIteratorPtr fIt = sm->GetElements();
10315   while ( fIt->more() )
10316   {
10317     const SMDS_MeshElement * f = fIt->next();
10318     if ( f->NbCornerNodes() != 3 ) continue;
10319     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
10320     double aspect = qualifier.GetValue( points );
10321     if ( aspect > maxAspectRatio )
10322     {
10323       badTrias.push_back( f );
10324       badAspects.push_back( aspect );
10325     }
10326   }
10327   if ( step == 1 )
10328   {
10329     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
10330     SMDS_ElemIteratorPtr fIt = sm->GetElements();
10331     while ( fIt->more() )
10332     {
10333       const SMDS_MeshElement * f = fIt->next();
10334       if ( f->NbCornerNodes() == 3 )
10335         dumpChangeNodes( f );
10336     }
10337     dumpFunctionEnd();
10338   }
10339   if ( badTrias.empty() )
10340     return;
10341
10342   // find couples of faces to swap diagonal
10343
10344   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
10345   vector< T2Trias > triaCouples; 
10346
10347   TIDSortedElemSet involvedFaces, emptySet;
10348   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
10349   {
10350     T2Trias trias    [3];
10351     double  aspRatio [3];
10352     int i1, i2, i3;
10353
10354     if ( !involvedFaces.insert( badTrias[iTia] ).second )
10355       continue;
10356     for ( int iP = 0; iP < 3; ++iP )
10357       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
10358
10359     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
10360     int bestCouple = -1;
10361     for ( int iSide = 0; iSide < 3; ++iSide )
10362     {
10363       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
10364       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
10365       trias [iSide].first  = badTrias[iTia];
10366       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
10367                                                              & i1, & i2 );
10368       if (( ! trias[iSide].second ) ||
10369           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
10370           ( ! sm->Contains( trias[iSide].second )))
10371         continue;
10372
10373       // aspect ratio of an adjacent tria
10374       for ( int iP = 0; iP < 3; ++iP )
10375         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
10376       double aspectInit = qualifier.GetValue( points2 );
10377
10378       // arrange nodes as after diag-swaping
10379       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
10380         i3 = helper.WrapIndex( i1-1, 3 );
10381       else
10382         i3 = helper.WrapIndex( i1+1, 3 );
10383       points1 = points;
10384       points1( 1+ iSide ) = points2( 1+ i3 );
10385       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
10386
10387       // aspect ratio after diag-swaping
10388       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
10389       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
10390         continue;
10391
10392       // prevent inversion of a triangle
10393       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
10394       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
10395       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
10396         continue;
10397
10398       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
10399         bestCouple = iSide;
10400     }
10401
10402     if ( bestCouple >= 0 )
10403     {
10404       triaCouples.push_back( trias[bestCouple] );
10405       involvedFaces.insert ( trias[bestCouple].second );
10406     }
10407     else
10408     {
10409       involvedFaces.erase( badTrias[iTia] );
10410     }
10411   }
10412   if ( triaCouples.empty() )
10413     return;
10414
10415   // swap diagonals
10416
10417   SMESH_MeshEditor editor( helper.GetMesh() );
10418   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10419   for ( size_t i = 0; i < triaCouples.size(); ++i )
10420   {
10421     dumpChangeNodes( triaCouples[i].first );
10422     dumpChangeNodes( triaCouples[i].second );
10423     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
10424   }
10425
10426   if ( involvedNodes )
10427     for ( size_t i = 0; i < triaCouples.size(); ++i )
10428     {
10429       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
10430                              triaCouples[i].first->end_nodes() );
10431       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
10432                              triaCouples[i].second->end_nodes() );
10433     }
10434
10435   // just for debug dump resulting triangles
10436   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
10437   for ( size_t i = 0; i < triaCouples.size(); ++i )
10438   {
10439     dumpChangeNodes( triaCouples[i].first );
10440     dumpChangeNodes( triaCouples[i].second );
10441   }
10442 }
10443
10444 //================================================================================
10445 /*!
10446  * \brief Move target node to it's final position on the FACE during shrinking
10447  */
10448 //================================================================================
10449
10450 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
10451                                  const TopoDS_Face&    F,
10452                                  _EdgesOnShape&        eos,
10453                                  SMESH_MesherHelper&   helper )
10454 {
10455   if ( _pos.empty() )
10456     return false; // already at the target position
10457
10458   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
10459
10460   if ( eos.SWOLType() == TopAbs_FACE )
10461   {
10462     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
10463     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
10464     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
10465     const double uvLen = tgtUV.Distance( curUV );
10466     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
10467
10468     // Select shrinking step such that not to make faces with wrong orientation.
10469     double stepSize = 1e100;
10470     for ( size_t i = 0; i < _simplices.size(); ++i )
10471     {
10472       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
10473       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
10474       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
10475       gp_XY dirN = uvN2 - uvN1;
10476       double det = uvDir.Crossed( dirN );
10477       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
10478       gp_XY dirN2Cur = curUV - uvN1;
10479       double step = dirN.Crossed( dirN2Cur ) / det;
10480       if ( step > 0 )
10481         stepSize = Min( step, stepSize );
10482     }
10483     gp_Pnt2d newUV;
10484     if ( uvLen <= stepSize )
10485     {
10486       newUV = tgtUV;
10487       _pos.clear();
10488     }
10489     else if ( stepSize > 0 )
10490     {
10491       newUV = curUV + uvDir.XY() * stepSize * kSafe;
10492     }
10493     else
10494     {
10495       return true;
10496     }
10497     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
10498     pos->SetUParameter( newUV.X() );
10499     pos->SetVParameter( newUV.Y() );
10500
10501 #ifdef __myDEBUG
10502     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10503     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10504     dumpMove( tgtNode );
10505 #endif
10506   }
10507   else // _sWOL is TopAbs_EDGE
10508   {
10509     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
10510     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
10511     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
10512
10513     const double u2     = helper.GetNodeU( E, n2, tgtNode );
10514     const double uSrc   = _pos[0].Coord( U_SRC );
10515     const double lenTgt = _pos[0].Coord( LEN_TGT );
10516
10517     double newU = _pos[0].Coord( U_TGT );
10518     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
10519     {
10520       _pos.clear();
10521     }
10522     else
10523     {
10524       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
10525     }
10526     tgtPos->SetUParameter( newU );
10527 #ifdef __myDEBUG
10528     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
10529     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
10530     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
10531     dumpMove( tgtNode );
10532 #endif
10533   }
10534
10535   return true;
10536 }
10537
10538 //================================================================================
10539 /*!
10540  * \brief Perform smooth on the FACE
10541  *  \retval bool - true if the node has been moved
10542  */
10543 //================================================================================
10544
10545 bool _SmoothNode::Smooth(int&                  nbBad,
10546                          Handle(Geom_Surface)& surface,
10547                          SMESH_MesherHelper&   helper,
10548                          const double          refSign,
10549                          SmoothType            how,
10550                          bool                  set3D)
10551 {
10552   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
10553
10554   // get uv of surrounding nodes
10555   vector<gp_XY> uv( _simplices.size() );
10556   for ( size_t i = 0; i < _simplices.size(); ++i )
10557     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
10558
10559   // compute new UV for the node
10560   gp_XY newPos (0,0);
10561   if ( how == TFI && _simplices.size() == 4 )
10562   {
10563     gp_XY corners[4];
10564     for ( size_t i = 0; i < _simplices.size(); ++i )
10565       if ( _simplices[i]._nOpp )
10566         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
10567       else
10568         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
10569
10570     newPos = helper.calcTFI ( 0.5, 0.5,
10571                               corners[0], corners[1], corners[2], corners[3],
10572                               uv[1], uv[2], uv[3], uv[0] );
10573   }
10574   else if ( how == ANGULAR )
10575   {
10576     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
10577   }
10578   else if ( how == CENTROIDAL && _simplices.size() > 3 )
10579   {
10580     // average centers of diagonals wieghted with their reciprocal lengths
10581     if ( _simplices.size() == 4 )
10582     {
10583       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
10584       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
10585       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
10586     }
10587     else
10588     {
10589       double sumWeight = 0;
10590       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
10591       for ( int i = 0; i < nb; ++i )
10592       {
10593         int iFrom = i + 2;
10594         int iTo   = i + _simplices.size() - 1;
10595         for ( int j = iFrom; j < iTo; ++j )
10596         {
10597           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
10598           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
10599           sumWeight += w;
10600           newPos += w * ( uv[i]+uv[i2] );
10601         }
10602       }
10603       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
10604     }
10605   }
10606   else
10607   {
10608     // Laplacian smooth
10609     for ( size_t i = 0; i < _simplices.size(); ++i )
10610       newPos += uv[i];
10611     newPos /= _simplices.size();
10612   }
10613
10614   // count quality metrics (orientation) of triangles around the node
10615   int nbOkBefore = 0;
10616   gp_XY tgtUV = helper.GetNodeUV( face, _node );
10617   for ( size_t i = 0; i < _simplices.size(); ++i )
10618     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
10619
10620   int nbOkAfter = 0;
10621   for ( size_t i = 0; i < _simplices.size(); ++i )
10622     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
10623
10624   if ( nbOkAfter < nbOkBefore )
10625   {
10626     nbBad += _simplices.size() - nbOkBefore;
10627     return false;
10628   }
10629
10630   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
10631   pos->SetUParameter( newPos.X() );
10632   pos->SetVParameter( newPos.Y() );
10633
10634 #ifdef __myDEBUG
10635   set3D = true;
10636 #endif
10637   if ( set3D )
10638   {
10639     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
10640     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
10641     dumpMove( _node );
10642   }
10643
10644   nbBad += _simplices.size() - nbOkAfter;
10645   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
10646 }
10647
10648 //================================================================================
10649 /*!
10650  * \brief Computes new UV using angle based smoothing technic
10651  */
10652 //================================================================================
10653
10654 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
10655                                      const gp_XY&   uvToFix,
10656                                      const double   refSign)
10657 {
10658   uv.push_back( uv.front() );
10659
10660   vector< gp_XY >  edgeDir ( uv.size() );
10661   vector< double > edgeSize( uv.size() );
10662   for ( size_t i = 1; i < edgeDir.size(); ++i )
10663   {
10664     edgeDir [i-1] = uv[i] - uv[i-1];
10665     edgeSize[i-1] = edgeDir[i-1].Modulus();
10666     if ( edgeSize[i-1] < numeric_limits<double>::min() )
10667       edgeDir[i-1].SetX( 100 );
10668     else
10669       edgeDir[i-1] /= edgeSize[i-1] * refSign;
10670   }
10671   edgeDir.back()  = edgeDir.front();
10672   edgeSize.back() = edgeSize.front();
10673
10674   gp_XY  newPos(0,0);
10675   //int    nbEdges = 0;
10676   double sumSize = 0;
10677   for ( size_t i = 1; i < edgeDir.size(); ++i )
10678   {
10679     if ( edgeDir[i-1].X() > 1. ) continue;
10680     int i1 = i-1;
10681     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
10682     if ( i == edgeDir.size() ) break;
10683     gp_XY p = uv[i];
10684     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
10685     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
10686     gp_XY bisec = norm1 + norm2;
10687     double bisecSize = bisec.Modulus();
10688     if ( bisecSize < numeric_limits<double>::min() )
10689     {
10690       bisec = -edgeDir[i1] + edgeDir[i];
10691       bisecSize = bisec.Modulus();
10692     }
10693     bisec /= bisecSize;
10694
10695     gp_XY  dirToN  = uvToFix - p;
10696     double distToN = dirToN.Modulus();
10697     if ( bisec * dirToN < 0 )
10698       distToN = -distToN;
10699
10700     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
10701     //++nbEdges;
10702     sumSize += edgeSize[i1] + edgeSize[i];
10703   }
10704   newPos /= /*nbEdges * */sumSize;
10705   return newPos;
10706 }
10707
10708 //================================================================================
10709 /*!
10710  * \brief Delete _SolidData
10711  */
10712 //================================================================================
10713
10714 _SolidData::~_SolidData()
10715 {
10716   TNode2Edge::iterator n2e = _n2eMap.begin();
10717   for ( ; n2e != _n2eMap.end(); ++n2e )
10718   {
10719     _LayerEdge* & e = n2e->second;
10720     if ( e )
10721     {
10722       delete e->_curvature;
10723       if ( e->_2neibors )
10724         delete e->_2neibors->_plnNorm;
10725       delete e->_2neibors;
10726     }
10727     delete e;
10728     e = 0;
10729   }
10730   _n2eMap.clear();
10731
10732   delete _helper;
10733   _helper = 0;
10734 }
10735
10736 //================================================================================
10737 /*!
10738  * \brief Keep a _LayerEdge inflated along the EDGE
10739  */
10740 //================================================================================
10741
10742 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
10743                            _EdgesOnShape&      eos,
10744                            SMESH_MesherHelper& helper )
10745 {
10746   // init
10747   if ( _nodes.empty() )
10748   {
10749     _edges[0] = _edges[1] = 0;
10750     _done = false;
10751   }
10752   // check _LayerEdge
10753   if ( e == _edges[0] || e == _edges[1] )
10754     return;
10755   if ( eos.SWOLType() != TopAbs_EDGE )
10756     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10757   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
10758     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
10759
10760   // store _LayerEdge
10761   _geomEdge = TopoDS::Edge( eos._sWOL );
10762   double f,l;
10763   BRep_Tool::Range( _geomEdge, f,l );
10764   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
10765   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
10766
10767   // Update _nodes
10768
10769   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
10770   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
10771
10772   if ( _nodes.empty() )
10773   {
10774     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
10775     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
10776       return;
10777     TopLoc_Location loc;
10778     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
10779     GeomAdaptor_Curve aCurve(C, f,l);
10780     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
10781
10782     int nbExpectNodes = eSubMesh->NbNodes();
10783     _initU  .reserve( nbExpectNodes );
10784     _normPar.reserve( nbExpectNodes );
10785     _nodes  .reserve( nbExpectNodes );
10786     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
10787     while ( nIt->more() )
10788     {
10789       const SMDS_MeshNode* node = nIt->next();
10790       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
10791            node == tgtNode0 || node == tgtNode1 )
10792         continue; // refinement nodes
10793       _nodes.push_back( node );
10794       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
10795       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
10796       _normPar.push_back(  len / totLen );
10797     }
10798   }
10799   else
10800   {
10801     // remove target node of the _LayerEdge from _nodes
10802     size_t nbFound = 0;
10803     for ( size_t i = 0; i < _nodes.size(); ++i )
10804       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
10805         _nodes[i] = 0, nbFound++;
10806     if ( nbFound == _nodes.size() )
10807       _nodes.clear();
10808   }
10809 }
10810
10811 //================================================================================
10812 /*!
10813  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
10814  */
10815 //================================================================================
10816
10817 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
10818 {
10819   if ( _done || _nodes.empty())
10820     return;
10821   const _LayerEdge* e = _edges[0];
10822   if ( !e ) e = _edges[1];
10823   if ( !e ) return;
10824
10825   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
10826             ( !_edges[1] || _edges[1]->_pos.empty() ));
10827
10828   double f,l;
10829   if ( set3D || _done )
10830   {
10831     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
10832     GeomAdaptor_Curve aCurve(C, f,l);
10833
10834     if ( _edges[0] )
10835       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10836     if ( _edges[1] )
10837       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10838     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
10839
10840     for ( size_t i = 0; i < _nodes.size(); ++i )
10841     {
10842       if ( !_nodes[i] ) continue;
10843       double len = totLen * _normPar[i];
10844       GCPnts_AbscissaPoint discret( aCurve, len, f );
10845       if ( !discret.IsDone() )
10846         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
10847       double u = discret.Parameter();
10848       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10849       pos->SetUParameter( u );
10850       gp_Pnt p = C->Value( u );
10851       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
10852     }
10853   }
10854   else
10855   {
10856     BRep_Tool::Range( _geomEdge, f,l );
10857     if ( _edges[0] )
10858       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
10859     if ( _edges[1] )
10860       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
10861     
10862     for ( size_t i = 0; i < _nodes.size(); ++i )
10863     {
10864       if ( !_nodes[i] ) continue;
10865       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
10866       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10867       pos->SetUParameter( u );
10868     }
10869   }
10870 }
10871
10872 //================================================================================
10873 /*!
10874  * \brief Restore initial parameters of nodes on EDGE
10875  */
10876 //================================================================================
10877
10878 void _Shrinker1D::RestoreParams()
10879 {
10880   if ( _done )
10881     for ( size_t i = 0; i < _nodes.size(); ++i )
10882     {
10883       if ( !_nodes[i] ) continue;
10884       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
10885       pos->SetUParameter( _initU[i] );
10886     }
10887   _done = false;
10888 }
10889
10890 //================================================================================
10891 /*!
10892  * \brief Replace source nodes by target nodes in shrinked mesh edges
10893  */
10894 //================================================================================
10895
10896 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
10897 {
10898   const SMDS_MeshNode* nodes[3];
10899   for ( int i = 0; i < 2; ++i )
10900   {
10901     if ( !_edges[i] ) continue;
10902
10903     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
10904     if ( !eSubMesh ) return;
10905     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
10906     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
10907     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
10908     while ( eIt->more() )
10909     {
10910       const SMDS_MeshElement* e = eIt->next();
10911       if ( !eSubMesh->Contains( e ))
10912           continue;
10913       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
10914       for ( int iN = 0; iN < e->NbNodes(); ++iN )
10915       {
10916         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
10917         nodes[iN] = ( n == srcNode ? tgtNode : n );
10918       }
10919       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
10920     }
10921   }
10922 }
10923
10924 //================================================================================
10925 /*!
10926  * \brief Creates 2D and 1D elements on boundaries of new prisms
10927  */
10928 //================================================================================
10929
10930 bool _ViscousBuilder::addBoundaryElements()
10931 {
10932   SMESH_MesherHelper helper( *_mesh );
10933
10934   vector< const SMDS_MeshNode* > faceNodes;
10935
10936   for ( size_t i = 0; i < _sdVec.size(); ++i )
10937   {
10938     _SolidData& data = _sdVec[i];
10939     TopTools_IndexedMapOfShape geomEdges;
10940     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
10941     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
10942     {
10943       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
10944       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
10945         continue;
10946
10947       // Get _LayerEdge's based on E
10948
10949       map< double, const SMDS_MeshNode* > u2nodes;
10950       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
10951         continue;
10952
10953       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
10954       TNode2Edge & n2eMap = data._n2eMap;
10955       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
10956       {
10957         //check if 2D elements are needed on E
10958         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
10959         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
10960         ledges.push_back( n2e->second );
10961         u2n++;
10962         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
10963           continue; // no layers on E
10964         ledges.push_back( n2eMap[ u2n->second ]);
10965
10966         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
10967         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
10968         int nbSharedPyram = 0;
10969         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
10970         while ( vIt->more() )
10971         {
10972           const SMDS_MeshElement* v = vIt->next();
10973           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
10974         }
10975         if ( nbSharedPyram > 1 )
10976           continue; // not free border of the pyramid
10977
10978         faceNodes.clear();
10979         faceNodes.push_back( ledges[0]->_nodes[0] );
10980         faceNodes.push_back( ledges[1]->_nodes[0] );
10981         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
10982         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
10983
10984         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
10985           continue; // faces already created
10986       }
10987       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
10988         ledges.push_back( n2eMap[ u2n->second ]);
10989
10990       // Find out orientation and type of face to create
10991
10992       bool reverse = false, isOnFace;
10993       
10994       map< TGeomID, TopoDS_Shape >::iterator e2f =
10995         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
10996       TopoDS_Shape F;
10997       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
10998       {
10999         F = e2f->second.Oriented( TopAbs_FORWARD );
11000         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
11001         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
11002           reverse = !reverse, F.Reverse();
11003         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
11004           reverse = !reverse;
11005       }
11006       else
11007       {
11008         // find FACE with layers sharing E
11009         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
11010         while ( fIt->more() && F.IsNull() )
11011         {
11012           const TopoDS_Shape* pF = fIt->next();
11013           if ( helper.IsSubShape( *pF, data._solid) &&
11014                !data._ignoreFaceIds.count( e2f->first ))
11015             F = *pF;
11016         }
11017       }
11018       // Find the sub-mesh to add new faces
11019       SMESHDS_SubMesh* sm = 0;
11020       if ( isOnFace )
11021         sm = getMeshDS()->MeshElements( F );
11022       else
11023         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
11024       if ( !sm )
11025         return error("error in addBoundaryElements()", data._index);
11026
11027       // Make faces
11028       const int dj1 = reverse ? 0 : 1;
11029       const int dj2 = reverse ? 1 : 0;
11030       for ( size_t j = 1; j < ledges.size(); ++j )
11031       {
11032         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
11033         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
11034         if ( nn1.size() == nn2.size() )
11035         {
11036           if ( isOnFace )
11037             for ( size_t z = 1; z < nn1.size(); ++z )
11038               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11039           else
11040             for ( size_t z = 1; z < nn1.size(); ++z )
11041               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
11042         }
11043         else if ( nn1.size() == 1 )
11044         {
11045           if ( isOnFace )
11046             for ( size_t z = 1; z < nn2.size(); ++z )
11047               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
11048           else
11049             for ( size_t z = 1; z < nn2.size(); ++z )
11050               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
11051         }
11052         else
11053         {
11054           if ( isOnFace )
11055             for ( size_t z = 1; z < nn1.size(); ++z )
11056               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
11057           else
11058             for ( size_t z = 1; z < nn1.size(); ++z )
11059               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
11060         }
11061       }
11062
11063       // Make edges
11064       for ( int isFirst = 0; isFirst < 2; ++isFirst )
11065       {
11066         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
11067         _EdgesOnShape* eos = data.GetShapeEdges( edge );
11068         if ( eos && eos->SWOLType() == TopAbs_EDGE )
11069         {
11070           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
11071           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
11072             continue;
11073           helper.SetSubShape( eos->_sWOL );
11074           helper.SetElementsOnShape( true );
11075           for ( size_t z = 1; z < nn.size(); ++z )
11076             helper.AddEdge( nn[z-1], nn[z] );
11077         }
11078       }
11079
11080     } // loop on EDGE's
11081   } // loop on _SolidData's
11082
11083   return true;
11084 }