Salome HOME
bos #20256: [CEA 18523] Porting SMESH to int 64 bits
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2021  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 "ObjectPool.hxx"
27 #include "SMDS_EdgePosition.hxx"
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_PolygonalFaceOfNodes.hxx"
32 #include "SMDS_SetIterator.hxx"
33 #include "SMESHDS_Group.hxx"
34 #include "SMESHDS_Hypothesis.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Algo.hxx"
37 #include "SMESH_Block.hxx"
38 #include "SMESH_ComputeError.hxx"
39 #include "SMESH_ControlsDef.hxx"
40 #include "SMESH_Gen.hxx"
41 #include "SMESH_Group.hxx"
42 #include "SMESH_HypoFilter.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MeshEditor.hxx"
46 #include "SMESH_MesherHelper.hxx"
47 #include "SMESH_ProxyMesh.hxx"
48 #include "SMESH_subMesh.hxx"
49 #include "SMESH_subMeshEventListener.hxx"
50 #include "StdMeshers_FaceSide.hxx"
51 #include "StdMeshers_ProjectionUtils.hxx"
52 #include "StdMeshers_ViscousLayers2D.hxx"
53
54 #include <Adaptor3d_HSurface.hxx>
55 #include <BRepAdaptor_Curve.hxx>
56 #include <BRepAdaptor_Curve2d.hxx>
57 #include <BRepAdaptor_Surface.hxx>
58 //#include <BRepLProp_CLProps.hxx>
59 #include <BRepLProp_SLProps.hxx>
60 #include <BRepOffsetAPI_MakeOffsetShape.hxx>
61 #include <BRep_Tool.hxx>
62 #include <Bnd_B2d.hxx>
63 #include <Bnd_B3d.hxx>
64 #include <ElCLib.hxx>
65 #include <GCPnts_AbscissaPoint.hxx>
66 #include <GCPnts_TangentialDeflection.hxx>
67 #include <Geom2d_Circle.hxx>
68 #include <Geom2d_Line.hxx>
69 #include <Geom2d_TrimmedCurve.hxx>
70 #include <GeomAdaptor_Curve.hxx>
71 #include <GeomLib.hxx>
72 #include <Geom_Circle.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Line.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Precision.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <Standard_Failure.hxx>
79 #include <TColStd_Array1OfReal.hxx>
80 #include <TopExp.hxx>
81 #include <TopExp_Explorer.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListOfShape.hxx>
84 #include <TopTools_MapIteratorOfMapOfShape.hxx>
85 #include <TopTools_MapOfShape.hxx>
86 #include <TopoDS.hxx>
87 #include <TopoDS_Edge.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Vertex.hxx>
90 #include <gp_Ax1.hxx>
91 #include <gp_Cone.hxx>
92 #include <gp_Sphere.hxx>
93 #include <gp_Vec.hxx>
94 #include <gp_XY.hxx>
95
96 #include <cmath>
97 #include <limits>
98 #include <list>
99 #include <queue>
100 #include <string>
101 #include <unordered_map>
102
103 #ifdef _DEBUG_
104 //#define __myDEBUG
105 //#define __NOT_INVALIDATE_BAD_SMOOTH
106 //#define __NODES_AT_POS
107 #endif
108
109 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
110 #define BLOCK_INFLATION // of individual _LayerEdge's
111 #define OLD_NEF_POLYGON
112
113 using namespace std;
114
115 //================================================================================
116 namespace VISCOUS_3D
117 {
118   typedef int TGeomID;
119
120   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
121
122   const double theMinSmoothCosin = 0.1;
123   const double theSmoothThickToElemSizeRatio = 0.6;
124   const double theMinSmoothTriaAngle = 30;
125   const double theMinSmoothQuadAngle = 45;
126
127   // what part of thickness is allowed till intersection
128   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
129   const double theThickToIntersection = 1.5;
130
131   bool needSmoothing( double cosin, double tgtThick, double elemSize )
132   {
133     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
134   }
135   double getSmoothingThickness( double cosin, double elemSize )
136   {
137     return theSmoothThickToElemSizeRatio * elemSize / cosin;
138   }
139
140   /*!
141    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
142    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
143    */
144   struct _MeshOfSolid : public SMESH_ProxyMesh,
145                         public SMESH_subMeshEventListenerData
146   {
147     bool                  _n2nMapComputed;
148     SMESH_ComputeErrorPtr _warning;
149
150     _MeshOfSolid( SMESH_Mesh* mesh)
151       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
152     {
153       SMESH_ProxyMesh::setMesh( *mesh );
154     }
155
156     // returns submesh for a geom face
157     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
158     {
159       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
160       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
161     }
162     void setNode2Node(const SMDS_MeshNode*                 srcNode,
163                       const SMDS_MeshNode*                 proxyNode,
164                       const SMESH_ProxyMesh::SubMesh* subMesh)
165     {
166       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
167     }
168   };
169   //--------------------------------------------------------------------------------
170   /*!
171    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
172    * It is used to clear an inferior dim sub-meshes modified by viscous layers
173    */
174   class _ShrinkShapeListener : SMESH_subMeshEventListener
175   {
176     _ShrinkShapeListener()
177       : SMESH_subMeshEventListener(/*isDeletable=*/false,
178                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
179   public:
180     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
181     virtual void ProcessEvent(const int                       event,
182                               const int                       eventType,
183                               SMESH_subMesh*                  solidSM,
184                               SMESH_subMeshEventListenerData* data,
185                               const SMESH_Hypothesis*         hyp)
186     {
187       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
188       {
189         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
190       }
191     }
192   };
193   //--------------------------------------------------------------------------------
194   /*!
195    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
196    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
197    * delete the data as soon as it has been used
198    */
199   class _ViscousListener : SMESH_subMeshEventListener
200   {
201     _ViscousListener():
202       SMESH_subMeshEventListener(/*isDeletable=*/false,
203                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
204     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
205   public:
206     virtual void ProcessEvent(const int                       event,
207                               const int                       eventType,
208                               SMESH_subMesh*                  subMesh,
209                               SMESH_subMeshEventListenerData* /*data*/,
210                               const SMESH_Hypothesis*         /*hyp*/)
211     {
212       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
213           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
214             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
215       {
216         // delete SMESH_ProxyMesh containing temporary faces
217         subMesh->DeleteEventListener( this );
218       }
219     }
220     // Finds or creates proxy mesh of the solid
221     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
222                                       const TopoDS_Shape& solid,
223                                       bool                toCreate=false)
224     {
225       if ( !mesh ) return 0;
226       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
227       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
228       if ( !data && toCreate )
229       {
230         data = new _MeshOfSolid(mesh);
231         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
232         sm->SetEventListener( Get(), data, sm );
233       }
234       return data;
235     }
236     // Removes proxy mesh of the solid
237     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
238     {
239       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
240     }
241   };
242   
243   //================================================================================
244   /*!
245    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
246    * the main shape when sub-mesh of the main shape is cleared,
247    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
248    * is cleared
249    */
250   //================================================================================
251
252   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
253   {
254     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
255     SMESH_subMeshEventListenerData* data =
256       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
257     if ( data )
258     {
259       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
260            data->mySubMeshes.end())
261         data->mySubMeshes.push_back( sub );
262     }
263     else
264     {
265       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
266       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
267     }
268   }
269   struct _SolidData;
270   //--------------------------------------------------------------------------------
271   /*!
272    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
273    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
274    * The class is used to check validity of face or volumes around a smoothed node;
275    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
276    */
277   struct _Simplex
278   {
279     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
280     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
281     _Simplex(const SMDS_MeshNode* nPrev=0,
282              const SMDS_MeshNode* nNext=0,
283              const SMDS_MeshNode* nOpp=0)
284       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
285     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
286     {
287       const double M[3][3] =
288         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
289          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
290          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
291       vol = ( + M[0][0] * M[1][1] * M[2][2]
292               + M[0][1] * M[1][2] * M[2][0]
293               + M[0][2] * M[1][0] * M[2][1]
294               - M[0][0] * M[1][2] * M[2][1]
295               - M[0][1] * M[1][0] * M[2][2]
296               - M[0][2] * M[1][1] * M[2][0]);
297       return vol > 1e-100;
298     }
299     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
300     {
301       SMESH_TNodeXYZ pSrc( nSrc );
302       return IsForward( &pSrc, &pTgt, vol );
303     }
304     bool IsForward(const gp_XY&         tgtUV,
305                    const SMDS_MeshNode* smoothedNode,
306                    const TopoDS_Face&   face,
307                    SMESH_MesherHelper&  helper,
308                    const double         refSign) const
309     {
310       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
311       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
312       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
313       double d = v1 ^ v2;
314       return d*refSign > 1e-100;
315     }
316     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
317     {
318       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
319       if ( !_nOpp ) // triangle
320       {
321         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
322         double tp2 = tp.SquareMagnitude();
323         double pn2 = pn.SquareMagnitude();
324         double nt2 = nt.SquareMagnitude();
325
326         if ( tp2 < pn2 && tp2 < nt2 )
327           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
328         else if ( pn2 < nt2 )
329           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
330         else
331           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
332
333         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
334                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
335         return minAngle < theMaxCos2;
336       }
337       else // quadrangle
338       {
339         SMESH_TNodeXYZ pOpp( _nOpp );
340         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
341         double tp2 = tp.SquareMagnitude();
342         double po2 = po.SquareMagnitude();
343         double on2 = on.SquareMagnitude();
344         double nt2 = nt.SquareMagnitude();
345         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
346                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
347                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
348                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
349
350         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
351                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
352         return minAngle < theMaxCos2;
353       }
354     }
355     bool IsNeighbour(const _Simplex& other) const
356     {
357       return _nPrev == other._nNext || _nNext == other._nPrev;
358     }
359     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
360     static void GetSimplices( const SMDS_MeshNode* node,
361                               vector<_Simplex>&   simplices,
362                               const set<TGeomID>& ingnoreShapes,
363                               const _SolidData*   dataToCheckOri = 0,
364                               const bool          toSort = false);
365     static void SortSimplices(vector<_Simplex>& simplices);
366   };
367   //--------------------------------------------------------------------------------
368   /*!
369    * Structure used to take into account surface curvature while smoothing
370    */
371   struct _Curvature
372   {
373     double   _r; // radius
374     double   _k; // factor to correct node smoothed position
375     double   _h2lenRatio; // avgNormProj / (2*avgDist)
376     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
377   public:
378     static _Curvature* New( double avgNormProj, double avgDist );
379     double lenDelta(double len) const { return _k * ( _r + len ); }
380     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
381   };
382   //--------------------------------------------------------------------------------
383
384   struct _2NearEdges;
385   struct _LayerEdge;
386   struct _EdgesOnShape;
387   struct _Smoother1D;
388   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
389
390   //--------------------------------------------------------------------------------
391   /*!
392    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
393    * and a node of the most internal layer (_nodes.back())
394    */
395   struct _LayerEdge
396   {
397     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
398
399     vector< const SMDS_MeshNode*> _nodes;
400
401     gp_XYZ              _normal;    // to boundary of solid
402     vector<gp_XYZ>      _pos;       // points computed during inflation
403     double              _len;       // length achieved with the last inflation step
404     double              _maxLen;    // maximal possible length
405     double              _cosin;     // of angle (_normal ^ surface)
406     double              _minAngle;  // of _simplices
407     double              _lenFactor; // to compute _len taking _cosin into account
408     int                 _flags;
409
410     // simplices connected to the source node (_nodes[0]);
411     // used for smoothing and quality check of _LayerEdge's based on the FACE
412     vector<_Simplex>    _simplices;
413     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
414     PSmooFun            _smooFunction; // smoothing function
415     _Curvature*         _curvature;
416     // data for smoothing of _LayerEdge's based on the EDGE
417     _2NearEdges*        _2neibors;
418
419     enum EFlags { TO_SMOOTH       = 0x0000001,
420                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
421                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
422                   DIFFICULT       = 0x0000008, // near concave VERTEX
423                   ON_CONCAVE_FACE = 0x0000010,
424                   BLOCKED         = 0x0000020, // not to inflate any more
425                   INTERSECTED     = 0x0000040, // close intersection with a face found
426                   NORMAL_UPDATED  = 0x0000080,
427                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
428                   MARKED          = 0x0000200, // local usage
429                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
430                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
431                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
432                   DISTORTED       = 0x0002000, // was bad before smoothing
433                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
434                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
435                   UNUSED_FLAG     = 0x0100000  // to add user flags after
436     };
437     bool Is   ( int flag ) const { return _flags & flag; }
438     void Set  ( int flag ) { _flags |= flag; }
439     void Unset( int flag ) { _flags &= ~flag; }
440     std::string DumpFlags() const; // debug
441
442     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
443     bool SetNewLength2d( Handle(Geom_Surface)& surface,
444                          const TopoDS_Face&    F,
445                          _EdgesOnShape&        eos,
446                          SMESH_MesherHelper&   helper );
447     void SetDataByNeighbors( const SMDS_MeshNode* n1,
448                              const SMDS_MeshNode* n2,
449                              const _EdgesOnShape& eos,
450                              SMESH_MesherHelper&  helper);
451     void Block( _SolidData& data );
452     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
453     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
454                             const TNode2Edge&     n2eMap);
455     void SmoothPos( const vector< double >& segLen, const double tol );
456     int  GetSmoothedPos( const double tol );
457     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
458     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
459     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
460     void SmoothWoCheck();
461     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
462                       const TopoDS_Face&             F,
463                       SMESH_MesherHelper&            helper);
464     void MoveNearConcaVer( const _EdgesOnShape*    eov,
465                            const _EdgesOnShape*    eos,
466                            const int               step,
467                            vector< _LayerEdge* > & badSmooEdges);
468     bool FindIntersection( SMESH_ElementSearcher&   searcher,
469                            double &                 distance,
470                            const double&            epsilon,
471                            _EdgesOnShape&           eos,
472                            const SMDS_MeshElement** face = 0);
473     bool SegTriaInter( const gp_Ax1&        lastSegment,
474                        const gp_XYZ&        p0,
475                        const gp_XYZ&        p1,
476                        const gp_XYZ&        p2,
477                        double&              dist,
478                        const double&        epsilon) const;
479     bool SegTriaInter( const gp_Ax1&        lastSegment,
480                        const SMDS_MeshNode* n0,
481                        const SMDS_MeshNode* n1,
482                        const SMDS_MeshNode* n2,
483                        double&              dist,
484                        const double&        epsilon) const
485     { return SegTriaInter( lastSegment,
486                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
487                            dist, epsilon );
488     }
489     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
490     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
491     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
492     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
493     bool   IsOnEdge() const { return _2neibors; }
494     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
495     int    BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
496     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
497     void   SetCosin( double cosin );
498     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
499     void   SetMaxLen( double l ) { _maxLen = l; }
500     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
501     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
502     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
503       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
504     }
505     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
506
507     gp_XYZ smoothLaplacian();
508     gp_XYZ smoothAngular();
509     gp_XYZ smoothLengthWeighted();
510     gp_XYZ smoothCentroidal();
511     gp_XYZ smoothNefPolygon();
512
513     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
514     static const int theNbSmooFuns = FUN_NB;
515     static PSmooFun _funs[theNbSmooFuns];
516     static const char* _funNames[theNbSmooFuns+1];
517     int smooFunID( PSmooFun fun=0) const;
518   };
519   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
520                                                             &_LayerEdge::smoothLengthWeighted,
521                                                             &_LayerEdge::smoothCentroidal,
522                                                             &_LayerEdge::smoothNefPolygon,
523                                                             &_LayerEdge::smoothAngular };
524   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
525                                                          "LengthWeighted",
526                                                          "Centroidal",
527                                                          "NefPolygon",
528                                                          "Angular",
529                                                          "None"};
530   struct _LayerEdgeCmp
531   {
532     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
533     {
534       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
535       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
536     }
537   };
538   //--------------------------------------------------------------------------------
539   /*!
540    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
541    */
542   struct _halfPlane
543   {
544     gp_XY _pos, _dir, _inNorm;
545     bool IsOut( const gp_XY p, const double tol ) const
546     {
547       return _inNorm * ( p - _pos ) < -tol;
548     }
549     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
550     {
551       //const double eps = 1e-10;
552       double D = _dir.Crossed( hp._dir );
553       if ( fabs(D) < std::numeric_limits<double>::min())
554         return false;
555       gp_XY vec21 = _pos - hp._pos; 
556       double u = hp._dir.Crossed( vec21 ) / D; 
557       intPnt = _pos + _dir * u;
558       return true;
559     }
560   };
561   //--------------------------------------------------------------------------------
562   /*!
563    * Structure used to smooth a _LayerEdge based on an EDGE.
564    */
565   struct _2NearEdges
566   {
567     double               _wgt  [2]; // weights of _nodes
568     _LayerEdge*          _edges[2];
569
570      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
571     gp_XYZ*              _plnNorm;
572
573     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
574     ~_2NearEdges(){ delete _plnNorm; }
575     const SMDS_MeshNode* tgtNode(bool is2nd) {
576       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
577     }
578     const SMDS_MeshNode* srcNode(bool is2nd) {
579       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
580     }
581     void reverse() {
582       std::swap( _wgt  [0], _wgt  [1] );
583       std::swap( _edges[0], _edges[1] );
584     }
585     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
586       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
587     }
588     bool include( const _LayerEdge* e ) {
589       return ( _edges[0] == e || _edges[1] == e );
590     }
591   };
592
593
594   //--------------------------------------------------------------------------------
595   /*!
596    * \brief Layers parameters got by averaging several hypotheses
597    */
598   struct AverageHyp
599   {
600     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
601       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
602     {
603       Add( hyp );
604     }
605     void Add( const StdMeshers_ViscousLayers* hyp )
606     {
607       if ( hyp )
608       {
609         _nbHyps++;
610         _nbLayers       = hyp->GetNumberLayers();
611         //_thickness     += hyp->GetTotalThickness();
612         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
613         _stretchFactor += hyp->GetStretchFactor();
614         _method         = hyp->GetMethod();
615         if ( _groupName.empty() )
616           _groupName = hyp->GetGroupName();
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     bool   ToCreateGroup()     const { return !_groupName.empty(); }
624     const std::string& GetGroupName() const { return _groupName; }
625
626     bool   UseSurfaceNormal()  const
627     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
628     bool   ToSmooth()          const
629     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
630     bool   IsOffsetMethod()    const
631     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
632
633     bool operator==( const AverageHyp& other ) const
634     {
635       return ( _nbLayers == other._nbLayers &&
636                _method   == other._method   &&
637                Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
638                Equals( GetStretchFactor(), other.GetStretchFactor() ));
639     }
640     static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
641
642   private:
643     int         _nbLayers, _nbHyps, _method;
644     double      _thickness, _stretchFactor;
645     std::string _groupName;
646   };
647
648   //--------------------------------------------------------------------------------
649   /*!
650    * \brief _LayerEdge's on a shape and other shape data
651    */
652   struct _EdgesOnShape
653   {
654     vector< _LayerEdge* > _edges;
655
656     TopoDS_Shape          _shape;
657     TGeomID               _shapeID;
658     SMESH_subMesh *       _subMesh;
659     // face or edge w/o layer along or near which _edges are inflated
660     TopoDS_Shape          _sWOL;
661     bool                  _isRegularSWOL; // w/o singularities
662     // averaged StdMeshers_ViscousLayers parameters
663     AverageHyp            _hyp;
664     bool                  _toSmooth;
665     _Smoother1D*          _edgeSmoother;
666     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
667     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
668
669     typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
670     TFace2NormMap            _faceNormals; // if _shape is FACE
671     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
672
673     Handle(ShapeAnalysis_Surface) _offsetSurf;
674     _LayerEdge*                   _edgeForOffset;
675
676     _SolidData*            _data; // parent SOLID
677
678     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
679     size_t           size() const { return _edges.size(); }
680     TopAbs_ShapeEnum ShapeType() const
681     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
682     TopAbs_ShapeEnum SWOLType() const
683     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
684     bool             HasC1( const _EdgesOnShape* other ) const
685     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
686     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
687     _SolidData&      GetData() const { return *_data; }
688
689     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0) {}
690     ~_EdgesOnShape();
691   };
692
693   //--------------------------------------------------------------------------------
694   /*!
695    * \brief Convex FACE whose radius of curvature is less than the thickness of
696    *        layers. It is used to detect distortion of prisms based on a convex
697    *        FACE and to update normals to enable further increasing the thickness
698    */
699   struct _ConvexFace
700   {
701     TopoDS_Face                     _face;
702
703     // edges whose _simplices are used to detect prism distortion
704     vector< _LayerEdge* >           _simplexTestEdges;
705
706     // map a sub-shape to _SolidData::_edgesOnShape
707     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
708
709     bool                            _isTooCurved;
710     bool                            _normalsFixed;
711     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
712
713     double GetMaxCurvature( _SolidData&         data,
714                             _EdgesOnShape&      eof,
715                             BRepLProp_SLProps&  surfProp,
716                             SMESH_MesherHelper& helper);
717
718     bool GetCenterOfCurvature( _LayerEdge*         ledge,
719                                BRepLProp_SLProps&  surfProp,
720                                SMESH_MesherHelper& helper,
721                                gp_Pnt &            center ) const;
722     bool CheckPrisms() const;
723   };
724
725   //--------------------------------------------------------------------------------
726   /*!
727    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
728    *        at inflation up to the full thickness. A detected collision
729    *        is fixed in updateNormals()
730    */
731   struct _CollisionEdges
732   {
733     _LayerEdge*           _edge;
734     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
735     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
736     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
737   };
738
739   //--------------------------------------------------------------------------------
740   /*!
741    * \brief Data of a SOLID
742    */
743   struct _SolidData
744   {
745     typedef const StdMeshers_ViscousLayers* THyp;
746     TopoDS_Shape                    _solid;
747     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
748     TGeomID                         _index; // SOLID id
749     _MeshOfSolid*                   _proxyMesh;
750     bool                            _done;
751     list< THyp >                    _hyps;
752     list< TopoDS_Shape >            _hypShapes;
753     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
754     set< TGeomID >                  _reversedFaceIds;
755     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
756
757     double                          _stepSize, _stepSizeCoeff, _geomSize;
758     const SMDS_MeshNode*            _stepSizeNodes[2];
759
760     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
761
762     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
763     map< TGeomID, TNode2Edge* >     _s2neMap;
764     // _LayerEdge's with underlying shapes
765     vector< _EdgesOnShape >         _edgesOnShape;
766
767     // key:   an ID of shape (EDGE or VERTEX) shared by a FACE with
768     //        layers and a FACE w/o layers
769     // value: the shape (FACE or EDGE) to shrink mesh on.
770     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
771     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
772
773     // Convex FACEs whose radius of curvature is less than the thickness of layers
774     map< TGeomID, _ConvexFace >      _convexFaces;
775
776     // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
777     // the adjacent SOLID
778     set< TGeomID >                   _noShrinkShapes;
779
780     int                              _nbShapesToSmooth;
781
782     vector< _CollisionEdges >        _collisionEdges;
783     set< TGeomID >                   _concaveFaces;
784
785     double                           _maxThickness; // of all _hyps
786     double                           _minThickness; // of all _hyps
787
788     double                           _epsilon; // precision for SegTriaInter()
789
790     SMESH_MesherHelper*              _helper;
791
792     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
793                _MeshOfSolid*       m=0)
794       :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
795     ~_SolidData() { delete _helper; _helper = 0; }
796
797     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
798     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
799
800     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
801       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
802       return id2face == _convexFaces.end() ? 0 : & id2face->second;
803     }
804     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
805     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
806     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
807     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
808
809     SMESH_MesherHelper& GetHelper() const { return *_helper; }
810
811     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
812       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
813         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
814           _edgesOnShape[i]._edges[j]->Unset( flag );
815     }
816     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
817                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
818
819     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
820   };
821   //--------------------------------------------------------------------------------
822   /*!
823    * \brief Offset plane used in getNormalByOffset()
824    */
825   struct _OffsetPlane
826   {
827     gp_Pln _plane;
828     int    _faceIndex;
829     int    _faceIndexNext[2];
830     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
831     bool   _isLineOK[2];
832     _OffsetPlane() {
833       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
834     }
835     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
836                                     const TopoDS_Edge&   E,
837                                     const TopoDS_Vertex& V );
838     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
839     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
840   };
841   //--------------------------------------------------------------------------------
842   /*!
843    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
844    */
845   struct _CentralCurveOnEdge
846   {
847     bool                  _isDegenerated;
848     vector< gp_Pnt >      _curvaCenters;
849     vector< _LayerEdge* > _ledges;
850     vector< gp_XYZ >      _normals; // new normal for each of _ledges
851     vector< double >      _segLength2;
852
853     TopoDS_Edge           _edge;
854     TopoDS_Face           _adjFace;
855     bool                  _adjFaceToSmooth;
856
857     void Append( const gp_Pnt& center, _LayerEdge* ledge )
858     {
859       if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
860         return;
861       if ( _curvaCenters.size() > 0 )
862         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
863       _curvaCenters.push_back( center );
864       _ledges.push_back( ledge );
865       _normals.push_back( ledge->_normal );
866     }
867     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
868     void SetShapes( const TopoDS_Edge&  edge,
869                     const _ConvexFace&  convFace,
870                     _SolidData&         data,
871                     SMESH_MesherHelper& helper);
872   };
873   //--------------------------------------------------------------------------------
874   /*!
875    * \brief Data of node on a shrinked FACE
876    */
877   struct _SmoothNode
878   {
879     const SMDS_MeshNode*         _node;
880     vector<_Simplex>             _simplices; // for quality check
881
882     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
883
884     bool Smooth(int&                  badNb,
885                 Handle(Geom_Surface)& surface,
886                 SMESH_MesherHelper&   helper,
887                 const double          refSign,
888                 SmoothType            how,
889                 bool                  set3D);
890
891     gp_XY computeAngularPos(vector<gp_XY>& uv,
892                             const gp_XY&   uvToFix,
893                             const double   refSign );
894   };
895   struct PyDump;
896   struct Periodicity;
897   //--------------------------------------------------------------------------------
898   /*!
899    * \brief Builder of viscous layers
900    */
901   class _ViscousBuilder
902   {
903   public:
904     _ViscousBuilder();
905     // does it's job
906     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
907                                   const TopoDS_Shape& shape);
908     // check validity of hypotheses
909     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
910                                            const TopoDS_Shape& shape );
911
912     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
913     void RestoreListeners();
914
915     // computes SMESH_ProxyMesh::SubMesh::_n2n;
916     bool MakeN2NMap( _MeshOfSolid* pm );
917
918   private:
919
920     bool findSolidsWithLayers(const bool checkFaceMesh=true);
921     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
922     bool findFacesWithLayers(const bool onlyWith=false);
923     void findPeriodicFaces();
924     void getIgnoreFaces(const TopoDS_Shape&             solid,
925                         const StdMeshers_ViscousLayers* hyp,
926                         const TopoDS_Shape&             hypShape,
927                         set<TGeomID>&                   ignoreFaces);
928     void makeEdgesOnShape();
929     bool makeLayer(_SolidData& data);
930     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
931     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
932                       SMESH_MesherHelper& helper, _SolidData& data);
933     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
934                          const TopoDS_Face&   face,
935                          SMESH_MesherHelper&  helper,
936                          bool&                isOK,
937                          bool                 shiftInside=false);
938     bool getFaceNormalAtSingularity(const gp_XY&        uv,
939                                     const TopoDS_Face&  face,
940                                     SMESH_MesherHelper& helper,
941                                     gp_Dir&             normal );
942     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
943     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
944                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
945                               int                              nbFaces,
946                               bool                             lastNoOffset = false);
947     bool findNeiborsOnEdge(const _LayerEdge*     edge,
948                            const SMDS_MeshNode*& n1,
949                            const SMDS_MeshNode*& n2,
950                            _EdgesOnShape&        eos,
951                            _SolidData&           data);
952     void findSimplexTestEdges( _SolidData&                    data,
953                                vector< vector<_LayerEdge*> >& edgesByGeom);
954     void computeGeomSize( _SolidData& data );
955     bool findShapesToSmooth( _SolidData& data);
956     void limitStepSizeByCurvature( _SolidData&  data );
957     void limitStepSize( _SolidData&             data,
958                         const SMDS_MeshElement* face,
959                         const _LayerEdge*       maxCosinEdge );
960     void limitStepSize( _SolidData& data, const double minSize);
961     bool inflate(_SolidData& data);
962     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
963     int  invalidateBadSmooth( _SolidData&               data,
964                               SMESH_MesherHelper&       helper,
965                               vector< _LayerEdge* >&    badSmooEdges,
966                               vector< _EdgesOnShape* >& eosC1,
967                               const int                 infStep );
968     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
969     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
970                              vector< _EdgesOnShape* >& eosC1,
971                              int smooStep=0, int moveAll=false );
972     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
973     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
974                                                 _SolidData&         data,
975                                                 SMESH_MesherHelper& helper );
976     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
977     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
978                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
979                                  const bool isSmoothable );
980     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
981     bool updateNormalsOfConvexFaces( _SolidData&         data,
982                                      SMESH_MesherHelper& helper,
983                                      int                 stepNb );
984     void updateNormalsOfC1Vertices( _SolidData& data );
985     bool updateNormalsOfSmoothed( _SolidData&         data,
986                                   SMESH_MesherHelper& helper,
987                                   const int           nbSteps,
988                                   const double        stepSize );
989     bool isNewNormalOk( _SolidData&   data,
990                         _LayerEdge&   edge,
991                         const gp_XYZ& newNormal);
992     bool refine(_SolidData& data);
993     bool shrink(_SolidData& data);
994     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
995                               SMESH_MesherHelper& helper,
996                               const SMESHDS_SubMesh* faceSubMesh );
997     void restoreNoShrink( _LayerEdge& edge ) const;
998     void fixBadFaces(const TopoDS_Face&          F,
999                      SMESH_MesherHelper&         helper,
1000                      const bool                  is2D,
1001                      const int                   step,
1002                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
1003     bool addBoundaryElements(_SolidData& data);
1004
1005     bool error( const string& text, int solidID=-1 );
1006     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1007
1008     // debug
1009     void makeGroupOfLE();
1010
1011     SMESH_Mesh*                  _mesh;
1012     SMESH_ComputeErrorPtr        _error;
1013
1014     vector<                      _SolidData >  _sdVec;
1015     TopTools_IndexedMapOfShape   _solids; // to find _SolidData by a solid
1016     TopTools_MapOfShape          _shrunkFaces;
1017     std::unique_ptr<Periodicity> _periodicity;
1018
1019     int                          _tmpFaceID;
1020     PyDump*                      _pyDump;
1021   };
1022   //--------------------------------------------------------------------------------
1023   /*!
1024    * \brief Shrinker of nodes on the EDGE
1025    */
1026   class _Shrinker1D
1027   {
1028     TopoDS_Edge                   _geomEdge;
1029     vector<double>                _initU;
1030     vector<double>                _normPar;
1031     vector<const SMDS_MeshNode*>  _nodes;
1032     const _LayerEdge*             _edges[2];
1033     bool                          _done;
1034   public:
1035     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1036     void Compute(bool set3D, SMESH_MesherHelper& helper);
1037     void RestoreParams();
1038     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1039     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1040     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1041     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1042     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1043     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1044   };
1045   //--------------------------------------------------------------------------------
1046   /*!
1047    * \brief Smoother of _LayerEdge's on EDGE.
1048    */
1049   struct _Smoother1D
1050   {
1051     struct OffPnt // point of the offsetted EDGE
1052     {
1053       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1054       double      _len;    // length reached at previous inflation step
1055       double      _param;  // on EDGE
1056       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1057       gp_XYZ      _edgeDir;// EDGE tangent at _param
1058       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1059     };
1060     vector< OffPnt >   _offPoints;
1061     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1062     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1063     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1064     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1065     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1066     _EdgesOnShape&     _eos;
1067     double             _curveLen; // length of the EDGE
1068     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1069
1070     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1071                                               _EdgesOnShape&      eos,
1072                                               SMESH_MesherHelper& helper);
1073
1074     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1075                  _EdgesOnShape&     eos )
1076       : _anaCurve( curveForSmooth ), _eos( eos )
1077     {
1078     }
1079     bool Perform(_SolidData&                    data,
1080                  Handle(ShapeAnalysis_Surface)& surface,
1081                  const TopoDS_Face&             F,
1082                  SMESH_MesherHelper&            helper );
1083
1084     void prepare(_SolidData& data );
1085
1086     void findEdgesToSmooth();
1087
1088     bool isToSmooth( int iE );
1089
1090     bool smoothAnalyticEdge( _SolidData&                    data,
1091                              Handle(ShapeAnalysis_Surface)& surface,
1092                              const TopoDS_Face&             F,
1093                              SMESH_MesherHelper&            helper);
1094     bool smoothComplexEdge( _SolidData&                     data,
1095                             Handle(ShapeAnalysis_Surface)& surface,
1096                             const TopoDS_Face&             F,
1097                             SMESH_MesherHelper&            helper);
1098     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1099                             const gp_XYZ&  edgeDir);
1100     _LayerEdge* getLEdgeOnV( bool is2nd )
1101     {
1102       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1103     }
1104     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1105
1106     void offPointsToPython() const; // debug
1107   };
1108   //--------------------------------------------------------------------------------
1109   /*!
1110    * \brief Class of temporary mesh face.
1111    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1112    * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1113    */
1114   struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1115   {
1116     const SMDS_MeshElement* _srcFace;
1117
1118     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1119                   int                                 ID,
1120                   int                                 faceID=-1,
1121                   const SMDS_MeshElement*             srcFace=0 ):
1122       SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1123     virtual SMDSAbs_EntityType  GetEntityType() const
1124     { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1125     virtual SMDSAbs_GeometryType GetGeomType()  const
1126     { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1127   };
1128   //--------------------------------------------------------------------------------
1129   /*!
1130    * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1131    */
1132   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1133   {
1134     _LayerEdge *_le1, *_le2;
1135     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1136       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1137     {
1138       myNodes[0]=_le1->_nodes[0];
1139       myNodes[1]=_le1->_nodes.back();
1140       myNodes[2]=_le2->_nodes.back();
1141       myNodes[3]=_le2->_nodes[0];
1142     }
1143     const SMDS_MeshNode* n( size_t i ) const
1144     {
1145       return myNodes[ i ];
1146     }
1147     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1148     {
1149       SMESH_TNodeXYZ p0s( myNodes[0] );
1150       SMESH_TNodeXYZ p0t( myNodes[1] );
1151       SMESH_TNodeXYZ p1t( myNodes[2] );
1152       SMESH_TNodeXYZ p1s( myNodes[3] );
1153       gp_XYZ  v0 = p0t - p0s;
1154       gp_XYZ  v1 = p1t - p1s;
1155       gp_XYZ v01 = p1s - p0s;
1156       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1157       gp_XYZ   d = v01 ^ n;
1158       d.Normalize();
1159       return d;
1160     }
1161     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1162     {
1163       myNodes[0]=le1->_nodes[0];
1164       myNodes[1]=le1->_nodes.back();
1165       myNodes[2]=le2->_nodes.back();
1166       myNodes[3]=le2->_nodes[0];
1167       return GetDir();
1168     }
1169   };
1170   //--------------------------------------------------------------------------------
1171   /*!
1172    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1173    * \warning Location of a surface is ignored
1174    */
1175   struct _NodeCoordHelper
1176   {
1177     SMESH_MesherHelper&        _helper;
1178     const TopoDS_Face&         _face;
1179     Handle(Geom_Surface)       _surface;
1180     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1181
1182     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1183       : _helper( helper ), _face( F )
1184     {
1185       if ( is2D )
1186       {
1187         TopLoc_Location loc;
1188         _surface = BRep_Tool::Surface( _face, loc );
1189       }
1190       if ( _surface.IsNull() )
1191         _fun = & _NodeCoordHelper::direct;
1192       else
1193         _fun = & _NodeCoordHelper::byUV;
1194     }
1195     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1196
1197   private:
1198     gp_XYZ direct(const SMDS_MeshNode* n) const
1199     {
1200       return SMESH_TNodeXYZ( n );
1201     }
1202     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1203     {
1204       gp_XY uv = _helper.GetNodeUV( _face, n );
1205       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1206     }
1207   };
1208
1209   //================================================================================
1210   /*!
1211    * \brief Check angle between vectors 
1212    */
1213   //================================================================================
1214
1215   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1216   {
1217     double dot = v1 * v2; // cos * |v1| * |v2|
1218     double l1  = v1.SquareMagnitude();
1219     double l2  = v2.SquareMagnitude();
1220     return (( dot * cos >= 0 ) && 
1221             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1222   }
1223
1224   class _Factory
1225   {
1226     ObjectPool< _LayerEdge >  _edgePool;
1227     ObjectPool< _Curvature >  _curvaturePool;
1228     ObjectPool< _2NearEdges > _nearEdgesPool;
1229
1230     static _Factory* & me()
1231     {
1232       static _Factory* theFactory = 0;
1233       return theFactory;
1234     }
1235   public:
1236
1237     _Factory()  { me() = this; }
1238     ~_Factory() { me() = 0; }
1239
1240     static _LayerEdge*  NewLayerEdge() { return me()->_edgePool.getNew(); }
1241     static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1242     static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1243   };
1244
1245 } // namespace VISCOUS_3D
1246
1247
1248
1249 //================================================================================
1250 // StdMeshers_ViscousLayers hypothesis
1251 //
1252 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1253   :SMESH_Hypothesis(hypId, gen),
1254    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1255    _method( SURF_OFFSET_SMOOTH ),
1256    _groupName("")
1257 {
1258   _name = StdMeshers_ViscousLayers::GetHypType();
1259   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1260 } // --------------------------------------------------------------------------------
1261 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1262 {
1263   if ( faceIds != _shapeIds )
1264     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1265   if ( _isToIgnoreShapes != toIgnore )
1266     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1267 } // --------------------------------------------------------------------------------
1268 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1269 {
1270   if ( thickness != _thickness )
1271     _thickness = thickness, NotifySubMeshesHypothesisModification();
1272 } // --------------------------------------------------------------------------------
1273 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1274 {
1275   if ( _nbLayers != nb )
1276     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1277 } // --------------------------------------------------------------------------------
1278 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1279 {
1280   if ( _stretchFactor != factor )
1281     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1282 } // --------------------------------------------------------------------------------
1283 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1284 {
1285   if ( _method != method )
1286     _method = method, NotifySubMeshesHypothesisModification();
1287 } // --------------------------------------------------------------------------------
1288 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1289 {
1290   if ( _groupName != name )
1291   {
1292     _groupName = name;
1293     if ( !_groupName.empty() )
1294       NotifySubMeshesHypothesisModification();
1295   }
1296 } // --------------------------------------------------------------------------------
1297 SMESH_ProxyMesh::Ptr
1298 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1299                                   const TopoDS_Shape& theShape,
1300                                   const bool          toMakeN2NMap) const
1301 {
1302   using namespace VISCOUS_3D;
1303   _ViscousBuilder builder;
1304   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1305   if ( err && !err->IsOK() )
1306     return SMESH_ProxyMesh::Ptr();
1307
1308   vector<SMESH_ProxyMesh::Ptr> components;
1309   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1310   for ( ; exp.More(); exp.Next() )
1311   {
1312     if ( _MeshOfSolid* pm =
1313          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1314     {
1315       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1316         if ( !builder.MakeN2NMap( pm ))
1317           return SMESH_ProxyMesh::Ptr();
1318       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1319       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1320
1321       if ( pm->_warning && !pm->_warning->IsOK() )
1322       {
1323         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1324         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1325         if ( !smError || smError->IsOK() )
1326           smError = pm->_warning;
1327       }
1328     }
1329     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1330   }
1331   switch ( components.size() )
1332   {
1333   case 0: break;
1334
1335   case 1: return components[0];
1336
1337   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1338   }
1339   return SMESH_ProxyMesh::Ptr();
1340 } // --------------------------------------------------------------------------------
1341 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1342 {
1343   save << " " << _nbLayers
1344        << " " << _thickness
1345        << " " << _stretchFactor
1346        << " " << _shapeIds.size();
1347   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1348     save << " " << _shapeIds[i];
1349   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1350   save << " " << _method;
1351   save << " " << _groupName.size();
1352   if ( !_groupName.empty() )
1353     save << " " << _groupName;
1354   return save;
1355 } // --------------------------------------------------------------------------------
1356 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1357 {
1358   int nbFaces, faceID, shapeToTreat, method;
1359   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1360   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1361     _shapeIds.push_back( faceID );
1362   if ( load >> shapeToTreat ) {
1363     _isToIgnoreShapes = !shapeToTreat;
1364     if ( load >> method )
1365       _method = (ExtrusionMethod) method;
1366     int nameSize = 0;
1367     if ( load >> nameSize && nameSize > 0 )
1368     {
1369       _groupName.resize( nameSize );
1370       load.get( _groupName[0] ); // remove a white-space
1371       load.getline( &_groupName[0], nameSize + 1 );
1372     }
1373   }
1374   else {
1375     _isToIgnoreShapes = true; // old behavior
1376   }
1377   return load;
1378 } // --------------------------------------------------------------------------------
1379 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   /*theMesh*/,
1380                                                    const TopoDS_Shape& /*theShape*/)
1381 {
1382   // TODO
1383   return false;
1384 } // --------------------------------------------------------------------------------
1385 SMESH_ComputeErrorPtr
1386 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1387                                           const TopoDS_Shape&                  theShape,
1388                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1389 {
1390   VISCOUS_3D::_ViscousBuilder builder;
1391   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1392   if ( err && !err->IsOK() )
1393     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1394   else
1395     theStatus = SMESH_Hypothesis::HYP_OK;
1396
1397   return err;
1398 }
1399 // --------------------------------------------------------------------------------
1400 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1401 {
1402   bool isIn =
1403     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1404   return IsToIgnoreShapes() ? !isIn : isIn;
1405 }
1406
1407 // --------------------------------------------------------------------------------
1408 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string&  theName,
1409                                                        SMESH_Mesh&         theMesh,
1410                                                        SMDSAbs_ElementType theType)
1411 {
1412   SMESH_Group*      group = 0;
1413   SMDS_MeshGroup* groupDS = 0;
1414
1415   if ( theName.empty() )
1416     return groupDS;
1417        
1418   if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1419     while( grIt->more() && !group )
1420     {
1421       group = grIt->next();
1422       if ( !group ||
1423            group->GetGroupDS()->GetType() != theType ||
1424            group->GetName()               != theName ||
1425            !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1426         group = 0;
1427     }
1428   if ( !group )
1429     group = theMesh.AddGroup( theType, theName.c_str() );
1430
1431   groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1432
1433   return groupDS;
1434 }
1435
1436 // END StdMeshers_ViscousLayers hypothesis
1437 //================================================================================
1438
1439 namespace VISCOUS_3D
1440 {
1441   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
1442   {
1443     gp_Vec dir;
1444     double f,l;
1445     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1446     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1447     gp_Pnt p = BRep_Tool::Pnt( fromV );
1448     double distF = p.SquareDistance( c->Value( f ));
1449     double distL = p.SquareDistance( c->Value( l ));
1450     c->D1(( distF < distL ? f : l), p, dir );
1451     if ( distL < distF ) dir.Reverse();
1452     return dir.XYZ();
1453   }
1454   //--------------------------------------------------------------------------------
1455   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1456                      SMESH_MesherHelper& helper)
1457   {
1458     gp_Vec dir;
1459     double f,l; gp_Pnt p;
1460     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1461     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1462     double u = helper.GetNodeU( E, atNode );
1463     c->D1( u, p, dir );
1464     return dir.XYZ();
1465   }
1466   //--------------------------------------------------------------------------------
1467   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1468                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1469                      double* cosin=0);
1470   //--------------------------------------------------------------------------------
1471   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1472                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1473   {
1474     double f,l;
1475     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1476     if ( c.IsNull() )
1477     {
1478       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1479       return getFaceDir( F, v, node, helper, ok );
1480     }
1481     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1482     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1483     gp_Pnt p; gp_Vec du, dv, norm;
1484     surface->D1( uv.X(),uv.Y(), p, du,dv );
1485     norm = du ^ dv;
1486
1487     double u = helper.GetNodeU( fromE, node, 0, &ok );
1488     c->D1( u, p, du );
1489     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1490     if ( o == TopAbs_REVERSED )
1491       du.Reverse();
1492
1493     gp_Vec dir = norm ^ du;
1494
1495     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1496          helper.IsClosedEdge( fromE ))
1497     {
1498       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1499       else                        c->D1( f, p, dv );
1500       if ( o == TopAbs_REVERSED )
1501         dv.Reverse();
1502       gp_Vec dir2 = norm ^ dv;
1503       dir = dir.Normalized() + dir2.Normalized();
1504     }
1505     return dir.XYZ();
1506   }
1507   //--------------------------------------------------------------------------------
1508   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1509                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1510                      bool& ok, double* cosin)
1511   {
1512     TopoDS_Face faceFrw = F;
1513     faceFrw.Orientation( TopAbs_FORWARD );
1514     //double f,l; TopLoc_Location loc;
1515     TopoDS_Edge edges[2]; // sharing a vertex
1516     size_t nbEdges = 0;
1517     {
1518       TopoDS_Vertex VV[2];
1519       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1520       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1521       {
1522         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1523         if ( SMESH_Algo::isDegenerated( e )) continue;
1524         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1525         if ( VV[1].IsSame( fromV )) {
1526           nbEdges += edges[ 0 ].IsNull();
1527           edges[ 0 ] = e;
1528         }
1529         else if ( VV[0].IsSame( fromV )) {
1530           nbEdges += edges[ 1 ].IsNull();
1531           edges[ 1 ] = e;
1532         }
1533       }
1534     }
1535     gp_XYZ dir(0,0,0), edgeDir[2];
1536     if ( nbEdges == 2 )
1537     {
1538       // get dirs of edges going fromV
1539       ok = true;
1540       for ( size_t i = 0; i < nbEdges && ok; ++i )
1541       {
1542         edgeDir[i] = getEdgeDir( edges[i], fromV );
1543         double size2 = edgeDir[i].SquareModulus();
1544         if (( ok = size2 > numeric_limits<double>::min() ))
1545           edgeDir[i] /= sqrt( size2 );
1546       }
1547       if ( !ok ) return dir;
1548
1549       // get angle between the 2 edges
1550       gp_Vec faceNormal;
1551       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1552       if ( Abs( angle ) < 5 * M_PI/180 )
1553       {
1554         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1555       }
1556       else
1557       {
1558         dir = edgeDir[0] + edgeDir[1];
1559         if ( angle < 0 )
1560           dir.Reverse();
1561       }
1562       if ( cosin ) {
1563         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1564         *cosin = Cos( angle );
1565       }
1566     }
1567     else if ( nbEdges == 1 )
1568     {
1569       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1570       if ( cosin ) *cosin = 1.;
1571     }
1572     else
1573     {
1574       ok = false;
1575     }
1576
1577     return dir;
1578   }
1579
1580   //================================================================================
1581   /*!
1582    * \brief Finds concave VERTEXes of a FACE
1583    */
1584   //================================================================================
1585
1586   bool getConcaveVertices( const TopoDS_Face&  F,
1587                            SMESH_MesherHelper& helper,
1588                            set< TGeomID >*     vertices = 0)
1589   {
1590     // check angles at VERTEXes
1591     TError error;
1592     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1593     for ( size_t iW = 0; iW < wires.size(); ++iW )
1594     {
1595       const int nbEdges = wires[iW]->NbEdges();
1596       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1597         continue;
1598       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1599       {
1600         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1601         int iE2 = ( iE1 + 1 ) % nbEdges;
1602         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1603           iE2 = ( iE2 + 1 ) % nbEdges;
1604         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1605         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1606                                         wires[iW]->Edge( iE2 ), F, V );
1607         if ( angle < -5. * M_PI / 180. )
1608         {
1609           if ( !vertices )
1610             return true;
1611           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1612         }
1613       }
1614     }
1615     return vertices ? !vertices->empty() : false;
1616   }
1617
1618   //================================================================================
1619   /*!
1620    * \brief Returns true if a FACE is bound by a concave EDGE
1621    */
1622   //================================================================================
1623
1624   bool isConcave( const TopoDS_Face&  F,
1625                   SMESH_MesherHelper& helper,
1626                   set< TGeomID >*     vertices = 0 )
1627   {
1628     bool isConcv = false;
1629     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1630     //   return true;
1631     gp_Vec2d drv1, drv2;
1632     gp_Pnt2d p;
1633     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1634     for ( ; eExp.More(); eExp.Next() )
1635     {
1636       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1637       if ( SMESH_Algo::isDegenerated( E )) continue;
1638       // check if 2D curve is concave
1639       BRepAdaptor_Curve2d curve( E, F );
1640       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1641       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1642       curve.Intervals( intervals, GeomAbs_C2 );
1643       bool isConvex = true;
1644       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1645       {
1646         double u1 = intervals( i );
1647         double u2 = intervals( i+1 );
1648         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1649         double cross = drv1 ^ drv2;
1650         if ( E.Orientation() == TopAbs_REVERSED )
1651           cross = -cross;
1652         isConvex = ( cross > -1e-9 ); // 0.1 );
1653       }
1654       if ( !isConvex )
1655       {
1656         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1657         isConcv = true;
1658         if ( vertices )
1659           break;
1660         else
1661           return true;
1662       }
1663     }
1664
1665     // check angles at VERTEXes
1666     if ( getConcaveVertices( F, helper, vertices ))
1667       isConcv = true;
1668
1669     return isConcv;
1670   }
1671
1672   //================================================================================
1673   /*!
1674    * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1675    *  \param [in] face - the mesh face to treat
1676    *  \param [in] nodeOnEdge - a node on the EDGE
1677    *  \param [out] faceSize - the computed distance
1678    *  \return bool - true if faceSize computed
1679    */
1680   //================================================================================
1681
1682   bool getDistFromEdge( const SMDS_MeshElement* face,
1683                         const SMDS_MeshNode*    nodeOnEdge,
1684                         double &                faceSize )
1685   {
1686     faceSize = Precision::Infinite();
1687     bool done = false;
1688
1689     int nbN  = face->NbCornerNodes();
1690     int iOnE = face->GetNodeIndex( nodeOnEdge );
1691     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1692                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1693     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1694                                       face->GetNode( iNext[1] ) };
1695     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1696     double segLen = -1.;
1697     // look for two neighbor not in-FACE nodes of face
1698     for ( int i = 0; i < 2; ++i )
1699     {
1700       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1701           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1702       {
1703         // look for an in-FACE node
1704         for ( int iN = 0; iN < nbN; ++iN )
1705         {
1706           if ( iN == iOnE || iN == iNext[i] )
1707             continue;
1708           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1709           gp_XYZ v = pInFace - segEnd;
1710           if ( segLen < 0 )
1711           {
1712             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1713             segLen = segVec.Modulus();
1714           }
1715           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1716           faceSize = Min( faceSize, distToSeg );
1717           done = true;
1718         }
1719         segLen = -1;
1720       }
1721     }
1722     return done;
1723   }
1724   //================================================================================
1725   /*!
1726    * \brief Return direction of axis or revolution of a surface
1727    */
1728   //================================================================================
1729
1730   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1731                           gp_Dir &                 axis )
1732   {
1733     switch ( surface.GetType() ) {
1734     case GeomAbs_Cone:
1735     {
1736       gp_Cone cone = surface.Cone();
1737       axis = cone.Axis().Direction();
1738       break;
1739     }
1740     case GeomAbs_Sphere:
1741     {
1742       gp_Sphere sphere = surface.Sphere();
1743       axis = sphere.Position().Direction();
1744       break;
1745     }
1746     case GeomAbs_SurfaceOfRevolution:
1747     {
1748       axis = surface.AxeOfRevolution().Direction();
1749       break;
1750     }
1751     //case GeomAbs_SurfaceOfExtrusion:
1752     case GeomAbs_OffsetSurface:
1753     {
1754       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1755       return getRovolutionAxis( base->Surface(), axis );
1756     }
1757     default: return false;
1758     }
1759     return true;
1760   }
1761
1762   //--------------------------------------------------------------------------------
1763   // DEBUG. Dump intermediate node positions into a python script
1764   // HOWTO use: run python commands written in a console to see
1765   //  construction steps of viscous layers
1766 #ifdef __myDEBUG
1767   ostream* py;
1768   int      theNbPyFunc;
1769   struct PyDump
1770   {
1771     PyDump(SMESH_Mesh& m) {
1772       int tag = 3 + m.GetId();
1773       const char* fname = "/tmp/viscous.py";
1774       cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1775       py = _pyStream = new ofstream(fname);
1776       *py << "import SMESH" << endl
1777           << "from salome.smesh import smeshBuilder" << endl
1778           << "smesh  = smeshBuilder.New()" << endl
1779           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1780           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1781       theNbPyFunc = 0;
1782     }
1783     void Finish() {
1784       if (py) {
1785         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1786           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1787         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1788           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1789       }
1790       delete py; py=0;
1791     }
1792     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1793     struct MyStream : public ostream
1794     {
1795       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1796     };
1797     void Pause() { py = &_mystream; }
1798     void Resume() { py = _pyStream; }
1799     MyStream _mystream;
1800     ostream* _pyStream;
1801   };
1802 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1803 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1804 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1805 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1806   void _dumpFunction(const string& fun, int ln)
1807   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1808   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1809   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1810                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1811   void _dumpCmd(const string& txt, int ln)
1812   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1813   void dumpFunctionEnd()
1814   { if (py) *py<< "  return"<< endl; }
1815   void dumpChangeNodes( const SMDS_MeshElement* f )
1816   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1817       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1818       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1819 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1820
1821 #else
1822
1823   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1824 #define dumpFunction(f) f
1825 #define dumpMove(n)
1826 #define dumpMoveComm(n,txt)
1827 #define dumpCmd(txt)
1828 #define dumpFunctionEnd()
1829 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1830 #define debugMsg( txt ) {}
1831
1832 #endif
1833 }
1834
1835 using namespace VISCOUS_3D;
1836
1837 //================================================================================
1838 /*!
1839  * \brief Constructor of _ViscousBuilder
1840  */
1841 //================================================================================
1842
1843 _ViscousBuilder::_ViscousBuilder()
1844 {
1845   _error = SMESH_ComputeError::New(COMPERR_OK);
1846   _tmpFaceID = 0;
1847 }
1848
1849 //================================================================================
1850 /*!
1851  * \brief Stores error description and returns false
1852  */
1853 //================================================================================
1854
1855 bool _ViscousBuilder::error(const string& text, int solidId )
1856 {
1857   const string prefix = string("Viscous layers builder: ");
1858   _error->myName    = COMPERR_ALGO_FAILED;
1859   _error->myComment = prefix + text;
1860   if ( _mesh )
1861   {
1862     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1863     if ( !sm && !_sdVec.empty() )
1864       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1865     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1866     {
1867       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1868       if ( smError && smError->myAlgo )
1869         _error->myAlgo = smError->myAlgo;
1870       smError = _error;
1871       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1872     }
1873     // set KO to all solids
1874     for ( size_t i = 0; i < _sdVec.size(); ++i )
1875     {
1876       if ( _sdVec[i]._index == solidId )
1877         continue;
1878       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1879       if ( !sm->IsEmpty() )
1880         continue;
1881       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1882       if ( !smError || smError->IsOK() )
1883       {
1884         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1885         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1886       }
1887     }
1888   }
1889   makeGroupOfLE(); // debug
1890
1891   return false;
1892 }
1893
1894 //================================================================================
1895 /*!
1896  * \brief At study restoration, restore event listeners used to clear an inferior
1897  *  dim sub-mesh modified by viscous layers
1898  */
1899 //================================================================================
1900
1901 void _ViscousBuilder::RestoreListeners()
1902 {
1903   // TODO
1904 }
1905
1906 //================================================================================
1907 /*!
1908  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1909  */
1910 //================================================================================
1911
1912 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1913 {
1914   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1915   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1916   for ( ; fExp.More(); fExp.Next() )
1917   {
1918     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1919     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1920
1921     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1922       continue;
1923     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1924       continue;
1925
1926     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1927       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1928
1929     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1930     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1931     while( prxIt->more() )
1932     {
1933       const SMDS_MeshElement* fSrc = srcIt->next();
1934       const SMDS_MeshElement* fPrx = prxIt->next();
1935       if ( fSrc->NbNodes() != fPrx->NbNodes())
1936         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1937       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1938         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1939     }
1940   }
1941   pm->_n2nMapComputed = true;
1942   return true;
1943 }
1944
1945 //================================================================================
1946 /*!
1947  * \brief Does its job
1948  */
1949 //================================================================================
1950
1951 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1952                                                const TopoDS_Shape& theShape)
1953 {
1954   _mesh = & theMesh;
1955
1956   _Factory factory;
1957
1958   // check if proxy mesh already computed
1959   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1960   if ( !exp.More() )
1961     return error("No SOLID's in theShape"), _error;
1962
1963   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1964     return SMESH_ComputeErrorPtr(); // everything already computed
1965
1966   PyDump debugDump( theMesh );
1967   _pyDump = &debugDump;
1968
1969   // TODO: ignore already computed SOLIDs
1970   if ( !findSolidsWithLayers())
1971     return _error;
1972
1973   if ( !findFacesWithLayers() )
1974     return _error;
1975
1976   // for ( size_t i = 0; i < _sdVec.size(); ++i )
1977   // {
1978   //   if ( ! makeLayer( _sdVec[ i ]))   // create _LayerEdge's
1979   //     return _error;
1980   // }
1981
1982   makeEdgesOnShape();
1983
1984   findPeriodicFaces();
1985
1986   for ( size_t i = 0; i < _sdVec.size(); ++i )
1987   {
1988     size_t iSD = 0;
1989     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
1990       if ( _sdVec[iSD]._before.IsEmpty() &&
1991            !_sdVec[iSD]._solid.IsNull() &&
1992            !_sdVec[iSD]._done )
1993         break;
1994
1995     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
1996       return _error;
1997
1998     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
1999     {
2000       _sdVec[iSD]._solid.Nullify();
2001       continue;
2002     }
2003
2004     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
2005       return _error;
2006
2007     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
2008       return _error;
2009
2010     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
2011       return _error;
2012
2013     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2014
2015     _sdVec[iSD]._done = true;
2016
2017     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2018     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2019       _sdVec[iSD]._before.Remove( solid );
2020   }
2021
2022   makeGroupOfLE(); // debug
2023   debugDump.Finish();
2024
2025   return _error;
2026 }
2027
2028 //================================================================================
2029 /*!
2030  * \brief Check validity of hypotheses
2031  */
2032 //================================================================================
2033
2034 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
2035                                                         const TopoDS_Shape& shape )
2036 {
2037   _mesh = & mesh;
2038
2039   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2040     return SMESH_ComputeErrorPtr(); // everything already computed
2041
2042
2043   findSolidsWithLayers( /*checkFaceMesh=*/false );
2044   bool ok = findFacesWithLayers( true );
2045
2046   // remove _MeshOfSolid's of _SolidData's
2047   for ( size_t i = 0; i < _sdVec.size(); ++i )
2048     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2049
2050   if ( !ok )
2051     return _error;
2052
2053   return SMESH_ComputeErrorPtr();
2054 }
2055
2056 //================================================================================
2057 /*!
2058  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2059  */
2060 //================================================================================
2061
2062 bool _ViscousBuilder::findSolidsWithLayers(const bool checkFaceMesh)
2063 {
2064   // get all solids
2065   TopTools_IndexedMapOfShape allSolids;
2066   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2067   _sdVec.reserve( allSolids.Extent());
2068
2069   SMESH_HypoFilter filter;
2070   for ( int i = 1; i <= allSolids.Extent(); ++i )
2071   {
2072     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2073     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2074       continue; // solid is already meshed
2075     // TODO: check if algo is hidden
2076     SMESH_Algo* algo = sm->GetAlgo();
2077     if ( !algo ) continue;
2078     // check if all FACEs are meshed, which can be false if Compute() a sub-shape
2079     if ( checkFaceMesh )
2080     {
2081       bool facesMeshed = true;
2082       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,true);
2083       while ( smIt->more() && facesMeshed )
2084       {
2085         SMESH_subMesh * faceSM = smIt->next();
2086         if ( faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2087           break;
2088         facesMeshed = faceSM->IsMeshComputed();
2089       }
2090       if ( !facesMeshed )
2091         continue;
2092     }
2093     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2094     const list <const SMESHDS_Hypothesis *> & allHyps =
2095       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2096     _SolidData* soData = 0;
2097     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2098     const StdMeshers_ViscousLayers* viscHyp = 0;
2099     for ( ; hyp != allHyps.end(); ++hyp )
2100       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2101       {
2102         TopoDS_Shape hypShape;
2103         filter.Init( filter.Is( viscHyp ));
2104         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2105
2106         if ( !soData )
2107         {
2108           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2109                                                                     allSolids(i),
2110                                                                     /*toCreate=*/true);
2111           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2112           soData = & _sdVec.back();
2113           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2114           soData->_helper = new SMESH_MesherHelper( *_mesh );
2115           soData->_helper->SetSubShape( allSolids(i) );
2116           _solids.Add( allSolids(i) );
2117         }
2118         soData->_hyps.push_back( viscHyp );
2119         soData->_hypShapes.push_back( hypShape );
2120       }
2121   }
2122   if ( _sdVec.empty() )
2123     return error
2124       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2125
2126   return true;
2127 }
2128
2129 //================================================================================
2130 /*!
2131  * \brief Set a _SolidData to be computed before another
2132  */
2133 //================================================================================
2134
2135 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2136 {
2137   // check possibility to set this order; get all solids before solidBefore
2138   TopTools_IndexedMapOfShape allSolidsBefore;
2139   allSolidsBefore.Add( solidBefore._solid );
2140   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2141   {
2142     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2143     if ( iSD )
2144     {
2145       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2146       for ( ; soIt.More(); soIt.Next() )
2147         allSolidsBefore.Add( soIt.Value() );
2148     }
2149   }
2150   if ( allSolidsBefore.Contains( solidAfter._solid ))
2151     return false;
2152
2153   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2154     solidAfter._before.Add( allSolidsBefore(i) );
2155
2156   return true;
2157 }
2158
2159 //================================================================================
2160 /*!
2161  * \brief
2162  */
2163 //================================================================================
2164
2165 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2166 {
2167   SMESH_MesherHelper helper( *_mesh );
2168   TopExp_Explorer exp;
2169
2170   // collect all faces-to-ignore defined by hyp
2171   for ( size_t i = 0; i < _sdVec.size(); ++i )
2172   {
2173     // get faces-to-ignore defined by each hyp
2174     typedef const StdMeshers_ViscousLayers* THyp;
2175     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2176     list< TFacesOfHyp > ignoreFacesOfHyps;
2177     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2178     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2179     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2180     {
2181       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2182       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2183     }
2184
2185     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2186     const int nbHyps = _sdVec[i]._hyps.size();
2187     if ( nbHyps > 1 )
2188     {
2189       // check if two hypotheses define different parameters for the same FACE
2190       list< TFacesOfHyp >::iterator igFacesOfHyp;
2191       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2192       {
2193         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2194         THyp hyp = 0;
2195         igFacesOfHyp = ignoreFacesOfHyps.begin();
2196         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2197           if ( ! igFacesOfHyp->first.count( faceID ))
2198           {
2199             if ( hyp )
2200               return error(SMESH_Comment("Several hypotheses define "
2201                                          "Viscous Layers on the face #") << faceID );
2202             hyp = igFacesOfHyp->second;
2203           }
2204         if ( hyp )
2205           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2206         else
2207           _sdVec[i]._ignoreFaceIds.insert( faceID );
2208       }
2209
2210       // check if two hypotheses define different number of viscous layers for
2211       // adjacent faces of a solid
2212       set< int > nbLayersSet;
2213       igFacesOfHyp = ignoreFacesOfHyps.begin();
2214       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2215       {
2216         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2217       }
2218       if ( nbLayersSet.size() > 1 )
2219       {
2220         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2221         {
2222           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2223           THyp hyp1 = 0, hyp2 = 0;
2224           while( const TopoDS_Shape* face = fIt->next() )
2225           {
2226             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2227             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2228             if ( f2h != _sdVec[i]._face2hyp.end() )
2229             {
2230               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2231             }
2232           }
2233           if ( hyp1 && hyp2 &&
2234                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2235           {
2236             return error("Two hypotheses define different number of "
2237                          "viscous layers on adjacent faces");
2238           }
2239         }
2240       }
2241     } // if ( nbHyps > 1 )
2242     else
2243     {
2244       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2245     }
2246   } // loop on _sdVec
2247
2248   if ( onlyWith ) // is called to check hypotheses compatibility only
2249     return true;
2250
2251   // fill _SolidData::_reversedFaceIds
2252   for ( size_t i = 0; i < _sdVec.size(); ++i )
2253   {
2254     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2255     for ( ; exp.More(); exp.Next() )
2256     {
2257       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2258       const TGeomID    faceID = getMeshDS()->ShapeToIndex( face );
2259       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2260           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2261           helper.IsReversedSubMesh( face ))
2262       {
2263         _sdVec[i]._reversedFaceIds.insert( faceID );
2264       }
2265     }
2266   }
2267
2268   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2269   TopTools_IndexedMapOfShape shapes;
2270   std::string structAlgoName = "Hexa_3D";
2271   for ( size_t i = 0; i < _sdVec.size(); ++i )
2272   {
2273     shapes.Clear();
2274     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2275     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2276     {
2277       const TopoDS_Shape& edge = shapes(iE);
2278       // find 2 FACEs sharing an EDGE
2279       TopoDS_Shape FF[2];
2280       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2281       while ( fIt->more())
2282       {
2283         const TopoDS_Shape* f = fIt->next();
2284         FF[ int( !FF[0].IsNull()) ] = *f;
2285       }
2286       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2287
2288       // check presence of layers on them
2289       int ignore[2];
2290       for ( int j = 0; j < 2; ++j )
2291         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2292       if ( ignore[0] == ignore[1] )
2293         continue; // nothing interesting
2294       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2295
2296       // add EDGE to maps
2297       if ( !fWOL.IsNull())
2298       {
2299         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2300         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2301       }
2302     }
2303   }
2304
2305   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2306
2307   for ( size_t i = 0; i < _sdVec.size(); ++i )
2308   {
2309     shapes.Clear();
2310     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2311     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2312     {
2313       const TopoDS_Shape& vertex = shapes(iV);
2314       // find faces WOL sharing the vertex
2315       vector< TopoDS_Shape > facesWOL;
2316       size_t totalNbFaces = 0;
2317       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2318       while ( fIt->more())
2319       {
2320         const TopoDS_Shape* f = fIt->next();
2321         totalNbFaces++;
2322         const int fID = getMeshDS()->ShapeToIndex( *f );
2323         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2324           facesWOL.push_back( *f );
2325       }
2326       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2327         continue; // no layers at this vertex or no WOL
2328       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2329       switch ( facesWOL.size() )
2330       {
2331       case 1:
2332       {
2333         helper.SetSubShape( facesWOL[0] );
2334         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2335         {
2336           TopoDS_Shape seamEdge;
2337           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2338           while ( eIt->more() && seamEdge.IsNull() )
2339           {
2340             const TopoDS_Shape* e = eIt->next();
2341             if ( helper.IsRealSeam( *e ) )
2342               seamEdge = *e;
2343           }
2344           if ( !seamEdge.IsNull() )
2345           {
2346             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2347             break;
2348           }
2349         }
2350         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2351         break;
2352       }
2353       case 2:
2354       {
2355         // find an edge shared by 2 faces
2356         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2357         while ( eIt->more())
2358         {
2359           const TopoDS_Shape* e = eIt->next();
2360           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2361                helper.IsSubShape( *e, facesWOL[1]))
2362           {
2363             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2364           }
2365         }
2366         break;
2367       }
2368       default:
2369         return error("Not yet supported case", _sdVec[i]._index);
2370       }
2371     }
2372   }
2373
2374   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2375   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2376   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2377   for ( size_t i = 0; i < _sdVec.size(); ++i )
2378   {
2379     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2380     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2381     {
2382       const TopoDS_Shape& fWOL = e2f->second;
2383       const TGeomID     edgeID = e2f->first;
2384       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2385       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2386       if ( edge.ShapeType() != TopAbs_EDGE )
2387         continue; // shrink shape is VERTEX
2388
2389       TopoDS_Shape solid;
2390       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2391       while ( soIt->more() && solid.IsNull() )
2392       {
2393         const TopoDS_Shape* so = soIt->next();
2394         if ( !so->IsSame( _sdVec[i]._solid ))
2395           solid = *so;
2396       }
2397       if ( solid.IsNull() )
2398         continue;
2399
2400       bool noShrinkE = false;
2401       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2402       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2403       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2404       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2405       {
2406         // the adjacent SOLID has NO layers on fWOL;
2407         // shrink allowed if
2408         // - there are layers on the EDGE in the adjacent SOLID
2409         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2410         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2411         bool shrinkAllowed = (( hasWLAdj ) ||
2412                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2413         noShrinkE = !shrinkAllowed;
2414       }
2415       else if ( iSolid < _sdVec.size() )
2416       {
2417         // the adjacent SOLID has layers on fWOL;
2418         // check if SOLID's mesh is unstructured and then try to set it
2419         // to be computed after the i-th solid
2420         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2421           noShrinkE = true; // don't shrink fWOL
2422       }
2423       else
2424       {
2425         // the adjacent SOLID has NO layers at all
2426         noShrinkE = isStructured;
2427       }
2428
2429       if ( noShrinkE )
2430       {
2431         _sdVec[i]._noShrinkShapes.insert( edgeID );
2432
2433         // check if there is a collision with to-shrink-from EDGEs in iSolid
2434         // if ( iSolid < _sdVec.size() )
2435         // {
2436         //   shapes.Clear();
2437         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2438         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2439         //   {
2440         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2441         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2442         //     if ( eID == edgeID ||
2443         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2444         //          _sdVec[i]._noShrinkShapes.count( eID ))
2445         //       continue;
2446         //     for ( int is1st = 0; is1st < 2; ++is1st )
2447         //     {
2448         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2449         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2450         //       {
2451         //         return error("No way to make a conformal mesh with "
2452         //                      "the given set of faces with layers", _sdVec[i]._index);
2453         //       }
2454         //     }
2455         //   }
2456         // }
2457       }
2458
2459       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2460       // _shrinkShape2Shape is different in the adjacent SOLID
2461       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2462       {
2463         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2464         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2465
2466         if ( iSolid < _sdVec.size() )
2467         {
2468           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2469           {
2470             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2471             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2472             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2473             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2474               noShrinkV = (( isStructured ) ||
2475                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2476             else
2477               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2478           }
2479           else
2480           {
2481             noShrinkV = noShrinkE;
2482           }
2483         }
2484         else
2485         {
2486           // the adjacent SOLID has NO layers at all
2487           if ( isStructured )
2488           {
2489             noShrinkV = true;
2490           }
2491           else
2492           {
2493             noShrinkV = noShrinkIfAdjMeshed =
2494               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2495           }
2496         }
2497
2498         if ( noShrinkV && noShrinkIfAdjMeshed )
2499         {
2500           // noShrinkV if FACEs in the adjacent SOLID are meshed
2501           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2502                                                        *_mesh, TopAbs_FACE, &solid );
2503           while ( fIt->more() )
2504           {
2505             const TopoDS_Shape* f = fIt->next();
2506             if ( !f->IsSame( fWOL ))
2507             {
2508               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2509               break;
2510             }
2511           }
2512         }
2513         if ( noShrinkV )
2514           _sdVec[i]._noShrinkShapes.insert( vID );
2515       }
2516
2517     } // loop on _sdVec[i]._shrinkShape2Shape
2518   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2519
2520
2521     // add FACEs of other SOLIDs to _ignoreFaceIds
2522   for ( size_t i = 0; i < _sdVec.size(); ++i )
2523   {
2524     shapes.Clear();
2525     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2526
2527     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2528     {
2529       if ( !shapes.Contains( exp.Current() ))
2530         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2531     }
2532   }
2533
2534   return true;
2535 }
2536
2537 //================================================================================
2538 /*!
2539  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2540  */
2541 //================================================================================
2542
2543 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2544                                      const StdMeshers_ViscousLayers* hyp,
2545                                      const TopoDS_Shape&             hypShape,
2546                                      set<TGeomID>&                   ignoreFaceIds)
2547 {
2548   TopExp_Explorer exp;
2549
2550   vector<TGeomID> ids = hyp->GetBndShapes();
2551   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2552   {
2553     for ( size_t ii = 0; ii < ids.size(); ++ii )
2554     {
2555       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2556       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2557         ignoreFaceIds.insert( ids[ii] );
2558     }
2559   }
2560   else // FACEs with layers are given
2561   {
2562     exp.Init( solid, TopAbs_FACE );
2563     for ( ; exp.More(); exp.Next() )
2564     {
2565       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2566       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2567         ignoreFaceIds.insert( faceInd );
2568     }
2569   }
2570
2571   // ignore internal FACEs if inlets and outlets are specified
2572   if ( hyp->IsToIgnoreShapes() )
2573   {
2574     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2575     TopExp::MapShapesAndAncestors( hypShape,
2576                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2577
2578     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2579     {
2580       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2581       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2582         continue;
2583
2584       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2585       if ( nbSolids > 1 )
2586         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2587     }
2588   }
2589 }
2590
2591 //================================================================================
2592 /*!
2593  * \brief Create the inner surface of the viscous layer and prepare data for infation
2594  */
2595 //================================================================================
2596
2597 bool _ViscousBuilder::makeLayer(_SolidData& data)
2598 {
2599   // make a map to find new nodes on sub-shapes shared with other SOLID
2600   map< TGeomID, TNode2Edge* >::iterator s2ne;
2601   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2602   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2603   {
2604     TGeomID shapeInd = s2s->first;
2605     for ( size_t i = 0; i < _sdVec.size(); ++i )
2606     {
2607       if ( _sdVec[i]._index == data._index ) continue;
2608       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2609       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2610            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2611       {
2612         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2613         break;
2614       }
2615     }
2616   }
2617
2618   // Create temporary faces and _LayerEdge's
2619
2620   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2621
2622   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2623
2624   data._stepSize = Precision::Infinite();
2625   data._stepSizeNodes[0] = 0;
2626
2627   SMESH_MesherHelper helper( *_mesh );
2628   helper.SetSubShape( data._solid );
2629   helper.SetElementsOnShape( true );
2630
2631   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2632   TNode2Edge::iterator n2e2;
2633
2634   // make _LayerEdge's
2635   for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2636   {
2637     const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2638     SMESH_subMesh*    sm = _mesh->GetSubMesh( F );
2639     const TGeomID     id = sm->GetId();
2640     if ( edgesByGeom[ id ]._shape.IsNull() )
2641       continue; // no layers
2642     SMESH_ProxyMesh::SubMesh* proxySub =
2643       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2644
2645     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2646     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2647
2648     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2649     while ( eIt->more() )
2650     {
2651       const SMDS_MeshElement* face = eIt->next();
2652       double          faceMaxCosin = -1;
2653       _LayerEdge*     maxCosinEdge = 0;
2654       int             nbDegenNodes = 0;
2655
2656       newNodes.resize( face->NbCornerNodes() );
2657       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2658       {
2659         const SMDS_MeshNode* n = face->GetNode( i );
2660         const int      shapeID = n->getshapeId();
2661         const bool onDegenShap = helper.IsDegenShape( shapeID );
2662         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2663         if ( onDegenShap )
2664         {
2665           if ( onDegenEdge )
2666           {
2667             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2668             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2669             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2670             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2671               n = vN;
2672               nbDegenNodes++;
2673             }
2674           }
2675           else
2676           {
2677             nbDegenNodes++;
2678           }
2679         }
2680         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2681         if ( !(*n2e).second )
2682         {
2683           // add a _LayerEdge
2684           _LayerEdge* edge = _Factory::NewLayerEdge();
2685           edge->_nodes.push_back( n );
2686           n2e->second = edge;
2687           edgesByGeom[ shapeID ]._edges.push_back( edge );
2688           const bool noShrink = data._noShrinkShapes.count( shapeID );
2689
2690           SMESH_TNodeXYZ xyz( n );
2691
2692           // set edge data or find already refined _LayerEdge and get data from it
2693           if (( !noShrink                                                     ) &&
2694               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2695               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2696               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2697           {
2698             _LayerEdge* foundEdge = (*n2e2).second;
2699             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2700             foundEdge->_pos.push_back( lastPos );
2701             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2702             const_cast< SMDS_MeshNode* >
2703               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2704           }
2705           else
2706           {
2707             if ( !noShrink )
2708             {
2709               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2710             }
2711             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2712               return false;
2713
2714             if ( edge->_nodes.size() < 2 )
2715               edge->Block( data );
2716               //data._noShrinkShapes.insert( shapeID );
2717           }
2718           dumpMove(edge->_nodes.back());
2719
2720           if ( edge->_cosin > faceMaxCosin )
2721           {
2722             faceMaxCosin = edge->_cosin;
2723             maxCosinEdge = edge;
2724           }
2725         }
2726         newNodes[ i ] = n2e->second->_nodes.back();
2727
2728         if ( onDegenEdge )
2729           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2730       }
2731       if ( newNodes.size() - nbDegenNodes < 2 )
2732         continue;
2733
2734       // create a temporary face
2735       const SMDS_MeshElement* newFace =
2736         new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2737       proxySub->AddElement( newFace );
2738
2739       // compute inflation step size by min size of element on a convex surface
2740       if ( faceMaxCosin > theMinSmoothCosin )
2741         limitStepSize( data, face, maxCosinEdge );
2742
2743     } // loop on 2D elements on a FACE
2744   } // loop on FACEs of a SOLID to create _LayerEdge's
2745
2746
2747   // Set _LayerEdge::_neibors
2748   TNode2Edge::iterator n2e;
2749   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2750   {
2751     _EdgesOnShape& eos = data._edgesOnShape[iS];
2752     for ( size_t i = 0; i < eos._edges.size(); ++i )
2753     {
2754       _LayerEdge* edge = eos._edges[i];
2755       TIDSortedNodeSet nearNodes;
2756       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2757       while ( fIt->more() )
2758       {
2759         const SMDS_MeshElement* f = fIt->next();
2760         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2761           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2762       }
2763       nearNodes.erase( edge->_nodes[0] );
2764       edge->_neibors.reserve( nearNodes.size() );
2765       TIDSortedNodeSet::iterator node = nearNodes.begin();
2766       for ( ; node != nearNodes.end(); ++node )
2767         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2768           edge->_neibors.push_back( n2e->second );
2769     }
2770   }
2771
2772   data._epsilon = 1e-7;
2773   if ( data._stepSize < 1. )
2774     data._epsilon *= data._stepSize;
2775
2776   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2777     return false;
2778
2779   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2780   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2781
2782   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2783   const SMDS_MeshNode* nn[2];
2784   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2785   {
2786     _EdgesOnShape& eos = data._edgesOnShape[iS];
2787     for ( size_t i = 0; i < eos._edges.size(); ++i )
2788     {
2789       _LayerEdge* edge = eos._edges[i];
2790       if ( edge->IsOnEdge() )
2791       {
2792         // get neighbor nodes
2793         bool hasData = ( edge->_2neibors->_edges[0] );
2794         if ( hasData ) // _LayerEdge is a copy of another one
2795         {
2796           nn[0] = edge->_2neibors->srcNode(0);
2797           nn[1] = edge->_2neibors->srcNode(1);
2798         }
2799         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2800         {
2801           return false;
2802         }
2803         // set neighbor _LayerEdge's
2804         for ( int j = 0; j < 2; ++j )
2805         {
2806           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2807             return error("_LayerEdge not found by src node", data._index);
2808           edge->_2neibors->_edges[j] = n2e->second;
2809         }
2810         if ( !hasData )
2811           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2812       }
2813
2814       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2815       {
2816         _Simplex& s = edge->_simplices[j];
2817         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2818         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2819       }
2820
2821       // For an _LayerEdge on a degenerated EDGE, copy some data from
2822       // a corresponding _LayerEdge on a VERTEX
2823       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2824       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2825       {
2826         // Generally we should not get here
2827         if ( eos.ShapeType() != TopAbs_EDGE )
2828           continue;
2829         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2830         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2831         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2832           continue;
2833         const _LayerEdge* vEdge = n2e->second;
2834         edge->_normal    = vEdge->_normal;
2835         edge->_lenFactor = vEdge->_lenFactor;
2836         edge->_cosin     = vEdge->_cosin;
2837       }
2838
2839     } // loop on data._edgesOnShape._edges
2840   } // loop on data._edgesOnShape
2841
2842   // fix _LayerEdge::_2neibors on EDGEs to smooth
2843   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2844   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2845   //   if ( !e2c->second.IsNull() )
2846   //   {
2847   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2848   //       data.Sort2NeiborsOnEdge( eos->_edges );
2849   //   }
2850
2851   dumpFunctionEnd();
2852   return true;
2853 }
2854
2855 //================================================================================
2856 /*!
2857  * \brief Compute inflation step size by min size of element on a convex surface
2858  */
2859 //================================================================================
2860
2861 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2862                                      const SMDS_MeshElement* face,
2863                                      const _LayerEdge*       maxCosinEdge )
2864 {
2865   int iN = 0;
2866   double minSize = 10 * data._stepSize;
2867   const int nbNodes = face->NbCornerNodes();
2868   for ( int i = 0; i < nbNodes; ++i )
2869   {
2870     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2871     const SMDS_MeshNode*  curN = face->GetNode( i );
2872     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2873          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2874     {
2875       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2876       if ( dist < minSize )
2877         minSize = dist, iN = i;
2878     }
2879   }
2880   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2881   if ( newStep < data._stepSize )
2882   {
2883     data._stepSize = newStep;
2884     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2885     data._stepSizeNodes[0] = face->GetNode( iN );
2886     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2887   }
2888 }
2889
2890 //================================================================================
2891 /*!
2892  * \brief Compute inflation step size by min size of element on a convex surface
2893  */
2894 //================================================================================
2895
2896 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2897 {
2898   if ( minSize < data._stepSize )
2899   {
2900     data._stepSize = minSize;
2901     if ( data._stepSizeNodes[0] )
2902     {
2903       double dist =
2904         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2905       data._stepSizeCoeff = data._stepSize / dist;
2906     }
2907   }
2908 }
2909
2910 //================================================================================
2911 /*!
2912  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2913  */
2914 //================================================================================
2915
2916 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2917 {
2918   SMESH_MesherHelper helper( *_mesh );
2919
2920   BRepLProp_SLProps surfProp( 2, 1e-6 );
2921   data._convexFaces.clear();
2922
2923   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2924   {
2925     _EdgesOnShape& eof = data._edgesOnShape[iS];
2926     if ( eof.ShapeType() != TopAbs_FACE ||
2927          data._ignoreFaceIds.count( eof._shapeID ))
2928       continue;
2929
2930     TopoDS_Face        F = TopoDS::Face( eof._shape );
2931     const TGeomID faceID = eof._shapeID;
2932
2933     BRepAdaptor_Surface surface( F, false );
2934     surfProp.SetSurface( surface );
2935
2936     _ConvexFace cnvFace;
2937     cnvFace._face = F;
2938     cnvFace._normalsFixed = false;
2939     cnvFace._isTooCurved = false;
2940
2941     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
2942     if ( maxCurvature > 0 )
2943     {
2944       limitStepSize( data, 0.9 / maxCurvature );
2945       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
2946     }
2947     if ( !cnvFace._isTooCurved ) continue;
2948
2949     _ConvexFace & convFace =
2950       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2951
2952     // skip a closed surface (data._convexFaces is useful anyway)
2953     bool isClosedF = false;
2954     helper.SetSubShape( F );
2955     if ( helper.HasRealSeam() )
2956     {
2957       // in the closed surface there must be a closed EDGE
2958       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
2959         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
2960     }
2961     if ( isClosedF )
2962     {
2963       // limit _LayerEdge::_maxLen on the FACE
2964       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2965       const double minCurvature =
2966         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
2967       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
2968       if ( id2eos != cnvFace._subIdToEOS.end() )
2969       {
2970         _EdgesOnShape& eos = * id2eos->second;
2971         for ( size_t i = 0; i < eos._edges.size(); ++i )
2972         {
2973           _LayerEdge* ledge = eos._edges[ i ];
2974           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
2975           surfProp.SetParameters( uv.X(), uv.Y() );
2976           if ( surfProp.IsCurvatureDefined() )
2977           {
2978             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
2979                                     surfProp.MinCurvature() * oriFactor );
2980             if ( curvature > minCurvature )
2981               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
2982           }
2983         }
2984       }
2985       continue;
2986     }
2987
2988     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2989     // prism distortion.
2990     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
2991     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
2992     {
2993       // there are _LayerEdge's on the FACE it-self;
2994       // select _LayerEdge's near EDGEs
2995       _EdgesOnShape& eos = * id2eos->second;
2996       for ( size_t i = 0; i < eos._edges.size(); ++i )
2997       {
2998         _LayerEdge* ledge = eos._edges[ i ];
2999         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
3000           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
3001           {
3002             // do not select _LayerEdge's neighboring sharp EDGEs
3003             bool sharpNbr = false;
3004             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
3005               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
3006             if ( !sharpNbr )
3007               convFace._simplexTestEdges.push_back( ledge );
3008             break;
3009           }
3010       }
3011     }
3012     else
3013     {
3014       // where there are no _LayerEdge's on a _ConvexFace,
3015       // as e.g. on a fillet surface with no internal nodes - issue 22580,
3016       // so that collision of viscous internal faces is not detected by check of
3017       // intersection of _LayerEdge's with the viscous internal faces.
3018
3019       set< const SMDS_MeshNode* > usedNodes;
3020
3021       // look for _LayerEdge's with null _sWOL
3022       id2eos = convFace._subIdToEOS.begin();
3023       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3024       {
3025         _EdgesOnShape& eos = * id2eos->second;
3026         if ( !eos._sWOL.IsNull() )
3027           continue;
3028         for ( size_t i = 0; i < eos._edges.size(); ++i )
3029         {
3030           _LayerEdge* ledge = eos._edges[ i ];
3031           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3032           if ( !usedNodes.insert( srcNode ).second ) continue;
3033
3034           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3035           {
3036             usedNodes.insert( ledge->_simplices[i]._nPrev );
3037             usedNodes.insert( ledge->_simplices[i]._nNext );
3038           }
3039           convFace._simplexTestEdges.push_back( ledge );
3040         }
3041       }
3042     }
3043   } // loop on FACEs of data._solid
3044 }
3045
3046 //================================================================================
3047 /*!
3048  * \brief Detect shapes (and _LayerEdge's on them) to smooth
3049  */
3050 //================================================================================
3051
3052 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3053 {
3054   // define allowed thickness
3055   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3056
3057
3058   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3059   // boundary inclined to the shape at a sharp angle
3060
3061   TopTools_MapOfShape edgesOfSmooFaces;
3062   SMESH_MesherHelper helper( *_mesh );
3063   bool ok = true;
3064
3065   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3066   data._nbShapesToSmooth = 0;
3067
3068   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3069   {
3070     _EdgesOnShape& eos = edgesByGeom[iS];
3071     eos._toSmooth = false;
3072     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3073       continue;
3074
3075     double tgtThick = eos._hyp.GetTotalThickness();
3076     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3077     while ( subIt->more() && !eos._toSmooth )
3078     {
3079       TGeomID iSub = subIt->next()->GetId();
3080       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3081       if ( eSub.empty() ) continue;
3082
3083       double faceSize;
3084       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3085         if ( eSub[i]->_cosin > theMinSmoothCosin )
3086         {
3087           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3088           while ( fIt->more() && !eos._toSmooth )
3089           {
3090             const SMDS_MeshElement* face = fIt->next();
3091             if ( face->getshapeId() == eos._shapeID &&
3092                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3093             {
3094               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3095                                              tgtThick * eSub[i]->_lenFactor,
3096                                              faceSize);
3097             }
3098           }
3099         }
3100     }
3101     if ( eos._toSmooth )
3102     {
3103       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3104         edgesOfSmooFaces.Add( eExp.Current() );
3105
3106       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3107     }
3108     data._nbShapesToSmooth += eos._toSmooth;
3109
3110   }  // check FACEs
3111
3112   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3113   {
3114     _EdgesOnShape& eos = edgesByGeom[iS];
3115     eos._edgeSmoother = NULL;
3116     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3117     if ( !eos._hyp.ToSmooth() ) continue;
3118
3119     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3120     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3121       continue;
3122
3123     double tgtThick = eos._hyp.GetTotalThickness();
3124     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3125     {
3126       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3127       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3128       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3129       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ));
3130       double angle    = eDir.Angle( eV[0]->_normal );
3131       double cosin    = Cos( angle );
3132       double cosinAbs = Abs( cosin );
3133       if ( cosinAbs > theMinSmoothCosin )
3134       {
3135         // always smooth analytic EDGEs
3136         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3137         eos._toSmooth = ! curve.IsNull();
3138
3139         // compare tgtThick with the length of an end segment
3140         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3141         while ( eIt->more() && !eos._toSmooth )
3142         {
3143           const SMDS_MeshElement* endSeg = eIt->next();
3144           if ( endSeg->getshapeId() == (int) iS )
3145           {
3146             double segLen =
3147               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3148             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3149           }
3150         }
3151         if ( eos._toSmooth )
3152         {
3153           eos._edgeSmoother = new _Smoother1D( curve, eos );
3154
3155           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3156           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3157         }
3158       }
3159     }
3160     data._nbShapesToSmooth += eos._toSmooth;
3161
3162   } // check EDGEs
3163
3164   // Reset _cosin if no smooth is allowed by the user
3165   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3166   {
3167     _EdgesOnShape& eos = edgesByGeom[iS];
3168     if ( eos._edges.empty() ) continue;
3169
3170     if ( !eos._hyp.ToSmooth() )
3171       for ( size_t i = 0; i < eos._edges.size(); ++i )
3172         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3173         eos._edges[i]->_lenFactor = 1;
3174   }
3175
3176
3177   // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3178
3179   TopTools_MapOfShape c1VV;
3180
3181   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3182   {
3183     _EdgesOnShape& eos = edgesByGeom[iS];
3184     if ( eos._edges.empty() ||
3185          eos.ShapeType() != TopAbs_FACE ||
3186          !eos._toSmooth )
3187       continue;
3188
3189     // check EDGEs of a FACE
3190     TopTools_MapOfShape checkedEE, allVV;
3191     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3192     while ( !smQueue.empty() )
3193     {
3194       SMESH_subMesh* sm = smQueue.front();
3195       smQueue.pop_front();
3196       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3197       while ( smIt->more() )
3198       {
3199         sm = smIt->next();
3200         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3201           allVV.Add( sm->GetSubShape() );
3202         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3203              !checkedEE.Add( sm->GetSubShape() ))
3204           continue;
3205
3206         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3207         vector<_LayerEdge*>& eE = eoe->_edges;
3208         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3209           continue;
3210
3211         bool isC1 = true; // check continuity along an EDGE
3212         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3213           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3214         if ( !isC1 )
3215           continue;
3216
3217         // check that mesh faces are C1 as well
3218         {
3219           gp_XYZ norm1, norm2;
3220           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3221           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3222           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3223             continue;
3224           while ( fIt->more() && isC1 )
3225             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3226                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3227           if ( !isC1 )
3228             continue;
3229         }
3230
3231         // add the EDGE and an adjacent FACE to _eosC1
3232         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3233         while ( const TopoDS_Shape* face = fIt->next() )
3234         {
3235           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3236           if ( !eof ) continue; // other solid
3237           if ( eos._shapeID == eof->_shapeID ) continue;
3238           if ( !eos.HasC1( eof ))
3239           {
3240             // check the FACEs
3241             eos._eosC1.push_back( eof );
3242             eof->_toSmooth = false;
3243             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3244             smQueue.push_back( eof->_subMesh );
3245           }
3246           if ( !eos.HasC1( eoe ))
3247           {
3248             eos._eosC1.push_back( eoe );
3249             eoe->_toSmooth = false;
3250             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3251           }
3252         }
3253       }
3254     }
3255     if ( eos._eosC1.empty() )
3256       continue;
3257
3258     // check VERTEXes of C1 FACEs
3259     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3260     for ( ; vIt.More(); vIt.Next() )
3261     {
3262       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3263       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3264         continue;
3265
3266       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3267       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3268       while ( const TopoDS_Shape* face = fIt->next() )
3269       {
3270         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3271         if ( !eof ) continue; // other solid
3272         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3273         if ( !isC1 )
3274           break;
3275       }
3276       if ( isC1 )
3277       {
3278         eos._eosC1.push_back( eov );
3279         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3280         c1VV.Add( eov->_shape );
3281       }
3282     }
3283
3284   } // fill _eosC1 of FACEs
3285
3286
3287   // Find C1 EDGEs
3288
3289   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3290
3291   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3292   {
3293     _EdgesOnShape& eov = edgesByGeom[iS];
3294     if ( eov._edges.empty() ||
3295          eov.ShapeType() != TopAbs_VERTEX ||
3296          c1VV.Contains( eov._shape ))
3297       continue;
3298     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3299
3300     // get directions of surrounding EDGEs
3301     dirOfEdges.clear();
3302     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3303     while ( const TopoDS_Shape* e = fIt->next() )
3304     {
3305       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3306       if ( !eoe ) continue; // other solid
3307       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V );
3308       if ( !Precision::IsInfinite( eDir.X() ))
3309         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3310     }
3311
3312     // find EDGEs with C1 directions
3313     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3314       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3315         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3316         {
3317           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3318           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3319           if ( isC1 )
3320           {
3321             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3322             for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3323             {
3324               size_t k = isJ ? j : i;
3325               const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3326               double eLen = SMESH_Algo::EdgeLength( e );
3327               if ( eLen < maxEdgeLen )
3328               {
3329                 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3330                 if ( oppV.IsSame( V ))
3331                   oppV = SMESH_MesherHelper::IthVertex( 1, e );
3332                 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3333                 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3334                   eov._eosC1.push_back( dirOfEdges[k].first );
3335               }
3336               dirOfEdges[k].first = 0;
3337             }
3338           }
3339         }
3340   } // fill _eosC1 of VERTEXes
3341
3342
3343
3344   return ok;
3345 }
3346
3347 //================================================================================
3348 /*!
3349  * \brief Set up _SolidData::_edgesOnShape
3350  */
3351 //================================================================================
3352
3353 void _ViscousBuilder::makeEdgesOnShape()
3354 {
3355   const int nbShapes = getMeshDS()->MaxShapeIndex();
3356
3357   for ( size_t i = 0; i < _sdVec.size(); ++i )
3358   {
3359     _SolidData& data = _sdVec[ i ];
3360     vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3361     edgesByGeom.resize( nbShapes+1 );
3362
3363     // set data of _EdgesOnShape's
3364     if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3365     {
3366       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3367       while ( smIt->more() )
3368       {
3369         sm = smIt->next();
3370         if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3371              data._ignoreFaceIds.count( sm->GetId() ))
3372           continue;
3373
3374         setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3375       }
3376     }
3377   }
3378 }
3379
3380 //================================================================================
3381 /*!
3382  * \brief initialize data of _EdgesOnShape
3383  */
3384 //================================================================================
3385
3386 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3387                                     SMESH_subMesh* sm,
3388                                     _SolidData&    data )
3389 {
3390   if ( !eos._shape.IsNull() ||
3391        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3392     return;
3393
3394   SMESH_MesherHelper helper( *_mesh );
3395
3396   eos._subMesh = sm;
3397   eos._shapeID = sm->GetId();
3398   eos._shape   = sm->GetSubShape();
3399   if ( eos.ShapeType() == TopAbs_FACE )
3400     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3401   eos._toSmooth = false;
3402   eos._data = &data;
3403
3404   // set _SWOL
3405   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3406     data._shrinkShape2Shape.find( eos._shapeID );
3407   if ( s2s != data._shrinkShape2Shape.end() )
3408     eos._sWOL = s2s->second;
3409
3410   eos._isRegularSWOL = true;
3411   if ( eos.SWOLType() == TopAbs_FACE )
3412   {
3413     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3414     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3415     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3416   }
3417
3418   // set _hyp
3419   if ( data._hyps.size() == 1 )
3420   {
3421     eos._hyp = data._hyps.back();
3422   }
3423   else
3424   {
3425     // compute average StdMeshers_ViscousLayers parameters
3426     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3427     if ( eos.ShapeType() == TopAbs_FACE )
3428     {
3429       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3430         eos._hyp = f2hyp->second;
3431     }
3432     else
3433     {
3434       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3435       while ( const TopoDS_Shape* face = fIt->next() )
3436       {
3437         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3438         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3439           eos._hyp.Add( f2hyp->second );
3440       }
3441     }
3442   }
3443
3444   // set _faceNormals
3445   if ( ! eos._hyp.UseSurfaceNormal() )
3446   {
3447     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3448     {
3449       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3450       if ( !smDS ) return;
3451       eos._faceNormals.reserve( smDS->NbElements() );
3452
3453       double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3454       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3455       for ( ; eIt->more(); )
3456       {
3457         const SMDS_MeshElement* face = eIt->next();
3458         gp_XYZ&                 norm = eos._faceNormals[face];
3459         if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3460           norm.SetCoord( 0,0,0 );
3461         norm *= oriFactor;
3462       }
3463     }
3464     else // find EOS of adjacent FACEs
3465     {
3466       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3467       while ( const TopoDS_Shape* face = fIt->next() )
3468       {
3469         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3470         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3471         if ( eos._faceEOS.back()->_shape.IsNull() )
3472           // avoid using uninitialised _shapeID in GetNormal()
3473           eos._faceEOS.back()->_shapeID = faceID;
3474       }
3475     }
3476   }
3477 }
3478
3479 //================================================================================
3480 /*!
3481  * \brief Returns normal of a face
3482  */
3483 //================================================================================
3484
3485 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3486 {
3487   bool ok = false;
3488   _EdgesOnShape* eos = 0;
3489
3490   if ( face->getshapeId() == _shapeID )
3491   {
3492     eos = this;
3493   }
3494   else
3495   {
3496     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3497       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3498         eos = _faceEOS[ iF ];
3499   }
3500
3501   if (( eos ) &&
3502       ( ok = ( eos->_faceNormals.count( face ) )))
3503   {
3504     norm = eos->_faceNormals[ face ];
3505   }
3506   else if ( !eos )
3507   {
3508     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3509               << " on _shape #" << _shapeID );
3510   }
3511   return ok;
3512 }
3513
3514 //================================================================================
3515 /*!
3516  * \brief EdgesOnShape destructor
3517  */
3518 //================================================================================
3519
3520 _EdgesOnShape::~_EdgesOnShape()
3521 {
3522   delete _edgeSmoother;
3523 }
3524
3525 //================================================================================
3526 /*!
3527  * \brief Set data of _LayerEdge needed for smoothing
3528  */
3529 //================================================================================
3530
3531 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3532                                   _EdgesOnShape&      eos,
3533                                   SMESH_MesherHelper& helper,
3534                                   _SolidData&         data)
3535 {
3536   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3537
3538   edge._len          = 0;
3539   edge._maxLen       = Precision::Infinite();
3540   edge._minAngle     = 0;
3541   edge._2neibors     = 0;
3542   edge._curvature    = 0;
3543   edge._flags        = 0;
3544   edge._smooFunction = 0;
3545
3546   // --------------------------
3547   // Compute _normal and _cosin
3548   // --------------------------
3549
3550   edge._cosin     = 0;
3551   edge._lenFactor = 1.;
3552   edge._normal.SetCoord(0,0,0);
3553   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3554
3555   int totalNbFaces = 0;
3556   TopoDS_Face F;
3557   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3558   gp_Vec geomNorm;
3559   bool normOK = true;
3560
3561   const bool onShrinkShape = !eos._sWOL.IsNull();
3562   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3563                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3564
3565   // get geom FACEs the node lies on
3566   //if ( useGeometry )
3567   {
3568     set<TGeomID> faceIds;
3569     if  ( eos.ShapeType() == TopAbs_FACE )
3570     {
3571       faceIds.insert( eos._shapeID );
3572     }
3573     else
3574     {
3575       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3576       while ( fIt->more() )
3577         faceIds.insert( fIt->next()->getshapeId() );
3578     }
3579     set<TGeomID>::iterator id = faceIds.begin();
3580     for ( ; id != faceIds.end(); ++id )
3581     {
3582       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3583       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3584         continue;
3585       F = TopoDS::Face( s );
3586       face2Norm[ totalNbFaces ].first = F;
3587       totalNbFaces++;
3588     }
3589   }
3590
3591   // find _normal
3592   bool fromVonF = false;
3593   if ( useGeometry )
3594   {
3595     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3596                  eos.SWOLType()  == TopAbs_FACE  &&
3597                  totalNbFaces > 1 );
3598
3599     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3600     {
3601       if ( eos.SWOLType() == TopAbs_EDGE )
3602       {
3603         // inflate from VERTEX along EDGE
3604         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ));
3605       }
3606       else if ( eos.ShapeType() == TopAbs_VERTEX )
3607       {
3608         // inflate from VERTEX along FACE
3609         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3610                                    node, helper, normOK, &edge._cosin);
3611       }
3612       else
3613       {
3614         // inflate from EDGE along FACE
3615         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3616                                    node, helper, normOK);
3617       }
3618     }
3619     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3620     {
3621       if ( fromVonF )
3622         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3623
3624       int nbOkNorms = 0;
3625       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3626       {
3627         F = face2Norm[ iF ].first;
3628         geomNorm = getFaceNormal( node, F, helper, normOK );
3629         if ( !normOK ) continue;
3630         nbOkNorms++;
3631
3632         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3633           geomNorm.Reverse();
3634         face2Norm[ iF ].second = geomNorm.XYZ();
3635         edge._normal += geomNorm.XYZ();
3636       }
3637       if ( nbOkNorms == 0 )
3638         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3639
3640       if ( totalNbFaces >= 3 )
3641       {
3642         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3643       }
3644
3645       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3646       {
3647         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3648         edge._normal.SetCoord( 0,0,0 );
3649         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3650         {
3651           const TopoDS_Face& F = face2Norm[iF].first;
3652           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3653           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3654             geomNorm.Reverse();
3655           if ( normOK )
3656             face2Norm[ iF ].second = geomNorm.XYZ();
3657           edge._normal += face2Norm[ iF ].second;
3658         }
3659       }
3660     }
3661   }
3662   else // !useGeometry - get _normal using surrounding mesh faces
3663   {
3664     edge._normal = getWeigthedNormal( &edge );
3665
3666     // set<TGeomID> faceIds;
3667     //
3668     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3669     // while ( fIt->more() )
3670     // {
3671     //   const SMDS_MeshElement* face = fIt->next();
3672     //   if ( eos.GetNormal( face, geomNorm ))
3673     //   {
3674     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3675     //       continue; // use only one mesh face on FACE
3676     //     edge._normal += geomNorm.XYZ();
3677     //     totalNbFaces++;
3678     //   }
3679     // }
3680   }
3681
3682   // compute _cosin
3683   //if ( eos._hyp.UseSurfaceNormal() )
3684   {
3685     switch ( eos.ShapeType() )
3686     {
3687     case TopAbs_FACE: {
3688       edge._cosin = 0;
3689       break;
3690     }
3691     case TopAbs_EDGE: {
3692       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3693       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3694       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3695       edge._cosin      = Cos( angle );
3696       break;
3697     }
3698     case TopAbs_VERTEX: {
3699       if ( fromVonF )
3700       {
3701         getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3702                     node, helper, normOK, &edge._cosin );
3703       }
3704       else if ( eos.SWOLType() != TopAbs_FACE ) // else _cosin is set by getFaceDir()
3705       {
3706         TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3707         gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
3708         double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3709         edge._cosin      = Cos( angle );
3710         if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
3711           for ( int iF = 1; iF < totalNbFaces; ++iF )
3712           {
3713             F = face2Norm[ iF ].first;
3714             inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3715             if ( normOK ) {
3716               double angle = inFaceDir.Angle( edge._normal );
3717               double cosin = Cos( angle );
3718               if ( Abs( cosin ) > Abs( edge._cosin ))
3719                 edge._cosin = cosin;
3720             }
3721           }
3722       }
3723       break;
3724     }
3725     default:
3726       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3727     }
3728   }
3729
3730   double normSize = edge._normal.SquareModulus();
3731   if ( normSize < numeric_limits<double>::min() )
3732     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3733
3734   edge._normal /= sqrt( normSize );
3735
3736   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3737   {
3738     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3739     edge._nodes.resize( 1 );
3740     edge._normal.SetCoord( 0,0,0 );
3741     edge.SetMaxLen( 0 );
3742   }
3743
3744   // Set the rest data
3745   // --------------------
3746
3747   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3748
3749   if ( onShrinkShape )
3750   {
3751     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3752     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3753       sm->RemoveNode( tgtNode );
3754
3755     // set initial position which is parameters on _sWOL in this case
3756     if ( eos.SWOLType() == TopAbs_EDGE )
3757     {
3758       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3759       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3760       if ( edge._nodes.size() > 1 )
3761         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3762     }
3763     else // eos.SWOLType() == TopAbs_FACE
3764     {
3765       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3766       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3767       if ( edge._nodes.size() > 1 )
3768         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3769     }
3770
3771     if ( edge._nodes.size() > 1 )
3772     {
3773       // check if an angle between a FACE with layers and SWOL is sharp,
3774       // else the edge should not inflate
3775       F.Nullify();
3776       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3777         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3778           F = face2Norm[iF].first;
3779       if ( !F.IsNull())
3780       {
3781         geomNorm = getFaceNormal( node, F, helper, normOK );
3782         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3783           geomNorm.Reverse(); // inside the SOLID
3784         if ( geomNorm * edge._normal < -0.001 )
3785         {
3786           getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3787           edge._nodes.resize( 1 );
3788         }
3789         else if ( edge._lenFactor > 3 )
3790         {
3791           edge._lenFactor = 2;
3792           edge.Set( _LayerEdge::RISKY_SWOL );
3793         }
3794       }
3795     }
3796   }
3797   else
3798   {
3799     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3800
3801     if ( eos.ShapeType() == TopAbs_FACE )
3802     {
3803       double angle;
3804       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3805       {
3806         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3807         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3808       }
3809     }
3810   }
3811
3812   // Set neighbor nodes for a _LayerEdge based on EDGE
3813
3814   if ( eos.ShapeType() == TopAbs_EDGE /*||
3815        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3816   {
3817     edge._2neibors = _Factory::NewNearEdges();
3818     // target nodes instead of source ones will be set later
3819   }
3820
3821   return true;
3822 }
3823
3824 //================================================================================
3825 /*!
3826  * \brief Return normal to a FACE at a node
3827  *  \param [in] n - node
3828  *  \param [in] face - FACE
3829  *  \param [in] helper - helper
3830  *  \param [out] isOK - true or false
3831  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3832  *  \return gp_XYZ - normal
3833  */
3834 //================================================================================
3835
3836 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3837                                       const TopoDS_Face&   face,
3838                                       SMESH_MesherHelper&  helper,
3839                                       bool&                isOK,
3840                                       bool                 shiftInside)
3841 {
3842   gp_XY uv;
3843   if ( shiftInside )
3844   {
3845     // get a shifted position
3846     gp_Pnt p = SMESH_TNodeXYZ( node );
3847     gp_XYZ shift( 0,0,0 );
3848     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3849     switch ( S.ShapeType() ) {
3850     case TopAbs_VERTEX:
3851     {
3852       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3853       break;
3854     }
3855     case TopAbs_EDGE:
3856     {
3857       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
3858       break;
3859     }
3860     default:
3861       isOK = false;
3862     }
3863     if ( isOK )
3864       shift.Normalize();
3865     p.Translate( shift * 1e-5 );
3866
3867     TopLoc_Location loc;
3868     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
3869
3870     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
3871     
3872     projector.Perform( p );
3873     if ( !projector.IsDone() || projector.NbPoints() < 1 )
3874     {
3875       isOK = false;
3876       return p.XYZ();
3877     }
3878     Standard_Real U,V;
3879     projector.LowerDistanceParameters(U,V);
3880     uv.SetCoord( U,V );
3881   }
3882   else
3883   {
3884     uv = helper.GetNodeUV( face, node, 0, &isOK );
3885   }
3886
3887   gp_Dir normal;
3888   isOK = false;
3889
3890   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
3891
3892   if ( !shiftInside &&
3893        helper.IsDegenShape( node->getshapeId() ) &&
3894        getFaceNormalAtSingularity( uv, face, helper, normal ))
3895   {
3896     isOK = true;
3897     return normal.XYZ();
3898   }
3899
3900   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
3901   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3902
3903   if ( pointKind == IMPOSSIBLE &&
3904        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
3905   {
3906     // probably NormEstim() failed due to a too high tolerance
3907     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
3908     isOK = ( pointKind < IMPOSSIBLE );
3909   }
3910   if ( pointKind < IMPOSSIBLE )
3911   {
3912     if ( pointKind != REGULAR &&
3913          !shiftInside &&
3914          node->GetPosition()->GetDim() < 2 ) // FACE boundary
3915     {
3916       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
3917       if ( normShift * normal.XYZ() < 0. )
3918         normal = normShift;
3919     }
3920     isOK = true;
3921   }
3922
3923   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
3924   {
3925     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
3926
3927     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3928     while ( fIt->more() )
3929     {
3930       const SMDS_MeshElement* f = fIt->next();
3931       if ( f->getshapeId() == faceID )
3932       {
3933         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
3934         if ( isOK )
3935         {
3936           TopoDS_Face ff = face;
3937           ff.Orientation( TopAbs_FORWARD );
3938           if ( helper.IsReversedSubMesh( ff ))
3939             normal.Reverse();
3940           break;
3941         }
3942       }
3943     }
3944   }
3945   return normal.XYZ();
3946 }
3947
3948 //================================================================================
3949 /*!
3950  * \brief Try to get normal at a singularity of a surface basing on it's nature
3951  */
3952 //================================================================================
3953
3954 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
3955                                                   const TopoDS_Face&  face,
3956                                                   SMESH_MesherHelper& /*helper*/,
3957                                                   gp_Dir&             normal )
3958 {
3959   BRepAdaptor_Surface surface( face );
3960   gp_Dir axis;
3961   if ( !getRovolutionAxis( surface, axis ))
3962     return false;
3963
3964   double f,l, d, du, dv;
3965   f = surface.FirstUParameter();
3966   l = surface.LastUParameter();
3967   d = ( uv.X() - f ) / ( l - f );
3968   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3969   f = surface.FirstVParameter();
3970   l = surface.LastVParameter();
3971   d = ( uv.Y() - f ) / ( l - f );
3972   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
3973
3974   gp_Dir refDir;
3975   gp_Pnt2d testUV = uv;
3976   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
3977   double tol = 1e-5;
3978   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
3979   for ( int iLoop = 0; true ; ++iLoop )
3980   {
3981     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
3982     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
3983       break;
3984     if ( iLoop > 20 )
3985       return false;
3986     tol /= 10.;
3987   }
3988
3989   if ( axis * refDir < 0. )
3990     axis.Reverse();
3991
3992   normal = axis;
3993
3994   return true;
3995 }
3996
3997 //================================================================================
3998 /*!
3999  * \brief Return a normal at a node weighted with angles taken by faces
4000  */
4001 //================================================================================
4002
4003 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
4004 {
4005   const SMDS_MeshNode* n = edge->_nodes[0];
4006
4007   gp_XYZ resNorm(0,0,0);
4008   SMESH_TNodeXYZ p0( n ), pP, pN;
4009   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4010   {
4011     pP.Set( edge->_simplices[i]._nPrev );
4012     pN.Set( edge->_simplices[i]._nNext );
4013     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
4014     double l0P = v0P.SquareMagnitude();
4015     double l0N = v0N.SquareMagnitude();
4016     double lPN = vPN.SquareMagnitude();
4017     if ( l0P < std::numeric_limits<double>::min() ||
4018          l0N < std::numeric_limits<double>::min() ||
4019          lPN < std::numeric_limits<double>::min() )
4020       continue;
4021     double lNorm = norm.SquareMagnitude();
4022     double  sin2 = lNorm / l0P / l0N;
4023     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4024
4025     double weight = sin2 * angle / lPN;
4026     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4027   }
4028
4029   return resNorm;
4030 }
4031
4032 //================================================================================
4033 /*!
4034  * \brief Return a normal at a node by getting a common point of offset planes
4035  *        defined by the FACE normals
4036  */
4037 //================================================================================
4038
4039 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
4040                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4041                                            int                              nbFaces,
4042                                            bool                             lastNoOffset)
4043 {
4044   SMESH_TNodeXYZ p0 = edge->_nodes[0];
4045
4046   gp_XYZ resNorm(0,0,0);
4047   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4048   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4049   {
4050     for ( int i = 0; i < nbFaces; ++i )
4051       resNorm += f2Normal[i].second;
4052     return resNorm;
4053   }
4054
4055   // prepare _OffsetPlane's
4056   vector< _OffsetPlane > pln( nbFaces );
4057   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4058   {
4059     pln[i]._faceIndex = i;
4060     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4061   }
4062   if ( lastNoOffset )
4063   {
4064     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4065     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4066   }
4067
4068   // intersect neighboring OffsetPlane's
4069   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4070   while ( const TopoDS_Shape* edge = edgeIt->next() )
4071   {
4072     int f1 = -1, f2 = -1;
4073     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
4074       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4075         (( f1 < 0 ) ? f1 : f2 ) = i;
4076
4077     if ( f2 >= 0 )
4078       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4079   }
4080
4081   // get a common point
4082   gp_XYZ commonPnt( 0, 0, 0 );
4083   int nbPoints = 0;
4084   bool isPointFound;
4085   for ( int i = 0; i < nbFaces; ++i )
4086   {
4087     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4088     nbPoints  += isPointFound;
4089   }
4090   gp_XYZ wgtNorm = getWeigthedNormal( edge );
4091   if ( nbPoints == 0 )
4092     return wgtNorm;
4093
4094   commonPnt /= nbPoints;
4095   resNorm = commonPnt - p0;
4096   if ( lastNoOffset )
4097     return resNorm;
4098
4099   // choose the best among resNorm and wgtNorm
4100   resNorm.Normalize();
4101   wgtNorm.Normalize();
4102   double resMinDot = std::numeric_limits<double>::max();
4103   double wgtMinDot = std::numeric_limits<double>::max();
4104   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4105   {
4106     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4107     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4108   }
4109
4110   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4111   {
4112     edge->Set( _LayerEdge::MULTI_NORMAL );
4113   }
4114
4115   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4116 }
4117
4118 //================================================================================
4119 /*!
4120  * \brief Compute line of intersection of 2 planes
4121  */
4122 //================================================================================
4123
4124 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
4125                                             const TopoDS_Edge&   E,
4126                                             const TopoDS_Vertex& V )
4127 {
4128   int iNext = bool( _faceIndexNext[0] >= 0 );
4129   _faceIndexNext[ iNext ] = pln._faceIndex;
4130
4131   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4132   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4133
4134   gp_XYZ lineDir = n1 ^ n2;
4135
4136   double x = Abs( lineDir.X() );
4137   double y = Abs( lineDir.Y() );
4138   double z = Abs( lineDir.Z() );
4139
4140   int cooMax; // max coordinate
4141   if (x > y) {
4142     if (x > z) cooMax = 1;
4143     else       cooMax = 3;
4144   }
4145   else {
4146     if (y > z) cooMax = 2;
4147     else       cooMax = 3;
4148   }
4149
4150   gp_Pnt linePos;
4151   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4152   {
4153     // parallel planes - intersection is an offset of the common EDGE
4154     gp_Pnt p = BRep_Tool::Pnt( V );
4155     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4156     lineDir  = getEdgeDir( E, V );
4157   }
4158   else
4159   {
4160     // the constants in the 2 plane equations
4161     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4162     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4163
4164     switch ( cooMax ) {
4165     case 1:
4166       linePos.SetX(  0 );
4167       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4168       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4169       break;
4170     case 2:
4171       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4172       linePos.SetY(  0 );
4173       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4174       break;
4175     case 3:
4176       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4177       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4178       linePos.SetZ(  0 );
4179     }
4180   }
4181   gp_Lin& line = _lines[ iNext ];
4182   line.SetDirection( lineDir );
4183   line.SetLocation ( linePos );
4184
4185   _isLineOK[ iNext ] = true;
4186
4187
4188   iNext = bool( pln._faceIndexNext[0] >= 0 );
4189   pln._lines        [ iNext ] = line;
4190   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4191   pln._isLineOK     [ iNext ] = true;
4192 }
4193
4194 //================================================================================
4195 /*!
4196  * \brief Computes intersection point of two _lines
4197  */
4198 //================================================================================
4199
4200 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4201                                     const TopoDS_Vertex & V) const
4202 {
4203   gp_XYZ p( 0,0,0 );
4204   isFound = false;
4205
4206   if ( NbLines() == 2 )
4207   {
4208     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4209     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4210     if ( Abs( dot01 ) > 0.05 )
4211     {
4212       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4213       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4214       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4215       isFound = true;
4216     }
4217     else
4218     {
4219       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4220       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4221       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4222       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4223       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4224       isFound = true;
4225     }
4226   }
4227
4228   return p;
4229 }
4230
4231 //================================================================================
4232 /*!
4233  * \brief Find 2 neighbor nodes of a node on EDGE
4234  */
4235 //================================================================================
4236
4237 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4238                                         const SMDS_MeshNode*& n1,
4239                                         const SMDS_MeshNode*& n2,
4240                                         _EdgesOnShape&        eos,
4241                                         _SolidData&           data)
4242 {
4243   const SMDS_MeshNode* node = edge->_nodes[0];
4244   const int        shapeInd = eos._shapeID;
4245   SMESHDS_SubMesh*   edgeSM = 0;
4246   if ( eos.ShapeType() == TopAbs_EDGE )
4247   {
4248     edgeSM = eos._subMesh->GetSubMeshDS();
4249     if ( !edgeSM || edgeSM->NbElements() == 0 )
4250       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4251   }
4252   int iN = 0;
4253   n2 = 0;
4254   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4255   while ( eIt->more() && !n2 )
4256   {
4257     const SMDS_MeshElement* e = eIt->next();
4258     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4259     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4260     if ( edgeSM )
4261     {
4262       if (!edgeSM->Contains(e)) continue;
4263     }
4264     else
4265     {
4266       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4267       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4268     }
4269     ( iN++ ? n2 : n1 ) = nNeibor;
4270   }
4271   if ( !n2 )
4272     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4273   return true;
4274 }
4275
4276 //================================================================================
4277 /*!
4278  * \brief Create _Curvature
4279  */
4280 //================================================================================
4281
4282 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4283 {
4284   // double   _r; // radius
4285   // double   _k; // factor to correct node smoothed position
4286   // double   _h2lenRatio; // avgNormProj / (2*avgDist)
4287   // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4288
4289   _Curvature* c = 0;
4290   if ( fabs( avgNormProj / avgDist ) > 1./200 )
4291   {
4292     c = _Factory::NewCurvature();
4293     c->_r = avgDist * avgDist / avgNormProj;
4294     c->_k = avgDist * avgDist / c->_r / c->_r;
4295     //c->_k = avgNormProj / c->_r;
4296     c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4297     c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4298
4299     c->_uv.SetCoord( 0., 0. );
4300   }
4301   return c;
4302 }
4303
4304 //================================================================================
4305 /*!
4306  * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4307  */
4308 //================================================================================
4309
4310 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4311                                      const SMDS_MeshNode* n2,
4312                                      const _EdgesOnShape& eos,
4313                                      SMESH_MesherHelper&  helper)
4314 {
4315   if ( eos.ShapeType() != TopAbs_EDGE )
4316     return;
4317   if ( _curvature && Is( SMOOTHED_C1 ))
4318     return;
4319
4320   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4321   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4322   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4323
4324   // Set _curvature
4325
4326   double      sumLen = vec1.Modulus() + vec2.Modulus();
4327   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4328   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4329   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4330   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4331   _curvature = _Curvature::New( avgNormProj, avgLen );
4332   // if ( _curvature )
4333   //   debugMsg( _nodes[0]->GetID()
4334   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4335   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4336   //             << _curvature->lenDelta(0) );
4337
4338   // Set _plnNorm
4339
4340   if ( eos._sWOL.IsNull() )
4341   {
4342     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4343     // if ( SMESH_Algo::isDegenerated( E ))
4344     //   return;
4345     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4346     gp_XYZ plnNorm = dirE ^ _normal;
4347     double proj0   = plnNorm * vec1;
4348     double proj1   = plnNorm * vec2;
4349     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4350     {
4351       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4352       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4353     }
4354   }
4355 }
4356
4357 //================================================================================
4358 /*!
4359  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4360  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4361  */
4362 //================================================================================
4363
4364 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4365                          _EdgesOnShape&      eos,
4366                          SMESH_MesherHelper& helper )
4367 {
4368   _nodes     = other._nodes;
4369   _normal    = other._normal;
4370   _len       = 0;
4371   _lenFactor = other._lenFactor;
4372   _cosin     = other._cosin;
4373   _2neibors  = other._2neibors;
4374   _curvature = other._curvature;
4375   _2neibors  = other._2neibors;
4376   _maxLen    = Precision::Infinite();//other._maxLen;
4377   _flags     = 0;
4378   _smooFunction = 0;
4379
4380   gp_XYZ lastPos( 0,0,0 );
4381   if ( eos.SWOLType() == TopAbs_EDGE )
4382   {
4383     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4384     _pos.push_back( gp_XYZ( u, 0, 0));
4385
4386     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4387     lastPos.SetX( u );
4388   }
4389   else // TopAbs_FACE
4390   {
4391     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4392     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4393
4394     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4395     lastPos.SetX( uv.X() );
4396     lastPos.SetY( uv.Y() );
4397   }
4398   return lastPos;
4399 }
4400
4401 //================================================================================
4402 /*!
4403  * \brief Set _cosin and _lenFactor
4404  */
4405 //================================================================================
4406
4407 void _LayerEdge::SetCosin( double cosin )
4408 {
4409   _cosin = cosin;
4410   cosin = Abs( _cosin );
4411   //_lenFactor = ( cosin < 1.-1e-12 ) ?  Min( 2., 1./sqrt(1-cosin*cosin )) : 1.0;
4412   _lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4413 }
4414
4415 //================================================================================
4416 /*!
4417  * \brief Check if another _LayerEdge is a neighbor on EDGE
4418  */
4419 //================================================================================
4420
4421 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4422 {
4423   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4424           ( edge->_2neibors && edge->_2neibors->include( this )));
4425 }
4426
4427 //================================================================================
4428 /*!
4429  * \brief Fills a vector<_Simplex > 
4430  */
4431 //================================================================================
4432
4433 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4434                              vector<_Simplex>&    simplices,
4435                              const set<TGeomID>&  ingnoreShapes,
4436                              const _SolidData*    dataToCheckOri,
4437                              const bool           toSort)
4438 {
4439   simplices.clear();
4440   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4441   while ( fIt->more() )
4442   {
4443     const SMDS_MeshElement* f = fIt->next();
4444     const TGeomID    shapeInd = f->getshapeId();
4445     if ( ingnoreShapes.count( shapeInd )) continue;
4446     const int nbNodes = f->NbCornerNodes();
4447     const int  srcInd = f->GetNodeIndex( node );
4448     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4449     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4450     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4451     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4452       std::swap( nPrev, nNext );
4453     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4454   }
4455
4456   if ( toSort )
4457     SortSimplices( simplices );
4458 }
4459
4460 //================================================================================
4461 /*!
4462  * \brief Set neighbor simplices side by side
4463  */
4464 //================================================================================
4465
4466 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4467 {
4468   vector<_Simplex> sortedSimplices( simplices.size() );
4469   sortedSimplices[0] = simplices[0];
4470   size_t nbFound = 0;
4471   for ( size_t i = 1; i < simplices.size(); ++i )
4472   {
4473     for ( size_t j = 1; j < simplices.size(); ++j )
4474       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4475       {
4476         sortedSimplices[i] = simplices[j];
4477         nbFound++;
4478         break;
4479       }
4480   }
4481   if ( nbFound == simplices.size() - 1 )
4482     simplices.swap( sortedSimplices );
4483 }
4484
4485 //================================================================================
4486 /*!
4487  * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4488  */
4489 //================================================================================
4490
4491 void _ViscousBuilder::makeGroupOfLE()
4492 {
4493 #ifdef _DEBUG_
4494   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4495   {
4496     if ( _sdVec[i]._n2eMap.empty() ) continue;
4497
4498     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4499     TNode2Edge::iterator n2e;
4500     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4501     {
4502       _LayerEdge* le = n2e->second;
4503       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4504       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4505       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4506       if ( le ) {
4507         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4508                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4509       }
4510     }
4511     dumpFunctionEnd();
4512
4513     dumpFunction( SMESH_Comment("makeNormals") << i );
4514     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4515     {
4516       _LayerEdge* edge = n2e->second;
4517       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4518       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4519       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4520               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4521     }
4522     dumpFunctionEnd();
4523
4524     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4525     dumpCmd( "faceId1 = mesh.NbElements()" );
4526     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4527     for ( ; fExp.More(); fExp.Next() )
4528     {
4529       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4530       {
4531         if ( sm->NbElements() == 0 ) continue;
4532         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4533         while ( fIt->more())
4534         {
4535           const SMDS_MeshElement* e = fIt->next();
4536           SMESH_Comment cmd("mesh.AddFace([");
4537           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4538             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4539           dumpCmd( cmd );
4540         }
4541       }
4542     }
4543     dumpCmd( "faceId2 = mesh.NbElements()" );
4544     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4545              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4546              << "'%s-%s' % (faceId1+1, faceId2))");
4547     dumpFunctionEnd();
4548   }
4549 #endif
4550 }
4551
4552 //================================================================================
4553 /*!
4554  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4555  */
4556 //================================================================================
4557
4558 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4559 {
4560   data._geomSize = Precision::Infinite();
4561   double intersecDist;
4562   const SMDS_MeshElement* face;
4563   SMESH_MesherHelper helper( *_mesh );
4564
4565   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4566     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4567                                            data._proxyMesh->GetFaces( data._solid )));
4568
4569   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4570   {
4571     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4572     if ( eos._edges.empty() )
4573       continue;
4574     // get neighbor faces, intersection with which should not be considered since
4575     // collisions are avoided by means of smoothing
4576     set< TGeomID > neighborFaces;
4577     if ( eos._hyp.ToSmooth() )
4578     {
4579       SMESH_subMeshIteratorPtr subIt =
4580         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4581       while ( subIt->more() )
4582       {
4583         SMESH_subMesh* sm = subIt->next();
4584         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4585         while ( const TopoDS_Shape* face = fIt->next() )
4586           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4587       }
4588     }
4589     // find intersections
4590     double thinkness = eos._hyp.GetTotalThickness();
4591     for ( size_t i = 0; i < eos._edges.size(); ++i )
4592     {
4593       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
4594       eos._edges[i]->SetMaxLen( thinkness );
4595       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4596       if ( intersecDist > 0 && face )
4597       {
4598         data._geomSize = Min( data._geomSize, intersecDist );
4599         if ( !neighborFaces.count( face->getshapeId() ))
4600           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4601       }
4602     }
4603   }
4604
4605   data._maxThickness = 0;
4606   data._minThickness = 1e100;
4607   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4608   for ( ; hyp != data._hyps.end(); ++hyp )
4609   {
4610     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4611     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4612   }
4613
4614   // Limit inflation step size by geometry size found by intersecting
4615   // normals of _LayerEdge's with mesh faces
4616   if ( data._stepSize > 0.3 * data._geomSize )
4617     limitStepSize( data, 0.3 * data._geomSize );
4618
4619   if ( data._stepSize > data._minThickness )
4620     limitStepSize( data, data._minThickness );
4621
4622
4623   // -------------------------------------------------------------------------
4624   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4625   // so no need in detecting intersection at each inflation step
4626   // -------------------------------------------------------------------------
4627
4628   int nbSteps = data._maxThickness / data._stepSize;
4629   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4630     return;
4631
4632   vector< const SMDS_MeshElement* > closeFaces;
4633   int nbDetected = 0;
4634
4635   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4636   {
4637     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4638     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4639       continue;
4640
4641     for ( size_t i = 0; i < eos.size(); ++i )
4642     {
4643       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4644       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4645       closeFaces.clear();
4646       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4647
4648       bool toIgnore = true;
4649       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4650         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4651                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4652         {
4653           // check if a _LayerEdge will inflate in a direction opposite to a direction
4654           // toward a close face
4655           bool allBehind = true;
4656           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4657           {
4658             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4659             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4660           }
4661           toIgnore = allBehind;
4662         }
4663
4664
4665       if ( toIgnore ) // no need to detect intersection
4666       {
4667         eos[i]->Set( _LayerEdge::INTERSECTED );
4668         ++nbDetected;
4669       }
4670     }
4671   }
4672
4673   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4674
4675   return;
4676 }
4677
4678 //================================================================================
4679 /*!
4680  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4681  */
4682 //================================================================================
4683
4684 bool _ViscousBuilder::inflate(_SolidData& data)
4685 {
4686   SMESH_MesherHelper helper( *_mesh );
4687
4688   const double tgtThick = data._maxThickness;
4689
4690   if ( data._stepSize < 1. )
4691     data._epsilon = data._stepSize * 1e-7;
4692
4693   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4694   _pyDump->Pause();
4695
4696   findCollisionEdges( data, helper );
4697
4698   limitMaxLenByCurvature( data, helper );
4699
4700   _pyDump->Resume();
4701
4702   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4703   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4704     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4705          data._edgesOnShape[i]._edges.size() > 0 &&
4706          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4707     {
4708       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4709       data._edgesOnShape[i]._edges[0]->Block( data );
4710     }
4711
4712   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4713
4714   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4715   int nbSteps = 0, nbRepeats = 0;
4716   while ( avgThick < 0.99 )
4717   {
4718     // new target length
4719     double prevThick = curThick;
4720     curThick += data._stepSize;
4721     if ( curThick > tgtThick )
4722     {
4723       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4724       nbRepeats++;
4725     }
4726
4727     double stepSize = curThick - prevThick;
4728     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4729
4730     // Elongate _LayerEdge's
4731     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4732     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4733     {
4734       _EdgesOnShape& eos = data._edgesOnShape[iS];
4735       if ( eos._edges.empty() ) continue;
4736
4737       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4738       for ( size_t i = 0; i < eos._edges.size(); ++i )
4739       {
4740         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4741       }
4742     }
4743     dumpFunctionEnd();
4744
4745     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4746       return false;
4747
4748     // Improve and check quality
4749     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4750     {
4751       if ( nbSteps > 0 )
4752       {
4753 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4754         debugMsg("NOT INVALIDATED STEP!");
4755         return error("Smoothing failed", data._index);
4756 #endif
4757         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4758         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4759         {
4760           _EdgesOnShape& eos = data._edgesOnShape[iS];
4761           for ( size_t i = 0; i < eos._edges.size(); ++i )
4762             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4763         }
4764         dumpFunctionEnd();
4765       }
4766       break; // no more inflating possible
4767     }
4768     nbSteps++;
4769
4770     // Evaluate achieved thickness
4771     avgThick = 0;
4772     int nbActiveEdges = 0;
4773     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4774     {
4775       _EdgesOnShape& eos = data._edgesOnShape[iS];
4776       if ( eos._edges.empty() ) continue;
4777
4778       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4779       for ( size_t i = 0; i < eos._edges.size(); ++i )
4780       {
4781         if ( eos._edges[i]->_nodes.size() > 1 )
4782           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4783         else
4784           avgThick    += shapeTgtThick;
4785         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4786       }
4787     }
4788     avgThick /= data._n2eMap.size();
4789     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4790
4791 #ifdef BLOCK_INFLATION
4792     if ( nbActiveEdges == 0 )
4793     {
4794       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4795       break;
4796     }
4797 #else
4798     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4799     {
4800       debugMsg( "-- Stop inflation since "
4801                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4802                 << tgtThick * avgThick << " ) * " << safeFactor );
4803       break;
4804     }
4805 #endif
4806
4807     // new step size
4808     limitStepSize( data, 0.25 * distToIntersection );
4809     if ( data._stepSizeNodes[0] )
4810       data._stepSize = data._stepSizeCoeff *
4811         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4812
4813   } // while ( avgThick < 0.99 )
4814
4815   if ( nbSteps == 0 )
4816     return error("failed at the very first inflation step", data._index);
4817
4818   if ( avgThick < 0.99 )
4819   {
4820     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4821     {
4822       data._proxyMesh->_warning.reset
4823         ( new SMESH_ComputeError (COMPERR_WARNING,
4824                                   SMESH_Comment("Thickness ") << tgtThick <<
4825                                   " of viscous layers not reached,"
4826                                   " average reached thickness is " << avgThick*tgtThick));
4827     }
4828   }
4829
4830   // Restore position of src nodes moved by inflation on _noShrinkShapes
4831   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4832   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4833   {
4834     _EdgesOnShape& eos = data._edgesOnShape[iS];
4835     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4836       for ( size_t i = 0; i < eos._edges.size(); ++i )
4837       {
4838         restoreNoShrink( *eos._edges[ i ] );
4839       }
4840   }
4841   dumpFunctionEnd();
4842
4843   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4844 }
4845
4846 //================================================================================
4847 /*!
4848  * \brief Improve quality of layer inner surface and check intersection
4849  */
4850 //================================================================================
4851
4852 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
4853                                      const int   infStep,
4854                                      double &    distToIntersection)
4855 {
4856   if ( data._nbShapesToSmooth == 0 )
4857     return true; // no shapes needing smoothing
4858
4859   bool moved, improved;
4860   double vol;
4861   vector< _LayerEdge* >    movedEdges, badEdges;
4862   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
4863   vector< bool >           isConcaveFace;
4864
4865   SMESH_MesherHelper helper(*_mesh);
4866   Handle(ShapeAnalysis_Surface) surface;
4867   TopoDS_Face F;
4868
4869   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
4870   {
4871     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
4872
4873     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4874     {
4875       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4876       if ( !eos._toSmooth ||
4877            eos.ShapeType() != shapeType ||
4878            eos._edges.empty() )
4879         continue;
4880
4881       // already smoothed?
4882       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
4883       // if ( !toSmooth ) continue;
4884
4885       if ( !eos._hyp.ToSmooth() )
4886       {
4887         // smooth disabled by the user; check validy only
4888         if ( !isFace ) continue;
4889         badEdges.clear();
4890         for ( size_t i = 0; i < eos._edges.size(); ++i )
4891         {
4892           _LayerEdge* edge = eos._edges[i];
4893           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
4894             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
4895             {
4896               // debugMsg( "-- Stop inflation. Bad simplex ("
4897               //           << " "<< edge->_nodes[0]->GetID()
4898               //           << " "<< edge->_nodes.back()->GetID()
4899               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
4900               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
4901               // return false;
4902               badEdges.push_back( edge );
4903             }
4904         }
4905         if ( !badEdges.empty() )
4906         {
4907           eosC1.resize(1);
4908           eosC1[0] = &eos;
4909           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
4910           if ( nbBad > 0 )
4911             return false;
4912         }
4913         continue; // goto the next EDGE or FACE
4914       }
4915
4916       // prepare data
4917       if ( eos.SWOLType() == TopAbs_FACE )
4918       {
4919         if ( !F.IsSame( eos._sWOL )) {
4920           F = TopoDS::Face( eos._sWOL );
4921           helper.SetSubShape( F );
4922           surface = helper.GetSurface( F );
4923         }
4924       }
4925       else
4926       {
4927         F.Nullify(); surface.Nullify();
4928       }
4929       const TGeomID sInd = eos._shapeID;
4930
4931       // perform smoothing
4932
4933       if ( eos.ShapeType() == TopAbs_EDGE )
4934       {
4935         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
4936
4937         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
4938         {
4939           // smooth on EDGE's (normally we should not get here)
4940           int step = 0;
4941           do {
4942             moved = false;
4943             for ( size_t i = 0; i < eos._edges.size(); ++i )
4944             {
4945               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
4946             }
4947             dumpCmd( SMESH_Comment("# end step ")<<step);
4948           }
4949           while ( moved && step++ < 5 );
4950         }
4951         dumpFunctionEnd();
4952       }
4953
4954       else // smooth on FACE
4955       {
4956         eosC1.clear();
4957         eosC1.push_back( & eos );
4958         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
4959
4960         movedEdges.clear();
4961         isConcaveFace.resize( eosC1.size() );
4962         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4963         {
4964           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
4965           vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4966           for ( size_t i = 0; i < edges.size(); ++i )
4967             if ( edges[i]->Is( _LayerEdge::MOVED ) ||
4968                  edges[i]->Is( _LayerEdge::NEAR_BOUNDARY ))
4969               movedEdges.push_back( edges[i] );
4970
4971           makeOffsetSurface( *eosC1[ iEOS ], helper );
4972         }
4973
4974         int step = 0, stepLimit = 5, nbBad = 0;
4975         while (( ++step <= stepLimit ) || improved )
4976         {
4977           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
4978                        <<"_InfStep"<<infStep<<"_"<<step); // debug
4979           int oldBadNb = nbBad;
4980           badEdges.clear();
4981
4982 #ifdef INCREMENTAL_SMOOTH
4983           bool findBest = false; // ( step == stepLimit );
4984           for ( size_t i = 0; i < movedEdges.size(); ++i )
4985           {
4986             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
4987             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
4988               badEdges.push_back( movedEdges[i] );
4989           }
4990 #else
4991           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
4992           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
4993           {
4994             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
4995             for ( size_t i = 0; i < edges.size(); ++i )
4996             {
4997               edges[i]->Unset( _LayerEdge::SMOOTHED );
4998               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
4999                 badEdges.push_back( eos._edges[i] );
5000             }
5001           }
5002 #endif
5003           nbBad = badEdges.size();
5004
5005           if ( nbBad > 0 )
5006             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5007
5008           if ( !badEdges.empty() && step >= stepLimit / 2 )
5009           {
5010             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
5011               stepLimit = 9;
5012
5013             // resolve hard smoothing situation around concave VERTEXes
5014             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5015             {
5016               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5017               for ( size_t i = 0; i < eosCoVe.size(); ++i )
5018                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5019                                                          step, badEdges );
5020             }
5021             // look for the best smooth of _LayerEdge's neighboring badEdges
5022             nbBad = 0;
5023             for ( size_t i = 0; i < badEdges.size(); ++i )
5024             {
5025               _LayerEdge* ledge = badEdges[i];
5026               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5027               {
5028                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5029                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5030               }
5031               ledge->Unset( _LayerEdge::SMOOTHED );
5032               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5033             }
5034             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5035           }
5036
5037           if ( nbBad == oldBadNb  &&
5038                nbBad > 0 &&
5039                step < stepLimit ) // smooth w/o check of validity
5040           {
5041             dumpFunctionEnd();
5042             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5043                          <<"_InfStep"<<infStep<<"_"<<step); // debug
5044             for ( size_t i = 0; i < movedEdges.size(); ++i )
5045             {
5046               movedEdges[i]->SmoothWoCheck();
5047             }
5048             if ( stepLimit < 9 )
5049               stepLimit++;
5050           }
5051
5052           improved = ( nbBad < oldBadNb );
5053
5054           dumpFunctionEnd();
5055
5056           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5057             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5058             {
5059               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5060             }
5061
5062         } // smoothing steps
5063
5064         // project -- to prevent intersections or fix bad simplices
5065         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5066         {
5067           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5068             putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1 );
5069         }
5070
5071         //if ( !badEdges.empty() )
5072         {
5073           badEdges.clear();
5074           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5075           {
5076             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5077             {
5078               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5079
5080               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5081               edge->CheckNeiborsOnBoundary( & badEdges );
5082               if (( nbBad > 0 ) ||
5083                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5084               {
5085                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5086                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
5087                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5088                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5089                   {
5090                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5091                              << " "<< tgtXYZ._node->GetID()
5092                              << " "<< edge->_simplices[j]._nPrev->GetID()
5093                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5094                     badEdges.push_back( edge );
5095                     break;
5096                   }
5097               }
5098             }
5099           }
5100
5101           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5102           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5103
5104           if ( nbBad > 0 )
5105             return false;
5106         }
5107
5108       } // // smooth on FACE's
5109     } // loop on shapes
5110   } // smooth on [ EDGEs, FACEs ]
5111
5112   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5113   eosC1.resize(1);
5114   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5115   {
5116     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5117     if ( eos.ShapeType() == TopAbs_FACE ||
5118          eos._edges.empty() ||
5119          !eos._sWOL.IsNull() )
5120       continue;
5121
5122     badEdges.clear();
5123     for ( size_t i = 0; i < eos._edges.size(); ++i )
5124     {
5125       _LayerEdge*      edge = eos._edges[i];
5126       if ( edge->_nodes.size() < 2 ) continue;
5127       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5128       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5129       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
5130       //const gp_XYZ& prevXYZ = edge->PrevPos();
5131       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5132         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5133         {
5134           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5135                    << " "<< tgtXYZ._node->GetID()
5136                    << " "<< edge->_simplices[j]._nPrev->GetID()
5137                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5138           badEdges.push_back( edge );
5139           break;
5140         }
5141     }
5142
5143     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5144     eosC1[0] = &eos;
5145     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5146     if ( nbBad > 0 )
5147       return false;
5148   }
5149
5150
5151   // Check if the last segments of _LayerEdge intersects 2D elements;
5152   // checked elements are either temporary faces or faces on surfaces w/o the layers
5153
5154   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5155     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5156                                            data._proxyMesh->GetFaces( data._solid )) );
5157
5158 #ifdef BLOCK_INFLATION
5159   const bool toBlockInfaltion = true;
5160 #else
5161   const bool toBlockInfaltion = false;
5162 #endif
5163   distToIntersection = Precision::Infinite();
5164   double dist;
5165   const SMDS_MeshElement* intFace = 0;
5166   const SMDS_MeshElement* closestFace = 0;
5167   _LayerEdge* le = 0;
5168   bool is1stBlocked = true; // dbg
5169   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5170   {
5171     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5172     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5173       continue;
5174     for ( size_t i = 0; i < eos._edges.size(); ++i )
5175     {
5176       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5177            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5178         continue;
5179       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5180       {
5181         return false;
5182         // commented due to "Illegal hash-positionPosition" error in NETGEN
5183         // on Debian60 on viscous_layers_01/B2 case
5184         // Collision; try to deflate _LayerEdge's causing it
5185         // badEdges.clear();
5186         // badEdges.push_back( eos._edges[i] );
5187         // eosC1[0] = & eos;
5188         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5189         // if ( nbBad > 0 )
5190         //   return false;
5191
5192         // badEdges.clear();
5193         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5194         // {
5195         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5196         //   {
5197         //     const SMDS_MeshElement* srcFace =
5198         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5199         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5200         //     while ( nIt->more() )
5201         //     {
5202         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5203         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5204         //       if ( n2e != data._n2eMap.end() )
5205         //         badEdges.push_back( n2e->second );
5206         //     }
5207         //     eosC1[0] = eof;
5208         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5209         //     if ( nbBad > 0 )
5210         //       return false;
5211         //   }
5212         // }
5213         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5214         //   return false;
5215         // else
5216         //   continue;
5217       }
5218       if ( !intFace )
5219       {
5220         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5221         debugMsg( msg );
5222         continue;
5223       }
5224
5225       const bool isShorterDist = ( distToIntersection > dist );
5226       if ( toBlockInfaltion || isShorterDist )
5227       {
5228         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5229         // lying on this _ConvexFace
5230         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5231           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5232             continue;
5233
5234         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5235         // ( avoid limiting the thickness on the case of issue 22576)
5236         if ( intFace->getshapeId() == eos._shapeID  )
5237           continue;
5238
5239         // ignore intersection with intFace of an adjacent FACE
5240         if ( dist > 0.1 * eos._edges[i]->_len )
5241         {
5242           bool toIgnore = false;
5243           if (  eos._toSmooth )
5244           {
5245             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5246             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5247             {
5248               TopExp_Explorer sub( eos._shape,
5249                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5250               for ( ; !toIgnore && sub.More(); sub.Next() )
5251                 // is adjacent - has a common EDGE or VERTEX
5252                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5253
5254               if ( toIgnore ) // check angle between normals
5255               {
5256                 gp_XYZ normal;
5257                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5258                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5259               }
5260             }
5261           }
5262           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5263           {
5264             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5265             {
5266               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5267               toIgnore = ( nInd >= 0 );
5268             }
5269           }
5270           if ( toIgnore )
5271             continue;
5272         }
5273
5274         // intersection not ignored
5275
5276         if ( toBlockInfaltion &&
5277              dist < ( eos._edges[i]->_len * theThickToIntersection ))
5278         {
5279           if ( is1stBlocked ) { is1stBlocked = false; // debug
5280             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5281           }
5282           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5283           eos._edges[i]->Block( data );                  // not to inflate
5284
5285           //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5286           {
5287             // block _LayerEdge's, on top of which intFace is
5288             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5289             {
5290               const SMDS_MeshElement* srcFace = f->_srcFace;
5291               SMDS_ElemIteratorPtr        nIt = srcFace->nodesIterator();
5292               while ( nIt->more() )
5293               {
5294                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5295                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5296                 if ( n2e != data._n2eMap.end() )
5297                   n2e->second->Block( data );
5298               }
5299             }
5300           }
5301         }
5302
5303         if ( isShorterDist )
5304         {
5305           distToIntersection = dist;
5306           le = eos._edges[i];
5307           closestFace = intFace;
5308         }
5309
5310       } // if ( toBlockInfaltion || isShorterDist )
5311     } // loop on eos._edges
5312   } // loop on data._edgesOnShape
5313
5314   if ( !is1stBlocked )
5315   {
5316     dumpFunctionEnd();
5317   }
5318
5319   if ( closestFace && le )
5320   {
5321 #ifdef __myDEBUG
5322     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5323     cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5324          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5325          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5326          << ") distance = " << distToIntersection<< endl;
5327 #endif
5328   }
5329
5330   return true;
5331 }
5332
5333 //================================================================================
5334 /*!
5335  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5336  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5337  *  \return int - resulting nb of bad _LayerEdge's
5338  */
5339 //================================================================================
5340
5341 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5342                                           SMESH_MesherHelper&       helper,
5343                                           vector< _LayerEdge* >&    badSmooEdges,
5344                                           vector< _EdgesOnShape* >& eosC1,
5345                                           const int                 infStep )
5346 {
5347   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5348
5349   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5350
5351   enum {
5352     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5353     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5354     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5355   };
5356   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5357
5358   double vol;
5359   bool haveInvalidated = true;
5360   while ( haveInvalidated )
5361   {
5362     haveInvalidated = false;
5363     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5364     {
5365       _LayerEdge*   edge = badSmooEdges[i];
5366       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5367       edge->Set( ADDED );
5368       bool invalidated = false;
5369       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5370       {
5371         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5372         edge->Block( data );
5373         edge->Set( INVALIDATED );
5374         edge->Unset( TO_INVALIDATE );
5375         invalidated = true;
5376         haveInvalidated = true;
5377       }
5378
5379       // look for _LayerEdge's of bad _simplices
5380       int nbBad = 0;
5381       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5382       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5383       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5384       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5385       {
5386         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5387             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5388           continue;
5389
5390         bool isBad = true;
5391         _LayerEdge* ee[2] = { 0,0 };
5392         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5393           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5394             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5395
5396         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5397         while ( maxNbSteps > edge->NbSteps() && isBad )
5398         {
5399           --maxNbSteps;
5400           for ( int iE = 0; iE < 2; ++iE )
5401           {
5402             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5403                  ee[ iE ]->NbSteps() > 1 )
5404             {
5405               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5406               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5407               ee[ iE ]->Block( data );
5408               ee[ iE ]->Set( INVALIDATED );
5409               haveInvalidated = true;
5410             }
5411           }
5412           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5413               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5414             isBad = false;
5415         }
5416         nbBad += isBad;
5417         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5418         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5419         ee[0]->Set( ADDED );
5420         ee[1]->Set( ADDED );
5421         if ( isBad )
5422         {
5423           ee[0]->Set( TO_INVALIDATE );
5424           ee[1]->Set( TO_INVALIDATE );
5425         }
5426       }
5427
5428       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5429       {
5430         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5431         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5432         edge->Block( data );
5433         edge->Set( INVALIDATED );
5434         edge->Unset( TO_INVALIDATE );
5435         haveInvalidated = true;
5436       }
5437     } // loop on badSmooEdges
5438   } // while ( haveInvalidated )
5439
5440   // re-smooth on analytical EDGEs
5441   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5442   {
5443     _LayerEdge* edge = badSmooEdges[i];
5444     if ( !edge->Is( INVALIDATED )) continue;
5445
5446     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5447     if ( eos->ShapeType() == TopAbs_VERTEX )
5448     {
5449       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5450       while ( const TopoDS_Shape* e = eIt->next() )
5451         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5452           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5453           {
5454             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5455             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5456             //   F       = TopoDS::Face( eoe->_sWOL );
5457             //   surface = helper.GetSurface( F );
5458             // }
5459             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5460             eoe->_edgeSmoother->_anaCurve.Nullify();
5461           }
5462     }
5463   }
5464
5465
5466   // check result of invalidation
5467
5468   int nbBad = 0;
5469   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5470   {
5471     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5472     {
5473       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5474       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5475       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5476       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5477       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5478         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5479         {
5480           ++nbBad;
5481           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5482                    << " "<< tgtXYZ._node->GetID()
5483                    << " "<< edge->_simplices[j]._nPrev->GetID()
5484                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5485         }
5486     }
5487   }
5488   dumpFunctionEnd();
5489
5490   return nbBad;
5491 }
5492
5493 //================================================================================
5494 /*!
5495  * \brief Create an offset surface
5496  */
5497 //================================================================================
5498
5499 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5500 {
5501   if ( eos._offsetSurf.IsNull() ||
5502        eos._edgeForOffset == 0 ||
5503        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5504     return;
5505
5506   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5507
5508   // find offset
5509   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5510   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5511   double offset = baseSurface->Gap();
5512
5513   eos._offsetSurf.Nullify();
5514
5515   try
5516   {
5517     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5518     offsetMaker.PerformByJoin( eos._shape, -offset, Precision::Confusion() );
5519     if ( !offsetMaker.IsDone() ) return;
5520
5521     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5522     if ( !fExp.More() ) return;
5523
5524     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5525     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5526     if ( surf.IsNull() ) return;
5527
5528     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5529   }
5530   catch ( Standard_Failure& )
5531   {
5532   }
5533 }
5534
5535 //================================================================================
5536 /*!
5537  * \brief Put nodes of a curved FACE to its offset surface
5538  */
5539 //================================================================================
5540
5541 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5542                                           int                       infStep,
5543                                           vector< _EdgesOnShape* >& eosC1,
5544                                           int                       smooStep,
5545                                           int                       moveAll )
5546 {
5547   _EdgesOnShape * eof = & eos;
5548   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5549   {
5550     eof = 0;
5551     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5552     {
5553       if ( eosC1[i]->_offsetSurf.IsNull() ||
5554            eosC1[i]->ShapeType() != TopAbs_FACE ||
5555            eosC1[i]->_edgeForOffset == 0 ||
5556            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5557         continue;
5558       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5559         eof = eosC1[i];
5560     }
5561   }
5562   if ( !eof ||
5563        eof->_offsetSurf.IsNull() ||
5564        eof->ShapeType() != TopAbs_FACE ||
5565        eof->_edgeForOffset == 0 ||
5566        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5567     return;
5568
5569   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5570   for ( size_t i = 0; i < eos._edges.size(); ++i )
5571   {
5572     _LayerEdge* edge = eos._edges[i];
5573     edge->Unset( _LayerEdge::MARKED );
5574     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5575       continue;
5576     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5577     {
5578       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5579         continue;
5580     }
5581     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5582       continue;
5583
5584     int nbBlockedAround = 0;
5585     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5586       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5587     if ( nbBlockedAround > 1 )
5588       continue;
5589
5590     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5591     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5592     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5593     edge->_curvature->_uv = uv;
5594     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5595
5596     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5597     gp_XYZ prevP = edge->PrevCheckPos();
5598     bool      ok = true;
5599     if ( !moveAll )
5600       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5601       {
5602         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5603       }
5604     if ( ok )
5605     {
5606       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5607       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5608       edge->_pos.back() = newP;
5609
5610       edge->Set( _LayerEdge::MARKED );
5611       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5612       {
5613         edge->_normal = ( newP - prevP ).Normalized();
5614       }
5615     }
5616   }
5617
5618
5619
5620 #ifdef _DEBUG_
5621   // dumpMove() for debug
5622   size_t i = 0;
5623   for ( ; i < eos._edges.size(); ++i )
5624     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5625       break;
5626   if ( i < eos._edges.size() )
5627   {
5628     dumpFunction(SMESH_Comment("putOnOffsetSurface_S") << eos._shapeID
5629                  << "_InfStep" << infStep << "_" << smooStep );
5630     for ( ; i < eos._edges.size(); ++i )
5631     {
5632       if ( eos._edges[i]->Is( _LayerEdge::MARKED )) {
5633         dumpMove( eos._edges[i]->_nodes.back() );
5634       }
5635     }
5636     dumpFunctionEnd();
5637   }
5638 #endif
5639
5640   _ConvexFace* cnvFace;
5641   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5642        eos.ShapeType() == TopAbs_FACE &&
5643        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5644        !cnvFace->_normalsFixedOnBorders )
5645   {
5646     // put on the surface nodes built on FACE boundaries
5647     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5648     while ( smIt->more() )
5649     {
5650       SMESH_subMesh* sm = smIt->next();
5651       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5652       if ( !subEOS->_sWOL.IsNull() ) continue;
5653       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5654
5655       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5656     }
5657     cnvFace->_normalsFixedOnBorders = true;
5658   }
5659 }
5660
5661 //================================================================================
5662 /*!
5663  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5664  *        _LayerEdge's to be in a consequent order
5665  */
5666 //================================================================================
5667
5668 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5669                                                 _EdgesOnShape&      eos,
5670                                                 SMESH_MesherHelper& helper)
5671 {
5672   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5673
5674   TopLoc_Location loc; double f,l;
5675
5676   Handle(Geom_Line)   line;
5677   Handle(Geom_Circle) circle;
5678   bool isLine, isCirc;
5679   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5680   {
5681     // check if the EDGE is a line
5682     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5683     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5684       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5685
5686     line   = Handle(Geom_Line)::DownCast( curve );
5687     circle = Handle(Geom_Circle)::DownCast( curve );
5688     isLine = (!line.IsNull());
5689     isCirc = (!circle.IsNull());
5690
5691     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5692     {
5693       isLine = SMESH_Algo::IsStraight( E );
5694
5695       if ( isLine )
5696         line = new Geom_Line( gp::OX() ); // only type does matter
5697     }
5698     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5699     {
5700       // TODO
5701     }
5702   }
5703   else //////////////////////////////////////////////////////////////////////// 2D case
5704   {
5705     if ( !eos._isRegularSWOL ) // 23190
5706       return NULL;
5707
5708     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5709
5710     // check if the EDGE is a line
5711     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5712     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5713       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5714
5715     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5716     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5717     isLine = (!line2d.IsNull());
5718     isCirc = (!circle2d.IsNull());
5719
5720     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5721     {
5722       Bnd_B2d bndBox;
5723       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5724       while ( nIt->more() )
5725         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5726       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5727
5728       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5729       for ( int i = 0; i < 2 && !isLine; ++i )
5730         isLine = ( size.Coord( i+1 ) <= lineTol );
5731     }
5732     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5733     {
5734       // TODO
5735     }
5736     if ( isLine )
5737     {
5738       line = new Geom_Line( gp::OX() ); // only type does matter
5739     }
5740     else if ( isCirc )
5741     {
5742       gp_Pnt2d p = circle2d->Location();
5743       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5744       circle = new Geom_Circle( ax, 1.); // only center position does matter
5745     }
5746   }
5747
5748   if ( isLine )
5749     return line;
5750   if ( isCirc )
5751     return circle;
5752
5753   return Handle(Geom_Curve)();
5754 }
5755
5756 //================================================================================
5757 /*!
5758  * \brief Smooth edges on EDGE
5759  */
5760 //================================================================================
5761
5762 bool _Smoother1D::Perform(_SolidData&                    data,
5763                           Handle(ShapeAnalysis_Surface)& surface,
5764                           const TopoDS_Face&             F,
5765                           SMESH_MesherHelper&            helper )
5766 {
5767   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
5768     prepare( data );
5769
5770   findEdgesToSmooth();
5771   if ( isAnalytic() )
5772     return smoothAnalyticEdge( data, surface, F, helper );
5773   else
5774     return smoothComplexEdge ( data, surface, F, helper );
5775 }
5776
5777 //================================================================================
5778 /*!
5779  * \brief Find edges to smooth
5780  */
5781 //================================================================================
5782
5783 void _Smoother1D::findEdgesToSmooth()
5784 {
5785   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
5786   for ( int iEnd = 0; iEnd < 2; ++iEnd )
5787     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
5788       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
5789
5790   _eToSmooth[0].first = _eToSmooth[0].second = 0;
5791
5792   for ( size_t i = 0; i < _eos.size(); ++i )
5793   {
5794     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5795     {
5796       if ( needSmoothing( _leOnV[0]._cosin,
5797                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
5798            isToSmooth( i )
5799            )
5800         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5801       else
5802         break;
5803     }
5804     _eToSmooth[0].second = i+1;
5805   }
5806
5807   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
5808
5809   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
5810   {
5811     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
5812     {
5813       if ( needSmoothing( _leOnV[1]._cosin,
5814                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
5815            isToSmooth( i ))
5816         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
5817       else
5818         break;
5819     }
5820     _eToSmooth[1].first = i;
5821   }
5822 }
5823
5824 //================================================================================
5825 /*!
5826  * \brief Check if iE-th _LayerEdge needs smoothing
5827  */
5828 //================================================================================
5829
5830 bool _Smoother1D::isToSmooth( int iE )
5831 {
5832   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
5833   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
5834   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
5835   gp_XYZ       seg0 = pi - p0;
5836   gp_XYZ       seg1 = p1 - pi;
5837   gp_XYZ    tangent =  seg0 + seg1;
5838   double tangentLen = tangent.Modulus();
5839   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
5840   if ( tangentLen < std::numeric_limits<double>::min() )
5841     return false;
5842   tangent /= tangentLen;
5843
5844   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
5845   {
5846     _LayerEdge* ne = _eos[iE]->_neibors[i];
5847     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
5848          ne->_nodes.size() < 2 ||
5849          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
5850       continue;
5851     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
5852     double    proj = edgeVec * tangent;
5853     if ( needSmoothing( 1., proj, segMinLen ))
5854       return true;
5855   }
5856   return false;
5857 }
5858
5859 //================================================================================
5860 /*!
5861  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
5862  */
5863 //================================================================================
5864
5865 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
5866                                       Handle(ShapeAnalysis_Surface)& surface,
5867                                       const TopoDS_Face&             F,
5868                                       SMESH_MesherHelper&            helper)
5869 {
5870   if ( !isAnalytic() ) return false;
5871
5872   size_t iFrom = 0, iTo = _eos._edges.size();
5873
5874   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
5875   {
5876     if ( F.IsNull() ) // 3D
5877     {
5878       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
5879       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
5880       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
5881       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
5882       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
5883       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
5884       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
5885       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
5886       //                    vLE1->Is( _LayerEdge::BLOCKED ));
5887       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5888       {
5889         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5890         if ( iFrom >= iTo ) continue;
5891         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
5892         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
5893         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5894         double param1 = _leParams[ iTo ];
5895         for ( size_t i = iFrom; i < iTo; ++i )
5896         {
5897           _LayerEdge*       edge = _eos[i];
5898           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
5899           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5900           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
5901
5902           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
5903           // {
5904           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
5905           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
5906           //                     lineDir * ( curPos - pSrc0 ));
5907           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
5908           // }
5909           if ( edge->Is( _LayerEdge::BLOCKED ))
5910           {
5911             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
5912             double curThick = pSrc.SquareDistance( tgtNode );
5913             double newThink = ( pSrc - newPos ).SquareModulus();
5914             if ( newThink > curThick )
5915               continue;
5916           }
5917           edge->_pos.back() = newPos;
5918           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5919           dumpMove( tgtNode );
5920         }
5921       }
5922     }
5923     else // 2D
5924     {
5925       _LayerEdge* eV0 = getLEdgeOnV( 0 );
5926       _LayerEdge* eV1 = getLEdgeOnV( 1 );
5927       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
5928       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
5929       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
5930       {
5931         int iPeriodic = helper.GetPeriodicIndex();
5932         if ( iPeriodic == 1 || iPeriodic == 2 )
5933         {
5934           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
5935           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
5936             std::swap( uvV0, uvV1 );
5937         }
5938       }
5939       for ( int iEnd = 0; iEnd < 2; ++iEnd )
5940       {
5941         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
5942         if ( iFrom >= iTo ) continue;
5943         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
5944         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
5945         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
5946         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
5947         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
5948         double  param1 = _leParams[ iTo ];
5949         gp_XY  rangeUV = uv1 - uv0;
5950         for ( size_t i = iFrom; i < iTo; ++i )
5951         {
5952           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
5953           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
5954           gp_XY newUV = uv0 + param * rangeUV;
5955
5956           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
5957           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
5958           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5959           dumpMove( tgtNode );
5960
5961           SMDS_FacePositionPtr pos = tgtNode->GetPosition();
5962           pos->SetUParameter( newUV.X() );
5963           pos->SetVParameter( newUV.Y() );
5964
5965           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
5966
5967           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
5968           {
5969             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
5970             if ( _eos[i]->_pos.size() > 2 )
5971             {
5972               // modify previous positions to make _LayerEdge less sharply bent
5973               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
5974               const gp_XYZ  uvShift = newUV0 - uvVec.back();
5975               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
5976               int iPrev = uvVec.size() - 2;
5977               while ( iPrev > 0 )
5978               {
5979                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
5980                 uvVec[ iPrev ] += uvShift * r;
5981                 --iPrev;
5982               }
5983             }
5984           }
5985           _eos[i]->_pos.back() = newUV0;
5986         }
5987       }
5988     }
5989     return true;
5990   }
5991
5992   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
5993   {
5994     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
5995     gp_Pnt center3D = circle->Location();
5996
5997     if ( F.IsNull() ) // 3D
5998     {
5999       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
6000         return true; // closed EDGE - nothing to do
6001
6002       // circle is a real curve of EDGE
6003       gp_Circ circ = circle->Circ();
6004
6005       // new center is shifted along its axis
6006       const gp_Dir& axis = circ.Axis().Direction();
6007       _LayerEdge*     e0 = getLEdgeOnV(0);
6008       _LayerEdge*     e1 = getLEdgeOnV(1);
6009       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
6010       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
6011       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
6012       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
6013       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
6014
6015       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
6016
6017       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6018       gp_Circ newCirc( newAxis, newRadius );
6019       gp_Vec  vecC1  ( newCenter, p1 );
6020
6021       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6022       if ( uLast < 0 )
6023         uLast += 2 * M_PI;
6024       
6025       for ( size_t i = 0; i < _eos.size(); ++i )
6026       {
6027         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6028         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6029         double u = uLast * _leParams[i];
6030         gp_Pnt p = ElCLib::Value( u, newCirc );
6031         _eos._edges[i]->_pos.back() = p.XYZ();
6032
6033         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6034         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6035         dumpMove( tgtNode );
6036       }
6037       return true;
6038     }
6039     else // 2D
6040     {
6041       const gp_XY center( center3D.X(), center3D.Y() );
6042
6043       _LayerEdge* e0 = getLEdgeOnV(0);
6044       _LayerEdge* eM = _eos._edges[ 0 ];
6045       _LayerEdge* e1 = getLEdgeOnV(1);
6046       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6047       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6048       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6049       gp_Vec2d vec0( center, uv0 );
6050       gp_Vec2d vecM( center, uvM );
6051       gp_Vec2d vec1( center, uv1 );
6052       double uLast = vec0.Angle( vec1 ); // -PI - +PI
6053       double uMidl = vec0.Angle( vecM );
6054       if ( uLast * uMidl <= 0. )
6055         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6056       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6057
6058       gp_Ax2d   axis( center, vec0 );
6059       gp_Circ2d circ( axis, radius );
6060       for ( size_t i = 0; i < _eos.size(); ++i )
6061       {
6062         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6063         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6064         double    newU = uLast * _leParams[i];
6065         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6066         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6067
6068         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6069         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6070         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6071         dumpMove( tgtNode );
6072
6073         SMDS_FacePositionPtr pos = tgtNode->GetPosition();
6074         pos->SetUParameter( newUV.X() );
6075         pos->SetVParameter( newUV.Y() );
6076
6077         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6078       }
6079     }
6080     return true;
6081   }
6082
6083   return false;
6084 }
6085
6086 //================================================================================
6087 /*!
6088  * \brief smooth _LayerEdge's on a an EDGE
6089  */
6090 //================================================================================
6091
6092 bool _Smoother1D::smoothComplexEdge( _SolidData&                    /*data*/,
6093                                      Handle(ShapeAnalysis_Surface)& surface,
6094                                      const TopoDS_Face&             F,
6095                                      SMESH_MesherHelper&            /*helper*/)
6096 {
6097   if ( _offPoints.empty() )
6098     return false;
6099
6100   // ----------------------------------------------
6101   // move _offPoints along normals of _LayerEdge's
6102   // ----------------------------------------------
6103
6104   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6105   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6106     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6107   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
6108     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6109   _leOnV[0]._len = e[0]->_len;
6110   _leOnV[1]._len = e[1]->_len;
6111   for ( size_t i = 0; i < _offPoints.size(); i++ )
6112   {
6113     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6114     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6115     const double w0 = _offPoints[i]._2edges._wgt[0];
6116     const double w1 = _offPoints[i]._2edges._wgt[1];
6117     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
6118     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
6119     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6120     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6121          e1->Is( _LayerEdge::NORMAL_UPDATED ))
6122       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6123
6124     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6125     _offPoints[i]._len  = avgLen;
6126   }
6127
6128   double fTol = 0;
6129   if ( !surface.IsNull() ) // project _offPoints to the FACE
6130   {
6131     fTol = 100 * BRep_Tool::Tolerance( F );
6132     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6133
6134     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6135     //if ( surface->Gap() < 0.5 * segLen )
6136       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6137
6138     for ( size_t i = 1; i < _offPoints.size(); ++i )
6139     {
6140       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6141       //if ( surface->Gap() < 0.5 * segLen )
6142         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6143     }
6144   }
6145
6146   // -----------------------------------------------------------------
6147   // project tgt nodes of extreme _LayerEdge's to the offset segments
6148   // -----------------------------------------------------------------
6149
6150   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6151   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6152   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6153
6154   gp_Pnt pExtreme[2], pProj[2];
6155   bool isProjected[2];
6156   for ( int is2nd = 0; is2nd < 2; ++is2nd )
6157   {
6158     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6159     int  i = _iSeg[ is2nd ];
6160     int di = is2nd ? -1 : +1;
6161     bool & projected = isProjected[ is2nd ];
6162     projected = false;
6163     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6164     int nbWorse = 0;
6165     do {
6166       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
6167       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6168       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
6169       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6170       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6171       if ( dist < distMin || projected )
6172       {
6173         _iSeg[ is2nd ] = i;
6174         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6175         distMin = dist;
6176       }
6177       else if ( dist > distPrev )
6178       {
6179         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6180           break;
6181       }
6182       distPrev = dist;
6183       i += di;
6184     }
6185     while ( !projected &&
6186             i >= 0 && i+1 < (int)_offPoints.size() );
6187
6188     if ( !projected )
6189     {
6190       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6191       {
6192         _iSeg[0] = 0;
6193         _iSeg[1] = _offPoints.size()-2;
6194         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6195         return false;
6196       }
6197     }
6198   }
6199   if ( _iSeg[0] > _iSeg[1] )
6200   {
6201     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6202     return false;
6203   }
6204
6205   // adjust length of extreme LE (test viscous_layers_01/B7)
6206   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6207   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6208   double d0 = vDiv0.Magnitude();
6209   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6210   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6211     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6212     else                                   e[0]->_len -= d0;
6213   }
6214   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6215     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6216     else                                   e[1]->_len -= d1;
6217   }
6218
6219   // ---------------------------------------------------------------------------------
6220   // compute normalized length of the offset segments located between the projections
6221   // ---------------------------------------------------------------------------------
6222
6223   // temporary replace extreme _offPoints by pExtreme
6224   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6225                       _offPoints[ _iSeg[1]+1 ]._xyz };
6226   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6227   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6228
6229   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6230   vector< double > len( nbSeg + 1 );
6231   len[ iSeg++ ] = 0;
6232   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6233   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6234   {
6235     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6236   }
6237   // if ( isProjected[ 1 ])
6238   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6239   // else
6240   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6241
6242   double fullLen = len.back() - d0 - d1;
6243   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6244     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6245
6246   // -------------------------------------------------------------
6247   // distribute tgt nodes of _LayerEdge's between the projections
6248   // -------------------------------------------------------------
6249
6250   iSeg = 0;
6251   for ( size_t i = 0; i < _eos.size(); ++i )
6252   {
6253     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6254     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6255     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6256       iSeg++;
6257     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6258     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6259                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6260
6261     if ( surface.IsNull() )
6262     {
6263       _eos[i]->_pos.back() = p;
6264     }
6265     else // project a new node position to a FACE
6266     {
6267       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6268       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6269
6270       p = surface->Value( uv2 ).XYZ();
6271       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6272     }
6273     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6274     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6275     dumpMove( tgtNode );
6276   }
6277
6278   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6279   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6280
6281   return true;
6282 }
6283
6284 //================================================================================
6285 /*!
6286  * \brief Prepare for smoothing
6287  */
6288 //================================================================================
6289
6290 void _Smoother1D::prepare(_SolidData& data)
6291 {
6292   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6293   _curveLen = SMESH_Algo::EdgeLength( E );
6294
6295   // sort _LayerEdge's by position on the EDGE
6296   data.SortOnEdge( E, _eos._edges );
6297
6298   // compute normalized param of _eos._edges on EDGE
6299   _leParams.resize( _eos._edges.size() + 1 );
6300   {
6301     double curLen;
6302     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6303     _leParams[0] = 0;
6304     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6305     {
6306       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6307       curLen         = p.Distance( pPrev );
6308       _leParams[i+1] = _leParams[i] + curLen;
6309       pPrev          = p;
6310     }
6311     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6312     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6313       _leParams[i] = _leParams[i+1] / fullLen;
6314     _leParams.back() = 1.;
6315   }
6316
6317   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6318
6319   // get cosin to use in findEdgesToSmooth()
6320   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6321   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6322   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6323   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6324   if ( _eos._sWOL.IsNull() ) // 3D
6325     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6326       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6327
6328   if ( isAnalytic() )
6329     return;
6330
6331   // divide E to have offset segments with low deflection
6332   BRepAdaptor_Curve c3dAdaptor( E );
6333   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2]*sin(p1p2,p1pM)
6334   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6335   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6336   if ( discret.NbPoints() <= 2 )
6337   {
6338     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6339     return;
6340   }
6341
6342   const double u0 = c3dAdaptor.FirstParameter();
6343   gp_Pnt p; gp_Vec tangent;
6344   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6345   {
6346     _offPoints.resize( discret.NbPoints() );
6347     for ( size_t i = 0; i < _offPoints.size(); i++ )
6348     {
6349       double u = discret.Parameter( i+1 );
6350       c3dAdaptor.D1( u, p, tangent );
6351       _offPoints[i]._xyz     = p.XYZ();
6352       _offPoints[i]._edgeDir = tangent.XYZ();
6353       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6354     }
6355   }
6356   else
6357   {
6358     std::vector< double > params( _eos.size() + 2 );
6359
6360     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6361     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6362     for ( size_t i = 0; i < _eos.size(); i++ )
6363       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6364
6365     if ( params[1] > params[ _eos.size() ] )
6366       std::reverse( params.begin() + 1, params.end() - 1 );
6367
6368     _offPoints.resize( _eos.size() + 2 );
6369     for ( size_t i = 0; i < _offPoints.size(); i++ )
6370     {
6371       const double u = params[i];
6372       c3dAdaptor.D1( u, p, tangent );
6373       _offPoints[i]._xyz     = p.XYZ();
6374       _offPoints[i]._edgeDir = tangent.XYZ();
6375       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6376     }
6377   }
6378
6379   // set _2edges
6380   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6381   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6382   _2NearEdges tmp2edges;
6383   tmp2edges._edges[1] = _eos._edges[0];
6384   _leOnV[0]._2neibors = & tmp2edges;
6385   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6386   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6387   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6388   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6389   {
6390     // find _LayerEdge's located before and after an offset point
6391     // (_eos._edges[ iLE ] is next after ePrev)
6392     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6393       ePrev = _eos._edges[ iLE++ ];
6394     eNext = ePrev->_2neibors->_edges[1];
6395
6396     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6397     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6398     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6399     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6400   }
6401
6402   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6403   for ( size_t i = 0; i < _offPoints.size(); i++ )
6404     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6405       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6406     else break;
6407   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6408     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6409       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6410     else break;
6411
6412   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6413
6414   int iLBO = _offPoints.size() - 2; // last but one
6415
6416   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6417     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6418   else
6419     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6420   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6421     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6422   else
6423     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6424   _leOnV[ 0 ]._len = 0;
6425   _leOnV[ 1 ]._len = 0;
6426   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6427   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6428
6429   _iSeg[0] = 0;
6430   _iSeg[1] = _offPoints.size()-2;
6431
6432   // initialize OffPnt::_len
6433   for ( size_t i = 0; i < _offPoints.size(); ++i )
6434     _offPoints[i]._len = 0;
6435
6436   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6437   {
6438     _leOnV[0]._len = leOnV[0]->_len;
6439     _leOnV[1]._len = leOnV[1]->_len;
6440     for ( size_t i = 0; i < _offPoints.size(); i++ )
6441     {
6442       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6443       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6444       const double w0 = _offPoints[i]._2edges._wgt[0];
6445       const double w1 = _offPoints[i]._2edges._wgt[1];
6446       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6447       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6448                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6449       _offPoints[i]._xyz = avgXYZ;
6450       _offPoints[i]._len = avgLen;
6451     }
6452   }
6453 }
6454
6455 //================================================================================
6456 /*!
6457  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6458  */
6459 //================================================================================
6460
6461 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6462                                      const gp_XYZ&  edgeDir)
6463 {
6464   gp_XYZ cross = normal ^ edgeDir;
6465   gp_XYZ  norm = edgeDir ^ cross;
6466   double  size = norm.Modulus();
6467
6468   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6469   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6470
6471   return norm / size;
6472 }
6473
6474 //================================================================================
6475 /*!
6476  * \brief Writes a script creating a mesh composed of _offPoints
6477  */
6478 //================================================================================
6479
6480 void _Smoother1D::offPointsToPython() const
6481 {
6482   const char* fname = "/tmp/offPoints.py";
6483   cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6484   ofstream py(fname);
6485   py << "import SMESH" << endl
6486      << "from salome.smesh import smeshBuilder" << endl
6487      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6488      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6489   for ( size_t i = 0; i < _offPoints.size(); i++ )
6490   {
6491     py << "mesh.AddNode( "
6492        << _offPoints[i]._xyz.X() << ", "
6493        << _offPoints[i]._xyz.Y() << ", "
6494        << _offPoints[i]._xyz.Z() << " )" << endl;
6495   }
6496 }
6497
6498 //================================================================================
6499 /*!
6500  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6501  */
6502 //================================================================================
6503
6504 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6505                              vector< _LayerEdge* >& edges)
6506 {
6507   map< double, _LayerEdge* > u2edge;
6508   for ( size_t i = 0; i < edges.size(); ++i )
6509     u2edge.insert( u2edge.end(),
6510                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6511
6512   ASSERT( u2edge.size() == edges.size() );
6513   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6514   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6515     edges[i] = u2e->second;
6516
6517   Sort2NeiborsOnEdge( edges );
6518 }
6519
6520 //================================================================================
6521 /*!
6522  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6523  */
6524 //================================================================================
6525
6526 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6527 {
6528   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6529
6530   for ( size_t i = 0; i < edges.size()-1; ++i )
6531     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6532       edges[i]->_2neibors->reverse();
6533
6534   const size_t iLast = edges.size() - 1;
6535   if ( edges.size() > 1 &&
6536        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6537     edges[iLast]->_2neibors->reverse();
6538 }
6539
6540 //================================================================================
6541 /*!
6542  * \brief Return _EdgesOnShape* corresponding to the shape
6543  */
6544 //================================================================================
6545
6546 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6547 {
6548   if ( shapeID < (int)_edgesOnShape.size() &&
6549        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6550     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6551
6552   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6553     if ( _edgesOnShape[i]._shapeID == shapeID )
6554       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6555
6556   return 0;
6557 }
6558
6559 //================================================================================
6560 /*!
6561  * \brief Return _EdgesOnShape* corresponding to the shape
6562  */
6563 //================================================================================
6564
6565 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6566 {
6567   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6568   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6569 }
6570
6571 //================================================================================
6572 /*!
6573  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6574  */
6575 //================================================================================
6576
6577 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6578 {
6579   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6580
6581   set< TGeomID > vertices;
6582   TopoDS_Face F;
6583   if ( eos->ShapeType() == TopAbs_FACE )
6584   {
6585     // check FACE concavity and get concave VERTEXes
6586     F = TopoDS::Face( eos->_shape );
6587     if ( isConcave( F, helper, &vertices ))
6588       _concaveFaces.insert( eos->_shapeID );
6589
6590     // set eos._eosConcaVer
6591     eos->_eosConcaVer.clear();
6592     eos->_eosConcaVer.reserve( vertices.size() );
6593     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6594     {
6595       _EdgesOnShape* eov = GetShapeEdges( *v );
6596       if ( eov && eov->_edges.size() == 1 )
6597       {
6598         eos->_eosConcaVer.push_back( eov );
6599         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6600           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6601       }
6602     }
6603
6604     // SetSmooLen() to _LayerEdge's on FACE
6605     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6606     // {
6607     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6608     // }
6609     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6610     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6611     // {
6612     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6613     //   if ( !eoe ) continue;
6614
6615     //   vector<_LayerEdge*>& eE = eoe->_edges;
6616     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6617     //   {
6618     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6619     //       continue;
6620
6621     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6622     //     while ( segIt->more() )
6623     //     {
6624     //       const SMDS_MeshElement* seg = segIt->next();
6625     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6626     //         continue;
6627     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6628     //         continue; // not to check a seg twice
6629     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6630     //       {
6631     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6632     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6633     //           continue;
6634     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6635     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6636     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6637     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6638     //       }
6639     //     }
6640     //   }
6641     // }
6642   } // if ( eos->ShapeType() == TopAbs_FACE )
6643
6644   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6645   {
6646     eos->_edges[i]->_smooFunction = 0;
6647     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6648   }
6649   bool isCurved = false;
6650   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6651   {
6652     _LayerEdge* edge = eos->_edges[i];
6653
6654     // get simplices sorted
6655     _Simplex::SortSimplices( edge->_simplices );
6656
6657     // smoothing function
6658     edge->ChooseSmooFunction( vertices, _n2eMap );
6659
6660     // set _curvature
6661     double avgNormProj = 0, avgLen = 0;
6662     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6663     {
6664       _Simplex& s = edge->_simplices[iS];
6665
6666       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6667       avgNormProj += edge->_normal * vec;
6668       avgLen      += vec.Modulus();
6669       if ( substituteSrcNodes )
6670       {
6671         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6672         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6673       }
6674     }
6675     avgNormProj /= edge->_simplices.size();
6676     avgLen      /= edge->_simplices.size();
6677     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6678     {
6679       edge->Set( _LayerEdge::SMOOTHED_C1 );
6680       isCurved = true;
6681       SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6682       if ( !fPos )
6683         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6684           fPos = edge->_simplices[iS]._nPrev->GetPosition();
6685       if ( fPos )
6686         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6687     }
6688   }
6689
6690   // prepare for putOnOffsetSurface()
6691   if (( eos->ShapeType() == TopAbs_FACE ) &&
6692       ( isCurved || !eos->_eosConcaVer.empty() ))
6693   {
6694     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6695     eos->_edgeForOffset = 0;
6696
6697     double maxCosin = -1;
6698     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6699     {
6700       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6701       if ( !eoe || eoe->_edges.empty() ) continue;
6702
6703       vector<_LayerEdge*>& eE = eoe->_edges;
6704       _LayerEdge* e = eE[ eE.size() / 2 ];
6705       if ( e->_cosin > maxCosin )
6706       {
6707         eos->_edgeForOffset = e;
6708         maxCosin = e->_cosin;
6709       }
6710     }
6711   }
6712 }
6713
6714 //================================================================================
6715 /*!
6716  * \brief Add faces for smoothing
6717  */
6718 //================================================================================
6719
6720 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
6721                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
6722 {
6723   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
6724   for ( ; eos != eosToSmooth.end(); ++eos )
6725   {
6726     if ( !*eos || (*eos)->_toSmooth ) continue;
6727
6728     (*eos)->_toSmooth = true;
6729
6730     if ( (*eos)->ShapeType() == TopAbs_FACE )
6731     {
6732       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
6733       (*eos)->_toSmooth = true;
6734     }
6735   }
6736
6737   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
6738   if ( edgesNoAnaSmooth )
6739     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
6740     {
6741       if ( (*eos)->_edgeSmoother )
6742         (*eos)->_edgeSmoother->_anaCurve.Nullify();
6743     }
6744 }
6745
6746 //================================================================================
6747 /*!
6748  * \brief Limit _LayerEdge::_maxLen according to local curvature
6749  */
6750 //================================================================================
6751
6752 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& /*helper*/ )
6753 {
6754   // find intersection of neighbor _LayerEdge's to limit _maxLen
6755   // according to local curvature (IPAL52648)
6756
6757   // This method must be called after findCollisionEdges() where _LayerEdge's
6758   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
6759
6760   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6761   {
6762     _EdgesOnShape& eosI = data._edgesOnShape[iS];
6763     if ( eosI._edges.empty() ) continue;
6764     if ( !eosI._hyp.ToSmooth() )
6765     {
6766       for ( size_t i = 0; i < eosI._edges.size(); ++i )
6767       {
6768         _LayerEdge* eI = eosI._edges[i];
6769         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
6770         {
6771           _LayerEdge* eN = eI->_neibors[iN];
6772           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
6773           {
6774             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
6775             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
6776           }
6777         }
6778       }
6779     }
6780     else if ( eosI.ShapeType() == TopAbs_EDGE )
6781     {
6782       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
6783       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
6784
6785       _LayerEdge* e0 = eosI._edges[0];
6786       for ( size_t i = 1; i < eosI._edges.size(); ++i )
6787       {
6788         _LayerEdge* eI = eosI._edges[i];
6789         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
6790         e0 = eI;
6791       }
6792     }
6793   }
6794 }
6795
6796 //================================================================================
6797 /*!
6798  * \brief Limit _LayerEdge::_maxLen according to local curvature
6799  */
6800 //================================================================================
6801
6802 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
6803                                               _LayerEdge*    e2,
6804                                               _EdgesOnShape& /*eos1*/,
6805                                               _EdgesOnShape& /*eos2*/,
6806                                               const bool     /*isSmoothable*/ )
6807 {
6808   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
6809         e2->_nodes[0]->GetPosition()->GetDim() ) &&
6810       ( e1->_cosin < 0.75 ))
6811     return; // angle > 90 deg at e1
6812
6813   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
6814   double norSize = plnNorm.SquareModulus();
6815   if ( norSize < std::numeric_limits<double>::min() )
6816     return; // parallel normals
6817
6818   // find closest points of skew _LayerEdge's
6819   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
6820   gp_XYZ dir12 = src2 - src1;
6821   gp_XYZ perp1 = e1->_normal ^ plnNorm;
6822   gp_XYZ perp2 = e2->_normal ^ plnNorm;
6823   double  dot1 = perp2 * e1->_normal;
6824   double  dot2 = perp1 * e2->_normal;
6825   double    u1 =   ( perp2 * dir12 ) / dot1;
6826   double    u2 = - ( perp1 * dir12 ) / dot2;
6827   if ( u1 > 0 && u2 > 0 )
6828   {
6829     double ovl = ( u1 * e1->_normal * dir12 -
6830                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
6831     if ( ovl > theSmoothThickToElemSizeRatio )
6832     {
6833       const double coef = 0.75;
6834       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
6835       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
6836     }
6837   }
6838 }
6839
6840 //================================================================================
6841 /*!
6842  * \brief Fill data._collisionEdges
6843  */
6844 //================================================================================
6845
6846 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
6847 {
6848   data._collisionEdges.clear();
6849
6850   // set the full thickness of the layers to LEs
6851   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6852   {
6853     _EdgesOnShape& eos = data._edgesOnShape[iS];
6854     if ( eos._edges.empty() ) continue;
6855     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
6856     if ( !eos._sWOL.IsNull() ) continue; // PAL23566
6857
6858     for ( size_t i = 0; i < eos._edges.size(); ++i )
6859     {
6860       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
6861       double maxLen = eos._edges[i]->_maxLen;
6862       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
6863       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
6864       eos._edges[i]->_maxLen = maxLen;
6865     }
6866   }
6867
6868   // make temporary quadrangles got by extrusion of
6869   // mesh edges along _LayerEdge._normal's
6870
6871   vector< const SMDS_MeshElement* > tmpFaces;
6872
6873   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6874   {
6875     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6876     if ( eos.ShapeType() != TopAbs_EDGE )
6877       continue;
6878     if ( eos._edges.empty() )
6879     {
6880       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
6881       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
6882       while ( smIt->more() )
6883         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
6884           if ( eov->_edges.size() == 1 )
6885             edge[ bool( edge[0]) ] = eov->_edges[0];
6886
6887       if ( edge[1] )
6888       {
6889         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
6890         tmpFaces.push_back( f );
6891       }
6892     }
6893     for ( size_t i = 0; i < eos._edges.size(); ++i )
6894     {
6895       _LayerEdge* edge = eos._edges[i];
6896       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
6897       {
6898         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
6899         if ( src2->GetPosition()->GetDim() > 0 &&
6900              src2->GetID() < edge->_nodes[0]->GetID() )
6901           continue; // avoid using same segment twice
6902
6903         // a _LayerEdge containing tgt2
6904         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
6905
6906         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
6907         tmpFaces.push_back( f );
6908       }
6909     }
6910   }
6911
6912   // Find _LayerEdge's intersecting tmpFaces.
6913
6914   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
6915                                                             tmpFaces.end()));
6916   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
6917     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
6918
6919   double dist1, dist2, segLen, eps = 0.5;
6920   _CollisionEdges collEdges;
6921   vector< const SMDS_MeshElement* > suspectFaces;
6922   const double angle45 = Cos( 45. * M_PI / 180. );
6923
6924   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
6925   {
6926     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
6927     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
6928       continue;
6929     // find sub-shapes whose VL can influence VL on eos
6930     set< TGeomID > neighborShapes;
6931     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
6932     while ( const TopoDS_Shape* face = fIt->next() )
6933     {
6934       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
6935       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
6936       {
6937         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6938         while ( subIt->more() )
6939           neighborShapes.insert( subIt->next()->GetId() );
6940       }
6941     }
6942     if ( eos.ShapeType() == TopAbs_VERTEX )
6943     {
6944       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
6945       while ( const TopoDS_Shape* edge = eIt->next() )
6946         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
6947     }
6948     // find intersecting _LayerEdge's
6949     for ( size_t i = 0; i < eos._edges.size(); ++i )
6950     {
6951       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
6952       _LayerEdge*   edge = eos._edges[i];
6953       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
6954       segLen *= 1.2;
6955
6956       gp_Vec eSegDir0, eSegDir1;
6957       if ( edge->IsOnEdge() )
6958       {
6959         SMESH_TNodeXYZ eP( edge->_nodes[0] );
6960         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
6961         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
6962       }
6963       suspectFaces.clear();
6964       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
6965                                      SMDSAbs_Face, suspectFaces );
6966       collEdges._intEdges.clear();
6967       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
6968       {
6969         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
6970         if ( f->_le1 == edge || f->_le2 == edge ) continue;
6971         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
6972         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
6973         if ( edge->IsOnEdge() ) {
6974           if ( edge->_2neibors->include( f->_le1 ) ||
6975                edge->_2neibors->include( f->_le2 )) continue;
6976         }
6977         else {
6978           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
6979               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
6980         }
6981         dist1 = dist2 = Precision::Infinite();
6982         if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
6983           dist1 = Precision::Infinite();
6984         if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
6985           dist2 = Precision::Infinite();
6986         if (( dist1 > segLen ) && ( dist2 > segLen ))
6987           continue;
6988
6989         if ( edge->IsOnEdge() )
6990         {
6991           // skip perpendicular EDGEs
6992           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
6993           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
6994                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
6995                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
6996                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
6997           if ( !isParallel )
6998             continue;
6999         }
7000
7001         // either limit inflation of edges or remember them for updating _normal
7002         // double dot = edge->_normal * f->GetDir();
7003         // if ( dot > 0.1 )
7004         {
7005           collEdges._intEdges.push_back( f->_le1 );
7006           collEdges._intEdges.push_back( f->_le2 );
7007         }
7008         // else
7009         // {
7010         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
7011         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
7012         // }
7013       }
7014
7015       if ( !collEdges._intEdges.empty() )
7016       {
7017         collEdges._edge = edge;
7018         data._collisionEdges.push_back( collEdges );
7019       }
7020     }
7021   }
7022
7023   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7024     delete tmpFaces[i];
7025
7026   // restore the zero thickness
7027   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7028   {
7029     _EdgesOnShape& eos = data._edgesOnShape[iS];
7030     if ( eos._edges.empty() ) continue;
7031     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7032
7033     for ( size_t i = 0; i < eos._edges.size(); ++i )
7034     {
7035       eos._edges[i]->InvalidateStep( 1, eos );
7036       eos._edges[i]->_len = 0;
7037     }
7038   }
7039 }
7040
7041 //================================================================================
7042 /*!
7043  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7044  *        will be updated at each inflation step
7045  */
7046 //================================================================================
7047
7048 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
7049                                                              _SolidData&         data,
7050                                                              SMESH_MesherHelper& helper )
7051 {
7052   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7053   const double       preci = BRep_Tool::Tolerance( convFace._face );
7054   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7055
7056   bool edgesToUpdateFound = false;
7057
7058   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7059   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7060   {
7061     _EdgesOnShape& eos = * id2eos->second;
7062     if ( !eos._sWOL.IsNull() ) continue;
7063     if ( !eos._hyp.ToSmooth() ) continue;
7064     for ( size_t i = 0; i < eos._edges.size(); ++i )
7065     {
7066       _LayerEdge* ledge = eos._edges[ i ];
7067       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7068       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7069
7070       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7071                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7072
7073       // the normal must be updated if distance from tgtPos to surface is less than
7074       // target thickness
7075
7076       // find an initial UV for search of a projection of tgtPos to surface
7077       const SMDS_MeshNode* nodeInFace = 0;
7078       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7079       while ( fIt->more() && !nodeInFace )
7080       {
7081         const SMDS_MeshElement* f = fIt->next();
7082         if ( convFaceID != f->getshapeId() ) continue;
7083
7084         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7085         while ( nIt->more() && !nodeInFace )
7086         {
7087           const SMDS_MeshElement* n = nIt->next();
7088           if ( n->getshapeId() == convFaceID )
7089             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7090         }
7091       }
7092       if ( !nodeInFace )
7093         continue;
7094       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7095
7096       // projection
7097       surface->NextValueOfUV( uv, tgtPos, preci );
7098       double  dist = surface->Gap();
7099       if ( dist < 0.95 * ledge->_maxLen )
7100       {
7101         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7102         if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7103         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7104         edgesToUpdateFound = true;
7105       }
7106     }
7107   }
7108
7109   if ( !convFace._isTooCurved && edgesToUpdateFound )
7110   {
7111     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7112   }
7113 }
7114
7115 //================================================================================
7116 /*!
7117  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7118  * _LayerEdge's on neighbor EDGE's
7119  */
7120 //================================================================================
7121
7122 bool _ViscousBuilder::updateNormals( _SolidData&         data,
7123                                      SMESH_MesherHelper& helper,
7124                                      int                 stepNb,
7125                                      double              /*stepSize*/)
7126 {
7127   updateNormalsOfC1Vertices( data );
7128
7129   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7130     return false;
7131
7132   // map to store new _normal and _cosin for each intersected edge
7133   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
7134   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7135   _LayerEdge zeroEdge;
7136   zeroEdge._normal.SetCoord( 0,0,0 );
7137   zeroEdge._maxLen = Precision::Infinite();
7138   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7139
7140   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7141
7142   double segLen, dist1, dist2, dist;
7143   vector< pair< _LayerEdge*, double > > intEdgesDist;
7144   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7145
7146   for ( int iter = 0; iter < 5; ++iter )
7147   {
7148     edge2newEdge.clear();
7149
7150     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7151     {
7152       _CollisionEdges& ce = data._collisionEdges[iE];
7153       _LayerEdge*   edge1 = ce._edge;
7154       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7155       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7156       if ( !eos1 ) continue;
7157
7158       // detect intersections
7159       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7160       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7161       double     eps = 0.5;
7162       intEdgesDist.clear();
7163       double minIntDist = Precision::Infinite();
7164       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7165       {
7166         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7167              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
7168              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7169           continue;
7170         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7171         double fact = ( 1.1 + dot * dot );
7172         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7173         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7174         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7175         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7176         dist1 = dist2 = Precision::Infinite();
7177         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
7178              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7179           continue;
7180         dist = dist1;
7181         if ( dist > testLen || dist <= 0 )
7182         {
7183           dist = dist2;
7184           if ( dist > testLen || dist <= 0 )
7185             continue;
7186         }
7187         // choose a closest edge
7188         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7189         double d1 = intP.SquareDistance( pSrc0 );
7190         double d2 = intP.SquareDistance( pSrc1 );
7191         int iClose = i + ( d2 < d1 );
7192         _LayerEdge* edge2 = ce._intEdges[iClose];
7193         edge2->Unset( _LayerEdge::MARKED );
7194
7195         // choose a closest edge among neighbors
7196         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7197         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7198         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7199         {
7200           _LayerEdge * edgeJ = intEdgesDist[j].first;
7201           if ( edge2->IsNeiborOnEdge( edgeJ ))
7202           {
7203             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7204             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7205           }
7206         }
7207         intEdgesDist.push_back( make_pair( edge2, dist ));
7208         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7209         // {
7210         //   iClose = i + !( d2 < d1 );
7211         //   intEdges.push_back( ce._intEdges[iClose] );
7212         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7213         // }
7214         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7215       }
7216
7217       //ce._edge = 0;
7218
7219       // compute new _normals
7220       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7221       {
7222         _LayerEdge* edge2   = intEdgesDist[i].first;
7223         double      distWgt = edge1->_len / intEdgesDist[i].second;
7224         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7225         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7226         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7227         edge2->Set( _LayerEdge::MARKED );
7228
7229         // get a new normal
7230         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7231
7232         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7233         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7234         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7235         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7236         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7237         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7238         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7239         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7240         newNormal.Normalize();
7241
7242         // get new cosin
7243         double newCos;
7244         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7245         if ( cos1 < theMinSmoothCosin )
7246         {
7247           newCos = cos2 * sgn1;
7248         }
7249         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7250         {
7251           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7252         }
7253         else
7254         {
7255           newCos = edge1->_cosin;
7256         }
7257
7258         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7259         e2neIt->second._normal += distWgt * newNormal;
7260         e2neIt->second._cosin   = newCos;
7261         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7262         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7263           e2neIt->second._normal += dir2;
7264
7265         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7266         e2neIt->second._normal += distWgt * newNormal;
7267         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7268         {
7269           e2neIt->second._cosin  = edge2->_cosin;
7270           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7271         }
7272         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7273           e2neIt->second._normal += dir1;
7274       }
7275     }
7276
7277     if ( edge2newEdge.empty() )
7278       break; //return true;
7279
7280     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7281
7282     // Update data of edges depending on a new _normal
7283
7284     data.UnmarkEdges();
7285     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7286     {
7287       _LayerEdge*    edge = e2neIt->first;
7288       _LayerEdge& newEdge = e2neIt->second;
7289       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7290       if ( edge->Is( _LayerEdge::BLOCKED ) && newEdge._maxLen > edge->_len )
7291         continue;
7292
7293       // Check if a new _normal is OK:
7294       newEdge._normal.Normalize();
7295       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7296       {
7297         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7298         {
7299           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7300           edge->SetMaxLen( newEdge._maxLen );
7301           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7302         }
7303         continue; // the new _normal is bad
7304       }
7305       // the new _normal is OK
7306
7307       // find shapes that need smoothing due to change of _normal
7308       if ( edge->_cosin   < theMinSmoothCosin &&
7309            newEdge._cosin > theMinSmoothCosin )
7310       {
7311         if ( eos->_sWOL.IsNull() )
7312         {
7313           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7314           while ( fIt->more() )
7315             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7316         }
7317         else // edge inflates along a FACE
7318         {
7319           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7320           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7321           while ( const TopoDS_Shape* E = eIt->next() )
7322           {
7323             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
7324             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7325             if ( angle < M_PI / 2 )
7326               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7327           }
7328         }
7329       }
7330
7331       double len = edge->_len;
7332       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7333       edge->SetNormal( newEdge._normal );
7334       edge->SetCosin( newEdge._cosin );
7335       edge->SetNewLength( len, *eos, helper );
7336       edge->Set( _LayerEdge::MARKED );
7337       edge->Set( _LayerEdge::NORMAL_UPDATED );
7338       edgesNoAnaSmooth.insert( eos );
7339     }
7340
7341     // Update normals and other dependent data of not intersecting _LayerEdge's
7342     // neighboring the intersecting ones
7343
7344     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7345     {
7346       _LayerEdge*   edge1 = e2neIt->first;
7347       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7348       if ( !edge1->Is( _LayerEdge::MARKED ))
7349         continue;
7350
7351       if ( edge1->IsOnEdge() )
7352       {
7353         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7354         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7355         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7356       }
7357
7358       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7359         continue;
7360       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7361       {
7362         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7363         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7364           continue; // j-th neighbor is also intersected
7365         _LayerEdge* prevEdge = edge1;
7366         const int nbSteps = 10;
7367         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7368         {
7369           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7370                neighbor->Is( _LayerEdge::MARKED ))
7371             break;
7372           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7373           if ( !eos ) continue;
7374           _LayerEdge* nextEdge = neighbor;
7375           if ( neighbor->_2neibors )
7376           {
7377             int iNext = 0;
7378             nextEdge = neighbor->_2neibors->_edges[iNext];
7379             if ( nextEdge == prevEdge )
7380               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7381           }
7382           double r = double(step-1)/nbSteps/(iter+1);
7383           if ( !nextEdge->_2neibors )
7384             r = Min( r, 0.5 );
7385
7386           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7387           newNorm.Normalize();
7388           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7389             break;
7390
7391           double len = neighbor->_len;
7392           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7393           neighbor->SetNormal( newNorm );
7394           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7395           if ( neighbor->_2neibors )
7396             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7397           neighbor->SetNewLength( len, *eos, helper );
7398           neighbor->Set( _LayerEdge::MARKED );
7399           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7400           edgesNoAnaSmooth.insert( eos );
7401
7402           if ( !neighbor->_2neibors )
7403             break; // neighbor is on VERTEX
7404
7405           // goto the next neighbor
7406           prevEdge = neighbor;
7407           neighbor = nextEdge;
7408         }
7409       }
7410     }
7411     dumpFunctionEnd();
7412   } // iterations
7413
7414   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7415
7416   return true;
7417 }
7418
7419 //================================================================================
7420 /*!
7421  * \brief Check if a new normal is OK
7422  */
7423 //================================================================================
7424
7425 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7426                                      _LayerEdge&   edge,
7427                                      const gp_XYZ& newNormal)
7428 {
7429   // check a min angle between the newNormal and surrounding faces
7430   vector<_Simplex> simplices;
7431   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7432   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7433   double newMinDot = 1, curMinDot = 1;
7434   for ( size_t i = 0; i < simplices.size(); ++i )
7435   {
7436     n1.Set( simplices[i]._nPrev );
7437     n2.Set( simplices[i]._nNext );
7438     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7439     double normLen2 = normFace.SquareModulus();
7440     if ( normLen2 < std::numeric_limits<double>::min() )
7441       continue;
7442     normFace /= Sqrt( normLen2 );
7443     newMinDot = Min( newNormal    * normFace, newMinDot );
7444     curMinDot = Min( edge._normal * normFace, curMinDot );
7445   }
7446   bool ok = true;
7447   if ( newMinDot < 0.5 )
7448   {
7449     ok = ( newMinDot >= curMinDot * 0.9 );
7450     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7451     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7452     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7453   }
7454
7455   return ok;
7456 }
7457
7458 //================================================================================
7459 /*!
7460  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7461  */
7462 //================================================================================
7463
7464 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7465                                                SMESH_MesherHelper& /*helper*/,
7466                                                const int           nbSteps,
7467                                                const double        stepSize )
7468 {
7469   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7470     return true; // no shapes needing smoothing
7471
7472   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7473   {
7474     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7475     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7476          !eos._hyp.ToSmooth() ||
7477          eos.ShapeType() != TopAbs_FACE ||
7478          eos._edges.empty() )
7479       continue;
7480
7481     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7482     if ( !toSmooth ) continue;
7483
7484     for ( size_t i = 0; i < eos._edges.size(); ++i )
7485     {
7486       _LayerEdge* edge = eos._edges[i];
7487       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7488         continue;
7489       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7490         continue;
7491
7492       const gp_XYZ& pPrev = edge->PrevPos();
7493       const gp_XYZ& pLast = edge->_pos.back();
7494       gp_XYZ      stepVec = pLast - pPrev;
7495       double realStepSize = stepVec.Modulus();
7496       if ( realStepSize < numeric_limits<double>::min() )
7497         continue;
7498
7499       edge->_lenFactor = realStepSize / stepSize;
7500       edge->_normal    = stepVec / realStepSize;
7501       edge->Set( _LayerEdge::NORMAL_UPDATED );
7502     }
7503   }
7504
7505   return true;
7506 }
7507
7508 //================================================================================
7509 /*!
7510  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7511  */
7512 //================================================================================
7513
7514 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7515 {
7516   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7517   {
7518     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7519     if ( eov._eosC1.empty() ||
7520          eov.ShapeType() != TopAbs_VERTEX ||
7521          eov._edges.empty() )
7522       continue;
7523
7524     gp_XYZ newNorm   = eov._edges[0]->_normal;
7525     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7526     bool normChanged = false;
7527
7528     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7529     {
7530       _EdgesOnShape*   eoe = eov._eosC1[i];
7531       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7532       const double    eLen = SMESH_Algo::EdgeLength( e );
7533       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7534       if ( oppV.IsSame( eov._shape ))
7535         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7536       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7537       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7538       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7539
7540       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7541       if ( curThickOpp + curThick < eLen )
7542         continue;
7543
7544       double wgt = 2. * curThick / eLen;
7545       newNorm += wgt * eovOpp->_edges[0]->_normal;
7546       normChanged = true;
7547     }
7548     if ( normChanged )
7549     {
7550       eov._edges[0]->SetNormal( newNorm.Normalized() );
7551       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7552     }
7553   }
7554 }
7555
7556 //================================================================================
7557 /*!
7558  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7559  */
7560 //================================================================================
7561
7562 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7563                                                   SMESH_MesherHelper& helper,
7564                                                   int                 stepNb )
7565 {
7566   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7567   bool isOK;
7568
7569   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7570   for ( ; id2face != data._convexFaces.end(); ++id2face )
7571   {
7572     _ConvexFace & convFace = (*id2face).second;
7573     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7574
7575     if ( convFace._normalsFixed )
7576       continue; // already fixed
7577     if ( convFace.CheckPrisms() )
7578       continue; // nothing to fix
7579
7580     convFace._normalsFixed = true;
7581
7582     BRepAdaptor_Surface surface ( convFace._face, false );
7583     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7584
7585     // check if the convex FACE is of spherical shape
7586
7587     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7588     Bnd_B3d nodesBox;
7589     gp_Pnt  center;
7590
7591     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7592     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7593     {
7594       _EdgesOnShape& eos = *(id2eos->second);
7595       if ( eos.ShapeType() == TopAbs_VERTEX )
7596       {
7597         _LayerEdge* ledge = eos._edges[ 0 ];
7598         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7599           centersBox.Add( center );
7600       }
7601       for ( size_t i = 0; i < eos._edges.size(); ++i )
7602         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7603     }
7604     if ( centersBox.IsVoid() )
7605     {
7606       debugMsg( "Error: centersBox.IsVoid()" );
7607       return false;
7608     }
7609     const bool isSpherical =
7610       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7611
7612     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7613     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7614
7615     if ( isSpherical )
7616     {
7617       // set _LayerEdge::_normal as average of all normals
7618
7619       // WARNING: different density of nodes on EDGEs is not taken into account that
7620       // can lead to an improper new normal
7621
7622       gp_XYZ avgNormal( 0,0,0 );
7623       nbEdges = 0;
7624       id2eos = convFace._subIdToEOS.begin();
7625       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7626       {
7627         _EdgesOnShape& eos = *(id2eos->second);
7628         // set data of _CentralCurveOnEdge
7629         if ( eos.ShapeType() == TopAbs_EDGE )
7630         {
7631           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7632           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7633           if ( !eos._sWOL.IsNull() )
7634             ceCurve._adjFace.Nullify();
7635           else
7636             ceCurve._ledges.insert( ceCurve._ledges.end(),
7637                                     eos._edges.begin(), eos._edges.end());
7638         }
7639         // summarize normals
7640         for ( size_t i = 0; i < eos._edges.size(); ++i )
7641           avgNormal += eos._edges[ i ]->_normal;
7642       }
7643       double normSize = avgNormal.SquareModulus();
7644       if ( normSize < 1e-200 )
7645       {
7646         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7647         return false;
7648       }
7649       avgNormal /= Sqrt( normSize );
7650
7651       // compute new _LayerEdge::_cosin on EDGEs
7652       double avgCosin = 0;
7653       int     nbCosin = 0;
7654       gp_Vec inFaceDir;
7655       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7656       {
7657         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7658         if ( ceCurve._adjFace.IsNull() )
7659           continue;
7660         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7661         {
7662           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7663           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7664           if ( isOK )
7665           {
7666             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
7667             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
7668             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
7669             nbCosin++;
7670           }
7671         }
7672       }
7673       if ( nbCosin > 0 )
7674         avgCosin /= nbCosin;
7675
7676       // set _LayerEdge::_normal = avgNormal
7677       id2eos = convFace._subIdToEOS.begin();
7678       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7679       {
7680         _EdgesOnShape& eos = *(id2eos->second);
7681         if ( eos.ShapeType() != TopAbs_EDGE )
7682           for ( size_t i = 0; i < eos._edges.size(); ++i )
7683             eos._edges[ i ]->_cosin = avgCosin;
7684
7685         for ( size_t i = 0; i < eos._edges.size(); ++i )
7686         {
7687           eos._edges[ i ]->SetNormal( avgNormal );
7688           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
7689         }
7690       }
7691     }
7692     else // if ( isSpherical )
7693     {
7694       // We suppose that centers of curvature at all points of the FACE
7695       // lie on some curve, let's call it "central curve". For all _LayerEdge's
7696       // having a common center of curvature we define the same new normal
7697       // as a sum of normals of _LayerEdge's on EDGEs among them.
7698
7699       // get all centers of curvature for each EDGE
7700
7701       helper.SetSubShape( convFace._face );
7702       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
7703
7704       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
7705       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
7706       {
7707         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
7708
7709         // set adjacent FACE
7710         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
7711
7712         // get _LayerEdge's of the EDGE
7713         TGeomID edgeID = meshDS->ShapeToIndex( edge );
7714         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
7715         if ( !eos || eos->_edges.empty() )
7716         {
7717           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
7718           for ( int iV = 0; iV < 2; ++iV )
7719           {
7720             TopoDS_Vertex v = helper.IthVertex( iV, edge );
7721             TGeomID     vID = meshDS->ShapeToIndex( v );
7722             eos = data.GetShapeEdges( vID );
7723             vertexLEdges[ iV ] = eos->_edges[ 0 ];
7724           }
7725           edgeLEdge    = &vertexLEdges[0];
7726           edgeLEdgeEnd = edgeLEdge + 2;
7727
7728           centerCurves[ iE ]._adjFace.Nullify();
7729         }
7730         else
7731         {
7732           if ( ! eos->_toSmooth )
7733             data.SortOnEdge( edge, eos->_edges );
7734           edgeLEdge    = &eos->_edges[ 0 ];
7735           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
7736           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
7737           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
7738
7739           if ( ! eos->_sWOL.IsNull() )
7740             centerCurves[ iE ]._adjFace.Nullify();
7741         }
7742
7743         // Get curvature centers
7744
7745         centersBox.Clear();
7746
7747         if ( edgeLEdge[0]->IsOnEdge() &&
7748              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
7749         { // 1st VERTEX
7750           centerCurves[ iE ].Append( center, vertexLEdges[0] );
7751           centersBox.Add( center );
7752         }
7753         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
7754           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
7755           { // EDGE or VERTEXes
7756             centerCurves[ iE ].Append( center, *edgeLEdge );
7757             centersBox.Add( center );
7758           }
7759         if ( edgeLEdge[-1]->IsOnEdge() &&
7760              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
7761         { // 2nd VERTEX
7762           centerCurves[ iE ].Append( center, vertexLEdges[1] );
7763           centersBox.Add( center );
7764         }
7765         centerCurves[ iE ]._isDegenerated =
7766           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7767
7768       } // loop on EDGES of convFace._face to set up data of centerCurves
7769
7770       // Compute new normals for _LayerEdge's on EDGEs
7771
7772       double avgCosin = 0;
7773       int     nbCosin = 0;
7774       gp_Vec inFaceDir;
7775       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
7776       {
7777         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
7778         if ( ceCurve._isDegenerated )
7779           continue;
7780         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
7781         vector< gp_XYZ > &   newNormals = ceCurve._normals;
7782         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
7783         {
7784           isOK = false;
7785           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
7786           {
7787             if ( iE1 != iE2 )
7788               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
7789           }
7790           if ( isOK && !ceCurve._adjFace.IsNull() )
7791           {
7792             // compute new _LayerEdge::_cosin
7793             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
7794             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7795             if ( isOK )
7796             {
7797               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
7798               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
7799               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
7800               nbCosin++;
7801             }
7802           }
7803         }
7804       }
7805       // set new normals to _LayerEdge's of NOT degenerated central curves
7806       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7807       {
7808         if ( centerCurves[ iE ]._isDegenerated )
7809           continue;
7810         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7811         {
7812           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
7813           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7814         }
7815       }
7816       // set new normals to _LayerEdge's of     degenerated central curves
7817       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7818       {
7819         if ( !centerCurves[ iE ]._isDegenerated ||
7820              centerCurves[ iE ]._ledges.size() < 3 )
7821           continue;
7822         // new normal is an average of new normals at VERTEXes that
7823         // was computed on non-degenerated _CentralCurveOnEdge's
7824         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
7825                            centerCurves[ iE ]._ledges.back ()->_normal );
7826         double sz = newNorm.Modulus();
7827         if ( sz < 1e-200 )
7828           continue;
7829         newNorm /= sz;
7830         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
7831                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
7832         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
7833         {
7834           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
7835           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
7836           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
7837         }
7838       }
7839
7840       // Find new normals for _LayerEdge's based on FACE
7841
7842       if ( nbCosin > 0 )
7843         avgCosin /= nbCosin;
7844       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
7845       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
7846       if ( id2eos != convFace._subIdToEOS.end() )
7847       {
7848         int iE = 0;
7849         gp_XYZ newNorm;
7850         _EdgesOnShape& eos = * ( id2eos->second );
7851         for ( size_t i = 0; i < eos._edges.size(); ++i )
7852         {
7853           _LayerEdge* ledge = eos._edges[ i ];
7854           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7855             continue;
7856           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
7857           {
7858             iE = iE % centerCurves.size();
7859             if ( centerCurves[ iE ]._isDegenerated )
7860               continue;
7861             newNorm.SetCoord( 0,0,0 );
7862             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
7863             {
7864               ledge->SetNormal( newNorm );
7865               ledge->_cosin  = avgCosin;
7866               ledge->Set( _LayerEdge::NORMAL_UPDATED );
7867               break;
7868             }
7869           }
7870         }
7871       }
7872
7873     } // not a quasi-spherical FACE
7874
7875     // Update _LayerEdge's data according to a new normal
7876
7877     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
7878                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
7879
7880     id2eos = convFace._subIdToEOS.begin();
7881     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7882     {
7883       _EdgesOnShape& eos = * ( id2eos->second );
7884       for ( size_t i = 0; i < eos._edges.size(); ++i )
7885       {
7886         _LayerEdge* & ledge = eos._edges[ i ];
7887         double len = ledge->_len;
7888         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
7889         ledge->SetCosin( ledge->_cosin );
7890         ledge->SetNewLength( len, eos, helper );
7891       }
7892       if ( eos.ShapeType() != TopAbs_FACE )
7893         for ( size_t i = 0; i < eos._edges.size(); ++i )
7894         {
7895           _LayerEdge* ledge = eos._edges[ i ];
7896           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
7897           {
7898             _LayerEdge* neibor = ledge->_neibors[iN];
7899             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
7900             {
7901               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
7902               neibor->Set( _LayerEdge::MOVED );
7903               neibor->SetSmooLen( neibor->_len );
7904             }
7905           }
7906         }
7907     } // loop on sub-shapes of convFace._face
7908
7909     // Find FACEs adjacent to convFace._face that got necessity to smooth
7910     // as a result of normals modification
7911
7912     set< _EdgesOnShape* > adjFacesToSmooth;
7913     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7914     {
7915       if ( centerCurves[ iE ]._adjFace.IsNull() ||
7916            centerCurves[ iE ]._adjFaceToSmooth )
7917         continue;
7918       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
7919       {
7920         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
7921         {
7922           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
7923           break;
7924         }
7925       }
7926     }
7927     data.AddShapesToSmooth( adjFacesToSmooth );
7928
7929     dumpFunctionEnd();
7930
7931
7932   } // loop on data._convexFaces
7933
7934   return true;
7935 }
7936
7937 //================================================================================
7938 /*!
7939  * \brief Return max curvature of a FACE
7940  */
7941 //================================================================================
7942
7943 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
7944                                      _EdgesOnShape&      eof,
7945                                      BRepLProp_SLProps&  surfProp,
7946                                      SMESH_MesherHelper& helper)
7947 {
7948   double maxCurvature = 0;
7949
7950   TopoDS_Face F = TopoDS::Face( eof._shape );
7951
7952   const int           nbTestPnt = 5;
7953   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
7954   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
7955   while ( smIt->more() )
7956   {
7957     SMESH_subMesh* sm = smIt->next();
7958     const TGeomID subID = sm->GetId();
7959
7960     // find _LayerEdge's of a sub-shape
7961     _EdgesOnShape* eos;
7962     if (( eos = data.GetShapeEdges( subID )))
7963       this->_subIdToEOS.insert( make_pair( subID, eos ));
7964     else
7965       continue;
7966
7967     // check concavity and curvature and limit data._stepSize
7968     const double minCurvature =
7969       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
7970     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
7971     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
7972     {
7973       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
7974       surfProp.SetParameters( uv.X(), uv.Y() );
7975       if ( surfProp.IsCurvatureDefined() )
7976       {
7977         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
7978                                 surfProp.MinCurvature() * oriFactor );
7979         maxCurvature = Max( maxCurvature, curvature );
7980
7981         if ( curvature > minCurvature )
7982           this->_isTooCurved = true;
7983       }
7984     }
7985   } // loop on sub-shapes of the FACE
7986
7987   return maxCurvature;
7988 }
7989
7990 //================================================================================
7991 /*!
7992  * \brief Finds a center of curvature of a surface at a _LayerEdge
7993  */
7994 //================================================================================
7995
7996 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
7997                                         BRepLProp_SLProps&  surfProp,
7998                                         SMESH_MesherHelper& helper,
7999                                         gp_Pnt &            center ) const
8000 {
8001   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
8002   surfProp.SetParameters( uv.X(), uv.Y() );
8003   if ( !surfProp.IsCurvatureDefined() )
8004     return false;
8005
8006   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8007   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
8008   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
8009   if ( surfCurvatureMin > surfCurvatureMax )
8010     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
8011   else
8012     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
8013
8014   return true;
8015 }
8016
8017 //================================================================================
8018 /*!
8019  * \brief Check that prisms are not distorted
8020  */
8021 //================================================================================
8022
8023 bool _ConvexFace::CheckPrisms() const
8024 {
8025   double vol = 0;
8026   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8027   {
8028     const _LayerEdge* edge = _simplexTestEdges[i];
8029     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8030     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8031       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8032       {
8033         debugMsg( "Bad simplex of _simplexTestEdges ("
8034                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8035                   << " "<< edge->_simplices[j]._nPrev->GetID()
8036                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8037         return false;
8038       }
8039   }
8040   return true;
8041 }
8042
8043 //================================================================================
8044 /*!
8045  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8046  *        stored in this _CentralCurveOnEdge.
8047  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8048  *  \param [in,out] newNormal - current normal at this point, to be redefined
8049  *  \return bool - true if succeeded.
8050  */
8051 //================================================================================
8052
8053 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8054 {
8055   if ( this->_isDegenerated )
8056     return false;
8057
8058   // find two centers the given one lies between
8059
8060   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
8061   {
8062     double sl2 = 1.001 * _segLength2[ i ];
8063
8064     double d1 = center.SquareDistance( _curvaCenters[ i ]);
8065     if ( d1 > sl2 )
8066       continue;
8067     
8068     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8069     if ( d2 > sl2 || d2 + d1 < 1e-100 )
8070       continue;
8071
8072     d1 = Sqrt( d1 );
8073     d2 = Sqrt( d2 );
8074     double r = d1 / ( d1 + d2 );
8075     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
8076                    (      r ) * _ledges[ i+1 ]->_normal );
8077     norm.Normalize();
8078
8079     newNormal += norm;
8080     double sz = newNormal.Modulus();
8081     if ( sz < 1e-200 )
8082       break;
8083     newNormal /= sz;
8084     return true;
8085   }
8086   return false;
8087 }
8088
8089 //================================================================================
8090 /*!
8091  * \brief Set shape members
8092  */
8093 //================================================================================
8094
8095 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
8096                                      const _ConvexFace&  convFace,
8097                                      _SolidData&         data,
8098                                      SMESH_MesherHelper& helper)
8099 {
8100   _edge = edge;
8101
8102   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8103   while ( const TopoDS_Shape* F = fIt->next())
8104     if ( !convFace._face.IsSame( *F ))
8105     {
8106       _adjFace = TopoDS::Face( *F );
8107       _adjFaceToSmooth = false;
8108       // _adjFace already in a smoothing queue ?
8109       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8110         _adjFaceToSmooth = eos->_toSmooth;
8111       break;
8112     }
8113 }
8114
8115 //================================================================================
8116 /*!
8117  * \brief Looks for intersection of it's last segment with faces
8118  *  \param distance - returns shortest distance from the last node to intersection
8119  */
8120 //================================================================================
8121
8122 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
8123                                    double &                 distance,
8124                                    const double&            epsilon,
8125                                    _EdgesOnShape&           eos,
8126                                    const SMDS_MeshElement** intFace)
8127 {
8128   vector< const SMDS_MeshElement* > suspectFaces;
8129   double segLen;
8130   gp_Ax1 lastSegment = LastSegment( segLen, eos );
8131   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8132
8133   bool segmentIntersected = false;
8134   distance = Precision::Infinite();
8135   int iFace = -1; // intersected face
8136   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8137   {
8138     const SMDS_MeshElement* face = suspectFaces[j];
8139     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8140          face->GetNodeIndex( _nodes[0]     ) >= 0 )
8141       continue; // face sharing _LayerEdge node
8142     const int nbNodes = face->NbCornerNodes();
8143     bool intFound = false;
8144     double dist;
8145     SMDS_MeshElement::iterator nIt = face->begin_nodes();
8146     if ( nbNodes == 3 )
8147     {
8148       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8149     }
8150     else
8151     {
8152       const SMDS_MeshNode* tria[3];
8153       tria[0] = *nIt++;
8154       tria[1] = *nIt++;
8155       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8156       {
8157         tria[2] = *nIt++;
8158         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8159         tria[1] = tria[2];
8160       }
8161     }
8162     if ( intFound )
8163     {
8164       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8165         segmentIntersected = true;
8166       if ( distance > dist )
8167         distance = dist, iFace = j;
8168     }
8169   }
8170   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8171
8172   distance -= segLen;
8173
8174   if ( segmentIntersected )
8175   {
8176 #ifdef __myDEBUG
8177     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8178     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8179     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8180          << ", intersection with face ("
8181          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8182          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8183          << ") distance = " << distance << endl;
8184 #endif
8185   }
8186
8187   return segmentIntersected;
8188 }
8189
8190 //================================================================================
8191 /*!
8192  * \brief Returns a point used to check orientation of _simplices
8193  */
8194 //================================================================================
8195
8196 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8197 {
8198   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8199
8200   if ( !eos || eos->_sWOL.IsNull() )
8201     return _pos[ i ];
8202
8203   if ( eos->SWOLType() == TopAbs_EDGE )
8204   {
8205     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8206   }
8207   //else //  TopAbs_FACE
8208
8209   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8210 }
8211
8212 //================================================================================
8213 /*!
8214  * \brief Returns size and direction of the last segment
8215  */
8216 //================================================================================
8217
8218 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8219 {
8220   // find two non-coincident positions
8221   gp_XYZ orig = _pos.back();
8222   gp_XYZ vec;
8223   int iPrev = _pos.size() - 2;
8224   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8225   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8226   while ( iPrev >= 0 )
8227   {
8228     vec = orig - _pos[iPrev];
8229     if ( vec.SquareModulus() > tol*tol )
8230       break;
8231     else
8232       iPrev--;
8233   }
8234
8235   // make gp_Ax1
8236   gp_Ax1 segDir;
8237   if ( iPrev < 0 )
8238   {
8239     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8240     segDir.SetDirection( _normal );
8241     segLen = 0;
8242   }
8243   else
8244   {
8245     gp_Pnt pPrev = _pos[ iPrev ];
8246     if ( !eos._sWOL.IsNull() )
8247     {
8248       TopLoc_Location loc;
8249       if ( eos.SWOLType() == TopAbs_EDGE )
8250       {
8251         double f,l;
8252         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8253         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8254       }
8255       else
8256       {
8257         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8258         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8259       }
8260       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8261     }
8262     segDir.SetLocation( pPrev );
8263     segDir.SetDirection( vec );
8264     segLen = vec.Modulus();
8265   }
8266
8267   return segDir;
8268 }
8269
8270 //================================================================================
8271 /*!
8272  * \brief Return the last (or \a which) position of the target node on a FACE. 
8273  *  \param [in] F - the FACE this _LayerEdge is inflated along
8274  *  \param [in] which - index of position
8275  *  \return gp_XY - result UV
8276  */
8277 //================================================================================
8278
8279 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8280 {
8281   if ( F.IsSame( eos._sWOL )) // F is my FACE
8282     return gp_XY( _pos.back().X(), _pos.back().Y() );
8283
8284   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8285     return gp_XY( 1e100, 1e100 );
8286
8287   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8288   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8289   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8290   if ( !C2d.IsNull() && f <= u && u <= l )
8291     return C2d->Value( u ).XY();
8292
8293   return gp_XY( 1e100, 1e100 );
8294 }
8295
8296 //================================================================================
8297 /*!
8298  * \brief Test intersection of the last segment with a given triangle
8299  *   using Moller-Trumbore algorithm
8300  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8301  */
8302 //================================================================================
8303
8304 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8305                                const gp_XYZ& vert0,
8306                                const gp_XYZ& vert1,
8307                                const gp_XYZ& vert2,
8308                                double&       t,
8309                                const double& EPSILON) const
8310 {
8311   const gp_Pnt& orig = lastSegment.Location();
8312   const gp_Dir& dir  = lastSegment.Direction();
8313
8314   /* calculate distance from vert0 to ray origin */
8315   //gp_XYZ tvec = orig.XYZ() - vert0;
8316
8317   //if ( tvec * dir > EPSILON )
8318     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8319     //return false;
8320
8321   gp_XYZ edge1 = vert1 - vert0;
8322   gp_XYZ edge2 = vert2 - vert0;
8323
8324   /* begin calculating determinant - also used to calculate U parameter */
8325   gp_XYZ pvec = dir.XYZ() ^ edge2;
8326
8327   /* if determinant is near zero, ray lies in plane of triangle */
8328   double det = edge1 * pvec;
8329
8330   const double ANGL_EPSILON = 1e-12;
8331   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8332     return false;
8333
8334   /* calculate distance from vert0 to ray origin */
8335   gp_XYZ tvec = orig.XYZ() - vert0;
8336
8337   /* calculate U parameter and test bounds */
8338   double u = ( tvec * pvec ) / det;
8339   //if (u < 0.0 || u > 1.0)
8340   if ( u < -EPSILON || u > 1.0 + EPSILON )
8341     return false;
8342
8343   /* prepare to test V parameter */
8344   gp_XYZ qvec = tvec ^ edge1;
8345
8346   /* calculate V parameter and test bounds */
8347   double v = (dir.XYZ() * qvec) / det;
8348   //if ( v < 0.0 || u + v > 1.0 )
8349   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8350     return false;
8351
8352   /* calculate t, ray intersects triangle */
8353   t = (edge2 * qvec) / det;
8354
8355   //return true;
8356   return t > 0.;
8357 }
8358
8359 //================================================================================
8360 /*!
8361  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8362  *        neighbor _LayerEdge's by it's own inflation vector.
8363  *  \param [in] eov - EOS of the VERTEX
8364  *  \param [in] eos - EOS of the FACE
8365  *  \param [in] step - inflation step
8366  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8367  */
8368 //================================================================================
8369
8370 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8371                                    const _EdgesOnShape*    eos,
8372                                    const int               step,
8373                                    vector< _LayerEdge* > & badSmooEdges )
8374 {
8375   // check if any of _neibors is in badSmooEdges
8376   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8377                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8378     return;
8379
8380   // get all edges to move
8381
8382   set< _LayerEdge* > edges;
8383
8384   // find a distance between _LayerEdge on VERTEX and its neighbors
8385   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8386   double dist2 = 0;
8387   for ( size_t i = 0; i < _neibors.size(); ++i )
8388   {
8389     _LayerEdge* nEdge = _neibors[i];
8390     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8391     {
8392       edges.insert( nEdge );
8393       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8394     }
8395   }
8396   // add _LayerEdge's close to curPosV
8397   size_t nbE;
8398   do {
8399     nbE = edges.size();
8400     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8401     {
8402       _LayerEdge* edgeF = *e;
8403       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8404       {
8405         _LayerEdge* nEdge = edgeF->_neibors[i];
8406         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8407              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8408           edges.insert( nEdge );
8409       }
8410     }
8411   }
8412   while ( nbE < edges.size() );
8413
8414   // move the target node of the got edges
8415
8416   gp_XYZ prevPosV = PrevPos();
8417   if ( eov->SWOLType() == TopAbs_EDGE )
8418   {
8419     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8420     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8421   }
8422   else if ( eov->SWOLType() == TopAbs_FACE )
8423   {
8424     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8425     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8426   }
8427
8428   SMDS_FacePositionPtr fPos;
8429   //double r = 1. - Min( 0.9, step / 10. );
8430   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8431   {
8432     _LayerEdge*       edgeF = *e;
8433     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8434     const gp_XYZ    newPosF = curPosV + prevVF;
8435     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8436     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8437     edgeF->_pos.back() = newPosF;
8438     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8439
8440     // set _curvature to make edgeF updated by putOnOffsetSurface()
8441     if ( !edgeF->_curvature )
8442       if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8443       {
8444         edgeF->_curvature = _Factory::NewCurvature();
8445         edgeF->_curvature->_r = 0;
8446         edgeF->_curvature->_k = 0;
8447         edgeF->_curvature->_h2lenRatio = 0;
8448         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8449       }
8450   }
8451   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8452   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8453   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8454   // {
8455   //   _LayerEdge*      edgeF = *e;
8456   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8457   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8458   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8459   //   edgeF->_pos.back() = newPosF;
8460   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8461   // }
8462
8463   // smooth _LayerEdge's around moved nodes
8464   //size_t nbBadBefore = badSmooEdges.size();
8465   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8466   {
8467     _LayerEdge* edgeF = *e;
8468     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8469       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8470         //&& !edges.count( edgeF->_neibors[j] ))
8471       {
8472         _LayerEdge* edgeFN = edgeF->_neibors[j];
8473         edgeFN->Unset( SMOOTHED );
8474         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8475         // if ( nbBad > 0 )
8476         // {
8477         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8478         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8479         //   int        nbBadAfter = edgeFN->_simplices.size();
8480         //   double vol;
8481         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8482         //   {
8483         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8484         //   }
8485         //   if ( nbBadAfter <= nbBad )
8486         //   {
8487         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8488         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8489         //     edgeF->_pos.back() = newPosF;
8490         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8491         //     nbBad = nbBadAfter;
8492         //   }
8493         // }
8494         if ( nbBad > 0 )
8495           badSmooEdges.push_back( edgeFN );
8496       }
8497   }
8498     // move a bit not smoothed around moved nodes
8499   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8500   //   {
8501   //   _LayerEdge*      edgeF = badSmooEdges[i];
8502   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8503   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8504   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8505   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8506   //   edgeF->_pos.back() = newPosF;
8507   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8508   // }
8509 }
8510
8511 //================================================================================
8512 /*!
8513  * \brief Perform smooth of _LayerEdge's based on EDGE's
8514  *  \retval bool - true if node has been moved
8515  */
8516 //================================================================================
8517
8518 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8519                               const TopoDS_Face&             F,
8520                               SMESH_MesherHelper&            helper)
8521 {
8522   ASSERT( IsOnEdge() );
8523
8524   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8525   SMESH_TNodeXYZ oldPos( tgtNode );
8526   double dist01, distNewOld;
8527   
8528   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8529   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8530   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8531
8532   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8533   double lenDelta = 0;
8534   if ( _curvature )
8535   {
8536     //lenDelta = _curvature->lenDelta( _len );
8537     lenDelta = _curvature->lenDeltaByDist( dist01 );
8538     newPos.ChangeCoord() += _normal * lenDelta;
8539   }
8540
8541   distNewOld = newPos.Distance( oldPos );
8542
8543   if ( F.IsNull() )
8544   {
8545     if ( _2neibors->_plnNorm )
8546     {
8547       // put newPos on the plane defined by source node and _plnNorm
8548       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8549       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8550       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8551     }
8552     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8553     _pos.back() = newPos.XYZ();
8554   }
8555   else
8556   {
8557     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8558     gp_XY uv( Precision::Infinite(), 0 );
8559     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8560     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8561
8562     newPos = surface->Value( uv );
8563     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8564   }
8565
8566   // commented for IPAL0052478
8567   // if ( _curvature && lenDelta < 0 )
8568   // {
8569   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8570   //   _len -= prevPos.Distance( oldPos );
8571   //   _len += prevPos.Distance( newPos );
8572   // }
8573   bool moved = distNewOld > dist01/50;
8574   //if ( moved )
8575   dumpMove( tgtNode ); // debug
8576
8577   return moved;
8578 }
8579
8580 //================================================================================
8581 /*!
8582  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8583  */
8584 //================================================================================
8585
8586 void _LayerEdge::SmoothWoCheck()
8587 {
8588   if ( Is( DIFFICULT ))
8589     return;
8590
8591   bool moved = Is( SMOOTHED );
8592   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8593     moved = _neibors[i]->Is( SMOOTHED );
8594   if ( !moved )
8595     return;
8596
8597   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8598
8599   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8600   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8601   _pos.back() = newPos;
8602
8603   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8604 }
8605
8606 //================================================================================
8607 /*!
8608  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8609  */
8610 //================================================================================
8611
8612 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8613 {
8614   if ( ! Is( NEAR_BOUNDARY ))
8615     return 0;
8616
8617   int nbBad = 0;
8618   double vol;
8619   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8620   {
8621     _LayerEdge* eN = _neibors[iN];
8622     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8623       continue;
8624     if ( needSmooth )
8625       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8626                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8627                        eN->_pos.size() != _pos.size() );
8628
8629     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8630     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8631     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8632       if ( eN->_nodes.size() > 1 &&
8633            eN->_simplices[i].Includes( _nodes.back() ) &&
8634            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8635       {
8636         ++nbBad;
8637         if ( badNeibors )
8638         {
8639           badNeibors->push_back( eN );
8640           debugMsg("Bad boundary simplex ( "
8641                    << " "<< eN->_nodes[0]->GetID()
8642                    << " "<< eN->_nodes.back()->GetID()
8643                    << " "<< eN->_simplices[i]._nPrev->GetID()
8644                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8645         }
8646         else
8647         {
8648           break;
8649         }
8650       }
8651   }
8652   return nbBad;
8653 }
8654
8655 //================================================================================
8656 /*!
8657  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8658  *  \retval int - nb of bad simplices around this _LayerEdge
8659  */
8660 //================================================================================
8661
8662 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8663 {
8664   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8665     return 0; // shape of simplices not changed
8666   if ( _simplices.size() < 2 )
8667     return 0; // _LayerEdge inflated along EDGE or FACE
8668
8669   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
8670     findBest = true;
8671
8672   const gp_XYZ& curPos  = _pos.back();
8673   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
8674
8675   // quality metrics (orientation) of tetras around _tgtNode
8676   int nbOkBefore = 0;
8677   double vol, minVolBefore = 1e100;
8678   for ( size_t i = 0; i < _simplices.size(); ++i )
8679   {
8680     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8681     minVolBefore = Min( minVolBefore, vol );
8682   }
8683   int nbBad = _simplices.size() - nbOkBefore;
8684
8685   bool bndNeedSmooth = false;
8686   if ( nbBad == 0 )
8687     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
8688   if ( nbBad > 0 )
8689     Set( DISTORTED );
8690
8691   // evaluate min angle
8692   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
8693   {
8694     size_t nbGoodAngles = _simplices.size();
8695     double angle;
8696     for ( size_t i = 0; i < _simplices.size(); ++i )
8697     {
8698       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
8699         --nbGoodAngles;
8700     }
8701     if ( nbGoodAngles == _simplices.size() )
8702     {
8703       Unset( MOVED );
8704       return 0;
8705     }
8706   }
8707   if ( Is( ON_CONCAVE_FACE ))
8708     findBest = true;
8709
8710   if ( step % 2 == 0 )
8711     findBest = false;
8712
8713   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8714   {
8715     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
8716       _smooFunction = _funs[ FUN_CENTROIDAL ];
8717     else
8718       _smooFunction = _funs[ FUN_LAPLACIAN ];
8719   }
8720
8721   // compute new position for the last _pos using different _funs
8722   gp_XYZ newPos;
8723   bool moved = false;
8724   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8725   {
8726     if ( iFun < 0 )
8727       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8728     else if ( _funs[ iFun ] == _smooFunction )
8729       continue; // _smooFunction again
8730     else if ( step > 1 )
8731       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8732     else
8733       break; // let "easy" functions improve elements around distorted ones
8734
8735     if ( _curvature )
8736     {
8737       double delta  = _curvature->lenDelta( _len );
8738       if ( delta > 0 )
8739         newPos += _normal * delta;
8740       else
8741       {
8742         double segLen = _normal * ( newPos - prevPos );
8743         if ( segLen + delta > 0 )
8744           newPos += _normal * delta;
8745       }
8746       // double segLenChange = _normal * ( curPos - newPos );
8747       // newPos += 0.5 * _normal * segLenChange;
8748     }
8749
8750     int nbOkAfter = 0;
8751     double minVolAfter = 1e100;
8752     for ( size_t i = 0; i < _simplices.size(); ++i )
8753     {
8754       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8755       minVolAfter = Min( minVolAfter, vol );
8756     }
8757     // get worse?
8758     if ( nbOkAfter < nbOkBefore )
8759       continue;
8760
8761     if (( findBest ) &&
8762         ( nbOkAfter == nbOkBefore ) &&
8763         ( minVolAfter <= minVolBefore ))
8764       continue;
8765
8766     nbBad        = _simplices.size() - nbOkAfter;
8767     minVolBefore = minVolAfter;
8768     nbOkBefore   = nbOkAfter;
8769     moved        = true;
8770
8771     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8772     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8773     _pos.back() = newPos;
8774
8775     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8776                   << (nbBad ? " --BAD" : ""));
8777
8778     if ( iFun > -1 )
8779     {
8780       continue; // look for a better function
8781     }
8782
8783     if ( !findBest )
8784       break;
8785
8786   } // loop on smoothing functions
8787
8788   if ( moved ) // notify _neibors
8789   {
8790     Set( SMOOTHED );
8791     for ( size_t i = 0; i < _neibors.size(); ++i )
8792       if ( !_neibors[i]->Is( MOVED ))
8793       {
8794         _neibors[i]->Set( MOVED );
8795         toSmooth.push_back( _neibors[i] );
8796       }
8797   }
8798
8799   return nbBad;
8800 }
8801
8802 //================================================================================
8803 /*!
8804  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8805  *  \retval int - nb of bad simplices around this _LayerEdge
8806  */
8807 //================================================================================
8808
8809 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
8810 {
8811   if ( !_smooFunction )
8812     return 0; // _LayerEdge inflated along EDGE or FACE
8813   if ( Is( BLOCKED ))
8814     return 0; // not inflated
8815
8816   const gp_XYZ& curPos  = _pos.back();
8817   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
8818
8819   // quality metrics (orientation) of tetras around _tgtNode
8820   int nbOkBefore = 0;
8821   double vol, minVolBefore = 1e100;
8822   for ( size_t i = 0; i < _simplices.size(); ++i )
8823   {
8824     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
8825     minVolBefore = Min( minVolBefore, vol );
8826   }
8827   int nbBad = _simplices.size() - nbOkBefore;
8828
8829   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
8830   {
8831     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
8832       _smooFunction = _funs[ FUN_LAPLACIAN ];
8833     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
8834       _smooFunction = _funs[ FUN_CENTROIDAL ];
8835   }
8836
8837   // compute new position for the last _pos using different _funs
8838   gp_XYZ newPos;
8839   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
8840   {
8841     if ( iFun < 0 )
8842       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8843     else if ( _funs[ iFun ] == _smooFunction )
8844       continue; // _smooFunction again
8845     else if ( step > 1 )
8846       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
8847     else
8848       break; // let "easy" functions improve elements around distorted ones
8849
8850     if ( _curvature )
8851     {
8852       double delta  = _curvature->lenDelta( _len );
8853       if ( delta > 0 )
8854         newPos += _normal * delta;
8855       else
8856       {
8857         double segLen = _normal * ( newPos - prevPos );
8858         if ( segLen + delta > 0 )
8859           newPos += _normal * delta;
8860       }
8861       // double segLenChange = _normal * ( curPos - newPos );
8862       // newPos += 0.5 * _normal * segLenChange;
8863     }
8864
8865     int nbOkAfter = 0;
8866     double minVolAfter = 1e100;
8867     for ( size_t i = 0; i < _simplices.size(); ++i )
8868     {
8869       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
8870       minVolAfter = Min( minVolAfter, vol );
8871     }
8872     // get worse?
8873     if ( nbOkAfter < nbOkBefore )
8874       continue;
8875     if (( isConcaveFace || findBest ) &&
8876         ( nbOkAfter == nbOkBefore ) &&
8877         ( minVolAfter <= minVolBefore )
8878         )
8879       continue;
8880
8881     nbBad        = _simplices.size() - nbOkAfter;
8882     minVolBefore = minVolAfter;
8883     nbOkBefore   = nbOkAfter;
8884
8885     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8886     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8887     _pos.back() = newPos;
8888
8889     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
8890                   << ( nbBad ? "--BAD" : ""));
8891
8892     // commented for IPAL0052478
8893     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
8894     // _len += prevPos.Distance(newPos);
8895
8896     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
8897     {
8898       //_smooFunction = _funs[ iFun ];
8899       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
8900       // << "\t nbBad: " << _simplices.size() - nbOkAfter
8901       // << " minVol: " << minVolAfter
8902       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
8903       // << endl;
8904       continue; // look for a better function
8905     }
8906
8907     if ( !findBest )
8908       break;
8909
8910   } // loop on smoothing functions
8911
8912   return nbBad;
8913 }
8914
8915 //================================================================================
8916 /*!
8917  * \brief Chooses a smoothing technique giving a position most close to an initial one.
8918  *        For a correct result, _simplices must contain nodes lying on geometry.
8919  */
8920 //================================================================================
8921
8922 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
8923                                      const TNode2Edge&     /*n2eMap*/)
8924 {
8925   if ( _smooFunction ) return;
8926
8927   // use smoothNefPolygon() near concaveVertices
8928   if ( !concaveVertices.empty() )
8929   {
8930     _smooFunction = _funs[ FUN_CENTROIDAL ];
8931
8932     Set( ON_CONCAVE_FACE );
8933
8934     for ( size_t i = 0; i < _simplices.size(); ++i )
8935     {
8936       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
8937       {
8938         _smooFunction = _funs[ FUN_NEFPOLY ];
8939
8940         // set FUN_CENTROIDAL to neighbor edges
8941         for ( i = 0; i < _neibors.size(); ++i )
8942         {
8943           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
8944           {
8945             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
8946           }
8947         }
8948         return;
8949       }
8950     }
8951
8952     // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
8953     // // where the nodes are smoothed too far along a sphere thus creating
8954     // // inverted _simplices
8955     // double dist[theNbSmooFuns];
8956     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
8957     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
8958
8959     // double minDist = Precision::Infinite();
8960     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
8961     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
8962     // {
8963     //   gp_Pnt newP = (this->*_funs[i])();
8964     //   dist[i] = p.SquareDistance( newP );
8965     //   if ( dist[i]*coef[i] < minDist )
8966     //   {
8967     //     _smooFunction = _funs[i];
8968     //     minDist = dist[i]*coef[i];
8969     //   }
8970     // }
8971   }
8972   else
8973   {
8974     _smooFunction = _funs[ FUN_LAPLACIAN ];
8975   }
8976   // int minDim = 3;
8977   // for ( size_t i = 0; i < _simplices.size(); ++i )
8978   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
8979   // if ( minDim == 0 )
8980   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8981   // else if ( minDim == 1 )
8982   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
8983
8984
8985   // int iMin;
8986   // for ( int i = 0; i < FUN_NB; ++i )
8987   // {
8988   //   //cout << dist[i] << " ";
8989   //   if ( _smooFunction == _funs[i] ) {
8990   //     iMin = i;
8991   //     //debugMsg( fNames[i] );
8992   //     break;
8993   //   }
8994   // }
8995   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
8996 }
8997
8998 //================================================================================
8999 /*!
9000  * \brief Returns a name of _SmooFunction
9001  */
9002 //================================================================================
9003
9004 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
9005 {
9006   if ( !fun )
9007     fun = _smooFunction;
9008   for ( int i = 0; i < theNbSmooFuns; ++i )
9009     if ( fun == _funs[i] )
9010       return i;
9011
9012   return theNbSmooFuns;
9013 }
9014
9015 //================================================================================
9016 /*!
9017  * \brief Computes a new node position using Laplacian smoothing
9018  */
9019 //================================================================================
9020
9021 gp_XYZ _LayerEdge::smoothLaplacian()
9022 {
9023   gp_XYZ newPos (0,0,0);
9024   for ( size_t i = 0; i < _simplices.size(); ++i )
9025     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9026   newPos /= _simplices.size();
9027
9028   return newPos;
9029 }
9030
9031 //================================================================================
9032 /*!
9033  * \brief Computes a new node position using angular-based smoothing
9034  */
9035 //================================================================================
9036
9037 gp_XYZ _LayerEdge::smoothAngular()
9038 {
9039   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
9040   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
9041   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
9042
9043   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9044   gp_XYZ pN( 0,0,0 );
9045   for ( size_t i = 0; i < _simplices.size(); ++i )
9046   {
9047     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9048     edgeDir.push_back( p - pPrev );
9049     edgeSize.push_back( edgeDir.back().Magnitude() );
9050     if ( edgeSize.back() < numeric_limits<double>::min() )
9051     {
9052       edgeDir.pop_back();
9053       edgeSize.pop_back();
9054     }
9055     else
9056     {
9057       edgeDir.back() /= edgeSize.back();
9058       points.push_back( p );
9059       pN += p;
9060     }
9061     pPrev = p;
9062   }
9063   edgeDir.push_back ( edgeDir[0] );
9064   edgeSize.push_back( edgeSize[0] );
9065   pN /= points.size();
9066
9067   gp_XYZ newPos(0,0,0);
9068   double sumSize = 0;
9069   for ( size_t i = 0; i < points.size(); ++i )
9070   {
9071     gp_Vec toN    = pN - points[i];
9072     double toNLen = toN.Magnitude();
9073     if ( toNLen < numeric_limits<double>::min() )
9074     {
9075       newPos += pN;
9076       continue;
9077     }
9078     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
9079     double bisecLen = bisec.SquareMagnitude();
9080     if ( bisecLen < numeric_limits<double>::min() )
9081     {
9082       gp_Vec norm = edgeDir[i] ^ toN;
9083       bisec = norm ^ edgeDir[i];
9084       bisecLen = bisec.SquareMagnitude();
9085     }
9086     bisecLen = Sqrt( bisecLen );
9087     bisec /= bisecLen;
9088
9089 #if 1
9090     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9091     sumSize += bisecLen;
9092 #else
9093     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9094     sumSize += ( edgeSize[i] + edgeSize[i+1] );
9095 #endif
9096     newPos += pNew;
9097   }
9098   newPos /= sumSize;
9099
9100   // project newPos to an average plane
9101
9102   gp_XYZ norm(0,0,0); // plane normal
9103   points.push_back( points[0] );
9104   for ( size_t i = 1; i < points.size(); ++i )
9105   {
9106     gp_XYZ vec1 = points[ i-1 ] - pN;
9107     gp_XYZ vec2 = points[ i   ] - pN;
9108     gp_XYZ cross = vec1 ^ vec2;
9109     try {
9110       cross.Normalize();
9111       if ( cross * norm < numeric_limits<double>::min() )
9112         norm += cross.Reversed();
9113       else
9114         norm += cross;
9115     }
9116     catch (Standard_Failure&) { // if |cross| == 0.
9117     }
9118   }
9119   gp_XYZ vec = newPos - pN;
9120   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
9121   newPos     = newPos - r * norm;
9122
9123   return newPos;
9124 }
9125
9126 //================================================================================
9127 /*!
9128  * \brief Computes a new node position using weighted node positions
9129  */
9130 //================================================================================
9131
9132 gp_XYZ _LayerEdge::smoothLengthWeighted()
9133 {
9134   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9135   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
9136
9137   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9138   for ( size_t i = 0; i < _simplices.size(); ++i )
9139   {
9140     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9141     edgeSize.push_back( ( p - pPrev ).Modulus() );
9142     if ( edgeSize.back() < numeric_limits<double>::min() )
9143     {
9144       edgeSize.pop_back();
9145     }
9146     else
9147     {
9148       points.push_back( p );
9149     }
9150     pPrev = p;
9151   }
9152   edgeSize.push_back( edgeSize[0] );
9153
9154   gp_XYZ newPos(0,0,0);
9155   double sumSize = 0;
9156   for ( size_t i = 0; i < points.size(); ++i )
9157   {
9158     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9159     sumSize += edgeSize[i] + edgeSize[i+1];
9160   }
9161   newPos /= sumSize;
9162   return newPos;
9163 }
9164
9165 //================================================================================
9166 /*!
9167  * \brief Computes a new node position using angular-based smoothing
9168  */
9169 //================================================================================
9170
9171 gp_XYZ _LayerEdge::smoothCentroidal()
9172 {
9173   gp_XYZ newPos(0,0,0);
9174   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9175   double sumSize = 0;
9176   for ( size_t i = 0; i < _simplices.size(); ++i )
9177   {
9178     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9179     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9180     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9181     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9182
9183     sumSize += size;
9184     newPos += gc * size;
9185   }
9186   newPos /= sumSize;
9187
9188   return newPos;
9189 }
9190
9191 //================================================================================
9192 /*!
9193  * \brief Computes a new node position located inside a Nef polygon
9194  */
9195 //================================================================================
9196
9197 gp_XYZ _LayerEdge::smoothNefPolygon()
9198 #ifdef OLD_NEF_POLYGON
9199 {
9200   gp_XYZ newPos(0,0,0);
9201
9202   // get a plane to search a solution on
9203
9204   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9205   size_t i;
9206   const double tol = numeric_limits<double>::min();
9207   gp_XYZ center(0,0,0);
9208   for ( i = 0; i < _simplices.size(); ++i )
9209   {
9210     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9211                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9212     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9213   }
9214   vecs.back() = vecs[0];
9215   center /= _simplices.size();
9216
9217   gp_XYZ zAxis(0,0,0);
9218   for ( i = 0; i < _simplices.size(); ++i )
9219     zAxis += vecs[i] ^ vecs[i+1];
9220
9221   gp_XYZ yAxis;
9222   for ( i = 0; i < _simplices.size(); ++i )
9223   {
9224     yAxis = vecs[i];
9225     if ( yAxis.SquareModulus() > tol )
9226       break;
9227   }
9228   gp_XYZ xAxis = yAxis ^ zAxis;
9229   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9230   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9231   //                             p0.Distance( _simplices[2]._nPrev ));
9232   // gp_XYZ center = smoothLaplacian();
9233   // gp_XYZ xAxis, yAxis, zAxis;
9234   // for ( i = 0; i < _simplices.size(); ++i )
9235   // {
9236   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9237   //   if ( xAxis.SquareModulus() > tol*tol )
9238   //     break;
9239   // }
9240   // for ( i = 1; i < _simplices.size(); ++i )
9241   // {
9242   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9243   //   zAxis = xAxis ^ yAxis;
9244   //   if ( zAxis.SquareModulus() > tol*tol )
9245   //     break;
9246   // }
9247   // if ( i == _simplices.size() ) return newPos;
9248
9249   yAxis = zAxis ^ xAxis;
9250   xAxis /= xAxis.Modulus();
9251   yAxis /= yAxis.Modulus();
9252
9253   // get half-planes of _simplices
9254
9255   vector< _halfPlane > halfPlns( _simplices.size() );
9256   int nbHP = 0;
9257   for ( size_t i = 0; i < _simplices.size(); ++i )
9258   {
9259     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9260     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9261     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9262     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9263     gp_XY  vec12 = p2 - p1;
9264     double dist12 = vec12.Modulus();
9265     if ( dist12 < tol )
9266       continue;
9267     vec12 /= dist12;
9268     halfPlns[ nbHP ]._pos = p1;
9269     halfPlns[ nbHP ]._dir = vec12;
9270     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9271     ++nbHP;
9272   }
9273
9274   // intersect boundaries of half-planes, define state of intersection points
9275   // in relation to all half-planes and calculate internal point of a 2D polygon
9276
9277   double sumLen = 0;
9278   gp_XY newPos2D (0,0);
9279
9280   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9281   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9282   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9283
9284   vector< vector< TIntPntState > > allIntPnts( nbHP );
9285   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9286   {
9287     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9288     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9289
9290     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9291     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9292
9293     int nbNotOut = 0;
9294     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9295
9296     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9297     {
9298       if ( iHP1 == iHP2 ) continue;
9299
9300       TIntPntState & ips1 = intPnts1[ iHP2 ];
9301       if ( ips1.second == UNDEF )
9302       {
9303         // find an intersection point of boundaries of iHP1 and iHP2
9304
9305         if ( iHP2 == iPrev ) // intersection with neighbors is known
9306           ips1.first = halfPlns[ iHP1 ]._pos;
9307         else if ( iHP2 == iNext )
9308           ips1.first = halfPlns[ iHP2 ]._pos;
9309         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9310           ips1.second = NO_INT;
9311
9312         // classify the found intersection point
9313         if ( ips1.second != NO_INT )
9314         {
9315           ips1.second = NOT_OUT;
9316           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9317             if ( i != iHP1 && i != iHP2 &&
9318                  halfPlns[ i ].IsOut( ips1.first, tol ))
9319               ips1.second = IS_OUT;
9320         }
9321         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9322         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9323         TIntPntState & ips2 = intPnts2[ iHP1 ];
9324         ips2 = ips1;
9325       }
9326       if ( ips1.second == NOT_OUT )
9327       {
9328         ++nbNotOut;
9329         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9330       }
9331     }
9332
9333     // find a NOT_OUT segment of boundary which is located between
9334     // two NOT_OUT int points
9335
9336     if ( nbNotOut < 2 )
9337       continue; // no such a segment
9338
9339     if ( nbNotOut > 2 )
9340     {
9341       // sort points along the boundary
9342       map< double, TIntPntState* > ipsByParam;
9343       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9344       {
9345         TIntPntState & ips1 = intPnts1[ iHP2 ];
9346         if ( ips1.second != NO_INT )
9347         {
9348           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9349           double param = op * halfPlns[ iHP1 ]._dir;
9350           ipsByParam.insert( make_pair( param, & ips1 ));
9351         }
9352       }
9353       // look for two neighboring NOT_OUT points
9354       nbNotOut = 0;
9355       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9356       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9357       {
9358         TIntPntState & ips1 = *(u2ips->second);
9359         if ( ips1.second == NOT_OUT )
9360           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9361         else if ( nbNotOut >= 2 )
9362           break;
9363         else
9364           nbNotOut = 0;
9365       }
9366     }
9367
9368     if ( nbNotOut >= 2 )
9369     {
9370       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9371       sumLen += len;
9372
9373       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9374     }
9375   }
9376
9377   if ( sumLen > 0 )
9378   {
9379     newPos2D /= sumLen;
9380     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9381   }
9382   else
9383   {
9384     newPos = center;
9385   }
9386
9387   return newPos;
9388 }
9389 #else // OLD_NEF_POLYGON
9390 { ////////////////////////////////// NEW
9391   gp_XYZ newPos(0,0,0);
9392
9393   // get a plane to search a solution on
9394
9395   size_t i;
9396   gp_XYZ center(0,0,0);
9397   for ( i = 0; i < _simplices.size(); ++i )
9398     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9399   center /= _simplices.size();
9400
9401   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9402   for ( i = 0; i < _simplices.size(); ++i )
9403     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9404   vecs.back() = vecs[0];
9405
9406   const double tol = numeric_limits<double>::min();
9407   gp_XYZ zAxis(0,0,0);
9408   for ( i = 0; i < _simplices.size(); ++i )
9409   {
9410     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9411     try {
9412       cross.Normalize();
9413       if ( cross * zAxis < tol )
9414         zAxis += cross.Reversed();
9415       else
9416         zAxis += cross;
9417     }
9418     catch (Standard_Failure) { // if |cross| == 0.
9419     }
9420   }
9421
9422   gp_XYZ yAxis;
9423   for ( i = 0; i < _simplices.size(); ++i )
9424   {
9425     yAxis = vecs[i];
9426     if ( yAxis.SquareModulus() > tol )
9427       break;
9428   }
9429   gp_XYZ xAxis = yAxis ^ zAxis;
9430   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9431   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9432   //                             p0.Distance( _simplices[2]._nPrev ));
9433   // gp_XYZ center = smoothLaplacian();
9434   // gp_XYZ xAxis, yAxis, zAxis;
9435   // for ( i = 0; i < _simplices.size(); ++i )
9436   // {
9437   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9438   //   if ( xAxis.SquareModulus() > tol*tol )
9439   //     break;
9440   // }
9441   // for ( i = 1; i < _simplices.size(); ++i )
9442   // {
9443   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9444   //   zAxis = xAxis ^ yAxis;
9445   //   if ( zAxis.SquareModulus() > tol*tol )
9446   //     break;
9447   // }
9448   // if ( i == _simplices.size() ) return newPos;
9449
9450   yAxis = zAxis ^ xAxis;
9451   xAxis /= xAxis.Modulus();
9452   yAxis /= yAxis.Modulus();
9453
9454   // get half-planes of _simplices
9455
9456   vector< _halfPlane > halfPlns( _simplices.size() );
9457   int nbHP = 0;
9458   for ( size_t i = 0; i < _simplices.size(); ++i )
9459   {
9460     const gp_XYZ& OP1 = vecs[ i   ];
9461     const gp_XYZ& OP2 = vecs[ i+1 ];
9462     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9463     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9464     gp_XY  vec12 = p2 - p1;
9465     double dist12 = vec12.Modulus();
9466     if ( dist12 < tol )
9467       continue;
9468     vec12 /= dist12;
9469     halfPlns[ nbHP ]._pos = p1;
9470     halfPlns[ nbHP ]._dir = vec12;
9471     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9472     ++nbHP;
9473   }
9474
9475   // intersect boundaries of half-planes, define state of intersection points
9476   // in relation to all half-planes and calculate internal point of a 2D polygon
9477
9478   double sumLen = 0;
9479   gp_XY newPos2D (0,0);
9480
9481   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9482   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9483   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9484
9485   vector< vector< TIntPntState > > allIntPnts( nbHP );
9486   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9487   {
9488     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9489     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9490
9491     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9492     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9493
9494     int nbNotOut = 0;
9495     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9496
9497     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9498     {
9499       if ( iHP1 == iHP2 ) continue;
9500
9501       TIntPntState & ips1 = intPnts1[ iHP2 ];
9502       if ( ips1.second == UNDEF )
9503       {
9504         // find an intersection point of boundaries of iHP1 and iHP2
9505
9506         if ( iHP2 == iPrev ) // intersection with neighbors is known
9507           ips1.first = halfPlns[ iHP1 ]._pos;
9508         else if ( iHP2 == iNext )
9509           ips1.first = halfPlns[ iHP2 ]._pos;
9510         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9511           ips1.second = NO_INT;
9512
9513         // classify the found intersection point
9514         if ( ips1.second != NO_INT )
9515         {
9516           ips1.second = NOT_OUT;
9517           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9518             if ( i != iHP1 && i != iHP2 &&
9519                  halfPlns[ i ].IsOut( ips1.first, tol ))
9520               ips1.second = IS_OUT;
9521         }
9522         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9523         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9524         TIntPntState & ips2 = intPnts2[ iHP1 ];
9525         ips2 = ips1;
9526       }
9527       if ( ips1.second == NOT_OUT )
9528       {
9529         ++nbNotOut;
9530         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9531       }
9532     }
9533
9534     // find a NOT_OUT segment of boundary which is located between
9535     // two NOT_OUT int points
9536
9537     if ( nbNotOut < 2 )
9538       continue; // no such a segment
9539
9540     if ( nbNotOut > 2 )
9541     {
9542       // sort points along the boundary
9543       map< double, TIntPntState* > ipsByParam;
9544       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9545       {
9546         TIntPntState & ips1 = intPnts1[ iHP2 ];
9547         if ( ips1.second != NO_INT )
9548         {
9549           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9550           double param = op * halfPlns[ iHP1 ]._dir;
9551           ipsByParam.insert( make_pair( param, & ips1 ));
9552         }
9553       }
9554       // look for two neighboring NOT_OUT points
9555       nbNotOut = 0;
9556       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9557       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9558       {
9559         TIntPntState & ips1 = *(u2ips->second);
9560         if ( ips1.second == NOT_OUT )
9561           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9562         else if ( nbNotOut >= 2 )
9563           break;
9564         else
9565           nbNotOut = 0;
9566       }
9567     }
9568
9569     if ( nbNotOut >= 2 )
9570     {
9571       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9572       sumLen += len;
9573
9574       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9575     }
9576   }
9577
9578   if ( sumLen > 0 )
9579   {
9580     newPos2D /= sumLen;
9581     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9582   }
9583   else
9584   {
9585     newPos = center;
9586   }
9587
9588   return newPos;
9589 }
9590 #endif // OLD_NEF_POLYGON
9591
9592 //================================================================================
9593 /*!
9594  * \brief Add a new segment to _LayerEdge during inflation
9595  */
9596 //================================================================================
9597
9598 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9599 {
9600   if ( Is( BLOCKED ))
9601     return;
9602
9603   if ( len > _maxLen )
9604   {
9605     len = _maxLen;
9606     Block( eos.GetData() );
9607   }
9608   const double lenDelta = len - _len;
9609   if ( lenDelta < len * 1e-3  )
9610   {
9611     Block( eos.GetData() );
9612     return;
9613   }
9614
9615   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9616   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9617   gp_XYZ newXYZ;
9618   if ( eos._hyp.IsOffsetMethod() )
9619   {
9620     newXYZ = oldXYZ;
9621     gp_Vec faceNorm;
9622     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9623     while ( faceIt->more() )
9624     {
9625       const SMDS_MeshElement* face = faceIt->next();
9626       if ( !eos.GetNormal( face, faceNorm ))
9627         continue;
9628
9629       // translate plane of a face
9630       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9631
9632       // find point of intersection of the face plane located at baryCenter
9633       // and _normal located at newXYZ
9634       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9635       double dot =  ( faceNorm.XYZ() * _normal );
9636       if ( dot < std::numeric_limits<double>::min() )
9637         dot = lenDelta * 1e-3;
9638       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9639       newXYZ += step * _normal;
9640     }
9641     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9642   }
9643   else
9644   {
9645     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9646   }
9647
9648   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9649   _pos.push_back( newXYZ );
9650
9651   if ( !eos._sWOL.IsNull() )
9652   {
9653     double distXYZ[4];
9654     bool uvOK = false;
9655     if ( eos.SWOLType() == TopAbs_EDGE )
9656     {
9657       double u = Precision::Infinite(); // to force projection w/o distance check
9658       uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u,
9659                                 /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9660       _pos.back().SetCoord( u, 0, 0 );
9661       if ( _nodes.size() > 1 && uvOK )
9662       {
9663         SMDS_EdgePositionPtr pos = n->GetPosition();
9664         pos->SetUParameter( u );
9665       }
9666     }
9667     else //  TopAbs_FACE
9668     {
9669       gp_XY uv( Precision::Infinite(), 0 );
9670       uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv,
9671                                  /*tol=*/2*lenDelta, /*force=*/true, distXYZ );
9672       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
9673       if ( _nodes.size() > 1 && uvOK )
9674       {
9675         SMDS_FacePositionPtr pos = n->GetPosition();
9676         pos->SetUParameter( uv.X() );
9677         pos->SetVParameter( uv.Y() );
9678       }
9679     }
9680     if ( uvOK )
9681     {
9682       n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
9683     }
9684     else
9685     {
9686       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9687       _pos.pop_back();
9688       Block( eos.GetData() );
9689       return;
9690     }
9691   }
9692
9693   _len = len;
9694
9695   // notify _neibors
9696   if ( eos.ShapeType() != TopAbs_FACE )
9697   {
9698     for ( size_t i = 0; i < _neibors.size(); ++i )
9699       //if (  _len > _neibors[i]->GetSmooLen() )
9700         _neibors[i]->Set( MOVED );
9701
9702     Set( MOVED );
9703   }
9704   dumpMove( n ); //debug
9705 }
9706
9707 //================================================================================
9708 /*!
9709  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
9710  */
9711 //================================================================================
9712
9713 void _LayerEdge::Block( _SolidData& data )
9714 {
9715   //if ( Is( BLOCKED )) return;
9716   Set( BLOCKED );
9717
9718   SMESH_Comment msg( "#BLOCK shape=");
9719   msg << data.GetShapeEdges( this )->_shapeID
9720       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
9721   dumpCmd( msg + " -- BEGIN");
9722
9723   SetMaxLen( _len );
9724   std::queue<_LayerEdge*> queue;
9725   queue.push( this );
9726
9727   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
9728   while ( !queue.empty() )
9729   {
9730     _LayerEdge* edge = queue.front(); queue.pop();
9731     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
9732     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
9733     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
9734     {
9735       _LayerEdge* neibor = edge->_neibors[iN];
9736       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
9737         continue;
9738       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
9739       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
9740       double minDist = pSrc.SquareDistance( pSrcN );
9741       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
9742       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
9743       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
9744       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
9745       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
9746       {
9747         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
9748         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
9749         //                   neibor->_lenFactor / edge->_lenFactor );
9750       }
9751       if ( neibor->_maxLen > newMaxLen )
9752       {
9753         neibor->SetMaxLen( newMaxLen );
9754         if ( neibor->_maxLen < neibor->_len )
9755         {
9756           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
9757           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
9758           while ( neibor->_len > neibor->_maxLen &&
9759                   neibor->NbSteps() > lastStep )
9760             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
9761           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
9762           //neibor->Block( data );
9763         }
9764         queue.push( neibor );
9765       }
9766     }
9767   }
9768   dumpCmd( msg + " -- END");
9769 }
9770
9771 //================================================================================
9772 /*!
9773  * \brief Remove last inflation step
9774  */
9775 //================================================================================
9776
9777 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
9778 {
9779   if ( _pos.size() > curStep && _nodes.size() > 1 )
9780   {
9781     _pos.resize( curStep );
9782
9783     gp_Pnt      nXYZ = _pos.back();
9784     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9785     SMESH_TNodeXYZ curXYZ( n );
9786     if ( !eos._sWOL.IsNull() )
9787     {
9788       TopLoc_Location loc;
9789       if ( eos.SWOLType() == TopAbs_EDGE )
9790       {
9791         SMDS_EdgePositionPtr pos = n->GetPosition();
9792         pos->SetUParameter( nXYZ.X() );
9793         double f,l;
9794         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
9795         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
9796       }
9797       else
9798       {
9799         SMDS_FacePositionPtr pos = n->GetPosition();
9800         pos->SetUParameter( nXYZ.X() );
9801         pos->SetVParameter( nXYZ.Y() );
9802         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
9803         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
9804       }
9805     }
9806     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
9807     dumpMove( n );
9808
9809     if ( restoreLength )
9810     {
9811       if ( NbSteps() == 0 )
9812         _len = 0.;
9813       else if ( IsOnFace() && Is( MOVED ))
9814         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
9815       else
9816         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
9817     }
9818   }
9819   return;
9820 }
9821
9822 //================================================================================
9823 /*!
9824  * \brief Return index of a _pos distant from _normal
9825  */
9826 //================================================================================
9827
9828 int _LayerEdge::GetSmoothedPos( const double tol )
9829 {
9830   int iSmoothed = 0;
9831   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
9832   {
9833     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
9834     if ( normDist > tol * tol )
9835       iSmoothed = i;
9836   }
9837   return iSmoothed;
9838 }
9839
9840 //================================================================================
9841 /*!
9842  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
9843  */
9844 //================================================================================
9845
9846 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
9847 {
9848   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
9849     return;
9850
9851   // find the 1st smoothed _pos
9852   int iSmoothed = GetSmoothedPos( tol );
9853   if ( !iSmoothed ) return;
9854
9855   gp_XYZ normal = _normal;
9856   if ( Is( NORMAL_UPDATED ))
9857   {
9858     double minDot = 1;
9859     for ( size_t i = 0; i < _neibors.size(); ++i )
9860     {
9861       if ( _neibors[i]->IsOnFace() )
9862       {
9863         double dot = _normal * _neibors[i]->_normal;
9864         if ( dot < minDot )
9865         {
9866           normal = _neibors[i]->_normal;
9867           minDot = dot;
9868         }
9869       }
9870     }
9871     if ( minDot == 1. )
9872       for ( size_t i = 1; i < _pos.size(); ++i )
9873       {
9874         normal = _pos[i] - _pos[0];
9875         double size = normal.Modulus();
9876         if ( size > RealSmall() )
9877         {
9878           normal /= size;
9879           break;
9880         }
9881       }
9882   }
9883   const double r = 0.2;
9884   for ( int iter = 0; iter < 50; ++iter )
9885   {
9886     double minDot = 1;
9887     for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
9888     {
9889       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
9890       gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
9891       _pos[i] = newPos;
9892       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
9893       double newLen = ( 1-r ) * midLen + r * segLen[i];
9894       const_cast< double& >( segLen[i] ) = newLen;
9895       // check angle between normal and (_pos[i+1], _pos[i] )
9896       gp_XYZ posDir = _pos[i+1] - _pos[i];
9897       double size   = posDir.SquareModulus();
9898       if ( size > RealSmall() )
9899         minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
9900     }
9901     if ( minDot > 0.5 * 0.5 )
9902       break;
9903   }
9904   return;
9905 }
9906
9907 //================================================================================
9908 /*!
9909  * \brief Print flags
9910  */
9911 //================================================================================
9912
9913 std::string _LayerEdge::DumpFlags() const
9914 {
9915   SMESH_Comment dump;
9916   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
9917     if ( _flags & flag )
9918     {
9919       EFlags f = (EFlags) flag;
9920       switch ( f ) {
9921       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
9922       case MOVED:           dump << "MOVED";           break;
9923       case SMOOTHED:        dump << "SMOOTHED";        break;
9924       case DIFFICULT:       dump << "DIFFICULT";       break;
9925       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
9926       case BLOCKED:         dump << "BLOCKED";         break;
9927       case INTERSECTED:     dump << "INTERSECTED";     break;
9928       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
9929       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
9930       case MARKED:          dump << "MARKED";          break;
9931       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
9932       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
9933       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
9934       case DISTORTED:       dump << "DISTORTED";       break;
9935       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
9936       case SHRUNK:          dump << "SHRUNK";          break;
9937       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
9938       }
9939       dump << " ";
9940     }
9941   cout << dump << endl;
9942   return dump;
9943 }
9944
9945
9946 //================================================================================
9947 /*!
9948  * \brief Create layers of prisms
9949  */
9950 //================================================================================
9951
9952 bool _ViscousBuilder::refine(_SolidData& data)
9953 {
9954   SMESH_MesherHelper& helper = data.GetHelper();
9955   helper.SetElementsOnShape(false);
9956
9957   Handle(Geom_Curve) curve;
9958   Handle(ShapeAnalysis_Surface) surface;
9959   TopoDS_Edge geomEdge;
9960   TopoDS_Face geomFace;
9961   TopLoc_Location loc;
9962   double f,l, u = 0;
9963   gp_XY uv;
9964   vector< gp_XYZ > pos3D;
9965   bool isOnEdge, isTooConvexFace = false;
9966   TGeomID prevBaseId = -1;
9967   TNode2Edge* n2eMap = 0;
9968   TNode2Edge::iterator n2e;
9969
9970   // Create intermediate nodes on each _LayerEdge
9971
9972   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
9973   {
9974     _EdgesOnShape& eos = data._edgesOnShape[iS];
9975     if ( eos._edges.empty() ) continue;
9976
9977     if ( eos._edges[0]->_nodes.size() < 2 )
9978       continue; // on _noShrinkShapes
9979
9980     // get data of a shrink shape
9981     isOnEdge = false;
9982     geomEdge.Nullify(); geomFace.Nullify();
9983     curve.Nullify(); surface.Nullify();
9984     if ( !eos._sWOL.IsNull() )
9985     {
9986       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
9987       if ( isOnEdge )
9988       {
9989         geomEdge = TopoDS::Edge( eos._sWOL );
9990         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
9991       }
9992       else
9993       {
9994         geomFace = TopoDS::Face( eos._sWOL );
9995         surface  = helper.GetSurface( geomFace );
9996       }
9997     }
9998     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
9999     {
10000       geomFace = TopoDS::Face( eos._shape );
10001       surface  = helper.GetSurface( geomFace );
10002       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
10003       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
10004         eos._eosC1[ i ]->_toSmooth = true;
10005
10006       isTooConvexFace = false;
10007       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
10008         isTooConvexFace = cf->_isTooCurved;
10009     }
10010
10011     vector< double > segLen;
10012     for ( size_t i = 0; i < eos._edges.size(); ++i )
10013     {
10014       _LayerEdge& edge = *eos._edges[i];
10015       if ( edge._pos.size() < 2 )
10016         continue;
10017
10018       // get accumulated length of segments
10019       segLen.resize( edge._pos.size() );
10020       segLen[0] = 0.0;
10021       if ( eos._sWOL.IsNull() )
10022       {
10023         bool useNormal = true;
10024         bool    usePos = false;
10025         bool  smoothed = false;
10026         double   preci = 0.1 * edge._len;
10027         if ( eos._toSmooth && edge._pos.size() > 2 )
10028         {
10029           smoothed = edge.GetSmoothedPos( preci );
10030         }
10031         if ( smoothed )
10032         {
10033           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10034           {
10035             useNormal = usePos = false;
10036             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10037             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10038             {
10039               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10040               if ( surface->Gap() < 2. * edge._len )
10041                 segLen[j] = surface->Gap();
10042               else
10043                 useNormal = true;
10044             }
10045           }
10046         }
10047         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10048         {
10049 #ifndef __NODES_AT_POS
10050           useNormal = usePos = false;
10051           edge._pos[1] = edge._pos.back();
10052           edge._pos.resize( 2 );
10053           segLen.resize( 2 );
10054           segLen[ 1 ] = edge._len;
10055 #endif
10056         }
10057         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10058         {
10059           useNormal = usePos = false;
10060           _LayerEdge tmpEdge; // get original _normal
10061           tmpEdge._nodes.push_back( edge._nodes[0] );
10062           if ( !setEdgeData( tmpEdge, eos, helper, data ))
10063             usePos = true;
10064           else
10065             for ( size_t j = 1; j < edge._pos.size(); ++j )
10066               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10067         }
10068         if ( useNormal )
10069         {
10070           for ( size_t j = 1; j < edge._pos.size(); ++j )
10071             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10072         }
10073         if ( usePos )
10074         {
10075           for ( size_t j = 1; j < edge._pos.size(); ++j )
10076             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10077         }
10078         else
10079         {
10080           bool swapped = ( edge._pos.size() > 2 );
10081           while ( swapped )
10082           {
10083             swapped = false;
10084             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10085               if ( segLen[j] > segLen.back() )
10086               {
10087                 segLen.erase( segLen.begin() + j );
10088                 edge._pos.erase( edge._pos.begin() + j );
10089                 --j;
10090               }
10091               else if ( segLen[j] < segLen[j-1] )
10092               {
10093                 std::swap( segLen[j], segLen[j-1] );
10094                 std::swap( edge._pos[j], edge._pos[j-1] );
10095                 swapped = true;
10096               }
10097           }
10098         }
10099         // smooth a path formed by edge._pos
10100 #ifndef __NODES_AT_POS
10101         if (( smoothed ) /*&&
10102             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10103           edge.SmoothPos( segLen, preci );
10104 #endif
10105       }
10106       else if ( eos._isRegularSWOL ) // usual SWOL
10107       {
10108         if ( edge.Is( _LayerEdge::SMOOTHED ))
10109         {
10110           SMESH_NodeXYZ p0( edge._nodes[0] );
10111           for ( size_t j = 1; j < edge._pos.size(); ++j )
10112           {
10113             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10114             segLen[j] = ( pj - p0 ) * edge._normal;
10115           }
10116         }
10117         else
10118         {
10119           for ( size_t j = 1; j < edge._pos.size(); ++j )
10120             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10121         }
10122       }
10123       else if ( !surface.IsNull() ) // SWOL surface with singularities
10124       {
10125         pos3D.resize( edge._pos.size() );
10126         for ( size_t j = 0; j < edge._pos.size(); ++j )
10127           pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10128
10129         for ( size_t j = 1; j < edge._pos.size(); ++j )
10130           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10131       }
10132
10133       // allocate memory for new nodes if it is not yet refined
10134       const SMDS_MeshNode* tgtNode = edge._nodes.back();
10135       if ( edge._nodes.size() == 2 )
10136       {
10137 #ifdef __NODES_AT_POS
10138         int nbNodes = edge._pos.size();
10139 #else
10140         int nbNodes = eos._hyp.GetNumberLayers() + 1;
10141 #endif
10142         edge._nodes.resize( nbNodes, 0 );
10143         edge._nodes[1] = 0;
10144         edge._nodes.back() = tgtNode;
10145       }
10146       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10147       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10148       if ( baseShapeId != prevBaseId )
10149       {
10150         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10151         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10152         prevBaseId = baseShapeId;
10153       }
10154       _LayerEdge* edgeOnSameNode = 0;
10155       bool        useExistingPos = false;
10156       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10157       {
10158         edgeOnSameNode = n2e->second;
10159         useExistingPos = ( edgeOnSameNode->_len < edge._len );
10160         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10161         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
10162         if ( isOnEdge )
10163         {
10164           SMDS_EdgePositionPtr epos = lastPos;
10165           epos->SetUParameter( otherTgtPos.X() );
10166         }
10167         else
10168         {
10169           SMDS_FacePositionPtr fpos = lastPos;
10170           fpos->SetUParameter( otherTgtPos.X() );
10171           fpos->SetVParameter( otherTgtPos.Y() );
10172         }
10173       }
10174       // calculate height of the first layer
10175       double h0;
10176       const double T = segLen.back(); //data._hyp.GetTotalThickness();
10177       const double f = eos._hyp.GetStretchFactor();
10178       const int    N = eos._hyp.GetNumberLayers();
10179       const double fPowN = pow( f, N );
10180       if ( fPowN - 1 <= numeric_limits<double>::min() )
10181         h0 = T / N;
10182       else
10183         h0 = T * ( f - 1 )/( fPowN - 1 );
10184
10185       const double zeroLen = std::numeric_limits<double>::min();
10186
10187       // create intermediate nodes
10188       double hSum = 0, hi = h0/f;
10189       size_t iSeg = 1;
10190       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10191       {
10192         // compute an intermediate position
10193         hi *= f;
10194         hSum += hi;
10195         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10196           ++iSeg;
10197         int iPrevSeg = iSeg-1;
10198         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10199           --iPrevSeg;
10200         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10201         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10202 #ifdef __NODES_AT_POS
10203         pos = edge._pos[ iStep ];
10204 #endif
10205         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10206         if ( !eos._sWOL.IsNull() )
10207         {
10208           // compute XYZ by parameters <pos>
10209           if ( isOnEdge )
10210           {
10211             u = pos.X();
10212             if ( !node )
10213               pos = curve->Value( u ).Transformed(loc);
10214           }
10215           else if ( eos._isRegularSWOL )
10216           {
10217             uv.SetCoord( pos.X(), pos.Y() );
10218             if ( !node )
10219               pos = surface->Value( pos.X(), pos.Y() );
10220           }
10221           else
10222           {
10223             uv.SetCoord( pos.X(), pos.Y() );
10224             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10225             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10226             if ( !node )
10227               pos = surface->Value( uv );
10228           }
10229         }
10230         // create or update the node
10231         if ( !node )
10232         {
10233           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10234           if ( !eos._sWOL.IsNull() )
10235           {
10236             if ( isOnEdge )
10237               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10238             else
10239               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10240           }
10241           else
10242           {
10243             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10244           }
10245         }
10246         else
10247         {
10248           if ( !eos._sWOL.IsNull() )
10249           {
10250             // make average pos from new and current parameters
10251             if ( isOnEdge )
10252             {
10253               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10254               if ( useExistingPos )
10255                 u = helper.GetNodeU( geomEdge, node );
10256               pos = curve->Value( u ).Transformed(loc);
10257
10258               SMDS_EdgePositionPtr epos = node->GetPosition();
10259               epos->SetUParameter( u );
10260             }
10261             else
10262             {
10263               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10264               if ( useExistingPos )
10265                 uv = helper.GetNodeUV( geomFace, node );
10266               pos = surface->Value( uv );
10267
10268               SMDS_FacePositionPtr fpos = node->GetPosition();
10269               fpos->SetUParameter( uv.X() );
10270               fpos->SetVParameter( uv.Y() );
10271             }
10272           }
10273           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10274         }
10275       } // loop on edge._nodes
10276
10277       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10278       {
10279         if ( isOnEdge )
10280           edge._pos.back().SetCoord( u, 0,0);
10281         else
10282           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10283
10284         if ( edgeOnSameNode )
10285           edgeOnSameNode->_pos.back() = edge._pos.back();
10286       }
10287
10288     } // loop on eos._edges to create nodes
10289
10290
10291     if ( !getMeshDS()->IsEmbeddedMode() )
10292       // Log node movement
10293       for ( size_t i = 0; i < eos._edges.size(); ++i )
10294       {
10295         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10296         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10297       }
10298   }
10299
10300
10301   // Create volumes
10302
10303   helper.SetElementsOnShape(true);
10304
10305   vector< vector<const SMDS_MeshNode*>* > nnVec;
10306   set< vector<const SMDS_MeshNode*>* >    nnSet;
10307   set< int >                       degenEdgeInd;
10308   vector<const SMDS_MeshElement*>     degenVols;
10309
10310   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10311   for ( ; exp.More(); exp.Next() )
10312   {
10313     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10314     if ( data._ignoreFaceIds.count( faceID ))
10315       continue;
10316     _EdgesOnShape*    eos = data.GetShapeEdges( faceID );
10317     SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10318                                                                    *helper.GetMesh(),
10319                                                                    SMDSAbs_Volume );
10320     std::vector< const SMDS_MeshElement* > vols;
10321     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10322     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10323     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10324     while ( fIt->more() )
10325     {
10326       const SMDS_MeshElement* face = fIt->next();
10327       const int            nbNodes = face->NbCornerNodes();
10328       nnVec.resize( nbNodes );
10329       nnSet.clear();
10330       degenEdgeInd.clear();
10331       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10332       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10333       for ( int iN = 0; iN < nbNodes; ++iN )
10334       {
10335         const SMDS_MeshNode* n = nIt->next();
10336         _LayerEdge*       edge = data._n2eMap[ n ];
10337         const int i = isReversedFace ? nbNodes-1-iN : iN;
10338         nnVec[ i ] = & edge->_nodes;
10339         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10340         minZ = std::min( minZ, nnVec[ i ]->size() );
10341
10342         if ( helper.HasDegeneratedEdges() )
10343           nnSet.insert( nnVec[ i ]);
10344       }
10345
10346       if ( maxZ == 0 )
10347         continue;
10348       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10349         continue;
10350
10351       vols.clear();
10352       const SMDS_MeshElement* vol;
10353
10354       switch ( nbNodes )
10355       {
10356       case 3: // TRIA
10357       {
10358         // PENTA
10359         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10360         {
10361           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10362                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10363           vols.push_back( vol );
10364         }
10365
10366         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10367         {
10368           for ( int iN = 0; iN < nbNodes; ++iN )
10369             if ( nnVec[ iN ]->size() < iZ+1 )
10370               degenEdgeInd.insert( iN );
10371
10372           if ( degenEdgeInd.size() == 1 )  // PYRAM
10373           {
10374             int i2 = *degenEdgeInd.begin();
10375             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10376             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10377             vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10378                                     (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10379             vols.push_back( vol );
10380           }
10381           else  // TETRA
10382           {
10383             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10384             vol = helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10385                                     (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10386                                     (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10387                                     (*nnVec[ i3 ])[ iZ ]);
10388             vols.push_back( vol );
10389           }
10390         }
10391         break; // TRIA
10392       }
10393       case 4: // QUAD
10394       {
10395         // HEX
10396         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10397         {
10398           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10399                                   (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10400                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10401                                   (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10402           vols.push_back( vol );
10403         }
10404
10405         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10406         {
10407           for ( int iN = 0; iN < nbNodes; ++iN )
10408             if ( nnVec[ iN ]->size() < iZ+1 )
10409               degenEdgeInd.insert( iN );
10410
10411           switch ( degenEdgeInd.size() )
10412           {
10413           case 2: // PENTA
10414           {
10415             int i2 = *degenEdgeInd.begin();
10416             int i3 = *degenEdgeInd.rbegin();
10417             bool ok = ( i3 - i2 == 1 );
10418             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10419             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10420             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10421
10422             vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10423                                     nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10424             vols.push_back( vol );
10425             if ( !ok && vol )
10426               degenVols.push_back( vol );
10427           }
10428           break;
10429
10430           default: // degen HEX
10431           {
10432             vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10433                                     nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10434                                     nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10435                                     nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10436                                     nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10437                                     nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10438                                     nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10439                                     nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10440             vols.push_back( vol );
10441             degenVols.push_back( vol );
10442           }
10443           }
10444         }
10445         break; // HEX
10446       }
10447       default:
10448         return error("Not supported type of element", data._index);
10449
10450       } // switch ( nbNodes )
10451
10452       if ( group )
10453         for ( size_t i = 0; i < vols.size(); ++i )
10454           group->Add( vols[ i ]);
10455
10456     } // while ( fIt->more() )
10457   } // loop on FACEs
10458
10459   if ( !degenVols.empty() )
10460   {
10461     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10462     if ( !err || err->IsOK() )
10463     {
10464       SMESH_BadInputElements* badElems =
10465         new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10466       badElems->myBadElements.insert( badElems->myBadElements.end(),
10467                                       degenVols.begin(),degenVols.end() );
10468       err.reset( badElems );
10469     }
10470   }
10471
10472   return true;
10473 }
10474
10475 namespace VISCOUS_3D
10476 {
10477   struct ShrinkFace;
10478   //--------------------------------------------------------------------------------
10479   /*!
10480    * \brief Pair of periodic FACEs
10481    */
10482   struct PeriodicFaces
10483   {
10484     typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10485
10486     ShrinkFace*  _shriFace[2];
10487     TNodeNodeMap _nnMap;
10488     Trsf         _trsf;
10489
10490     PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10491     bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10492     bool MoveNodes( const TopoDS_Face& tgtFace );
10493     void Clear() { _nnMap.clear(); }
10494     bool IsEmpty() const { return _nnMap.empty(); }
10495   };
10496
10497   //--------------------------------------------------------------------------------
10498   /*!
10499    * \brief Shrink FACE data used to find periodic FACEs
10500    */
10501   struct ShrinkFace
10502   {
10503     // ................................................................................
10504     struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10505     {
10506       bool                         _isShrink, _isReverse;
10507       int                          _nbSegments;
10508       AverageHyp*                  _hyp;
10509       std::vector< SMESH_NodeXYZ > _nodes;
10510       TopAbs_ShapeEnum             _vertSWOLType[2]; // shrink part includes VERTEXes
10511       AverageHyp*                  _vertHyp[2];
10512
10513       BndPart():
10514         _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10515         _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }
10516       {}
10517
10518       bool operator==( const BndPart& other ) const
10519       {
10520         return ( _isShrink       == other._isShrink &&
10521                  _nbSegments     == other._nbSegments &&
10522                  _nodes.size()   == other._nodes.size() &&
10523                  vertSWOLType1() == other.vertSWOLType1() &&
10524                  vertSWOLType2() == other.vertSWOLType2() &&
10525                  (( !_isShrink ) ||
10526                   ( *_hyp        == *other._hyp &&
10527                     vertHyp1()   == other.vertHyp1() &&
10528                     vertHyp2()   == other.vertHyp2() ))
10529                  );
10530       }
10531       bool CanAppend( const BndPart& other )
10532       {
10533         return ( _isShrink  == other._isShrink  &&
10534                  (( !_isShrink ) ||
10535                   ( *_hyp        == *other._hyp &&
10536                     *_hyp        == vertHyp2()  &&
10537                     vertHyp2()   == other.vertHyp1() ))
10538                  );
10539       }
10540       void Append( const BndPart& other )
10541       {
10542         _nbSegments += other._nbSegments;
10543         bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10544         _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10545         _vertSWOLType[1] = other._vertSWOLType[1];
10546         if ( _isShrink )
10547           _vertHyp[1] = other._vertHyp[1];
10548       }
10549       const SMDS_MeshNode*    Node(size_t i)  const
10550       {
10551         return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10552       }
10553       void Reverse() { _isReverse = !_isReverse; }
10554       const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse  ]; }
10555       const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10556       const AverageHyp&       vertHyp1()      const { return *(_vertHyp[ _isReverse  ]); }
10557       const AverageHyp&       vertHyp2()      const { return *(_vertHyp[ !_isReverse ]); }
10558     };
10559     // ................................................................................
10560
10561     SMESH_subMesh*       _subMesh;
10562     _SolidData*          _data1;
10563     _SolidData*          _data2;
10564     //bool                 _isPeriodic;
10565
10566     std::list< BndPart > _boundary;
10567     int                  _boundarySize, _nbBoundaryParts;
10568
10569     void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10570     {
10571       _subMesh = sm; _data1 = sd1; _data2 = sd2; //_isPeriodic = false;
10572     }
10573     bool IsSame( const TopoDS_Face& face ) const
10574     {
10575       return _subMesh->GetSubShape().IsSame( face );
10576     }
10577     bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10578     {
10579       return shrunkFaces.Contains( _subMesh->GetSubShape() );
10580     }
10581
10582     //================================================================================
10583     /*!
10584      * Check if meshes on two FACEs are equal
10585      */
10586     bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10587     {
10588       if ( !IsSameNbElements( other ))
10589         return false;
10590
10591       this->SetBoundary();
10592       other.SetBoundary();
10593       if ( this->_boundarySize    != other._boundarySize ||
10594            this->_nbBoundaryParts != other._nbBoundaryParts )
10595         return false;
10596
10597       for ( int isReverse = 0; isReverse < 2; ++isReverse )
10598       {
10599         if ( isReverse )
10600           Reverse( _boundary );
10601
10602         // check boundaries
10603         bool equalBoundary = false;
10604         for ( int iP = 0; iP < _nbBoundaryParts &&  !equalBoundary; ++iP )
10605         {
10606           if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10607             // set first part at end
10608             _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10609         }
10610         if ( !equalBoundary )
10611           continue;
10612
10613         // check connectivity
10614         std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10615         this->GetElements( elemsThis  );
10616         other.GetElements( elemsOther );
10617         SMESH_MeshEditor::Sew_Error err =
10618           SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10619                                                this->_boundary.front().Node(0),
10620                                                other._boundary.front().Node(0),
10621                                                this->_boundary.front().Node(1),
10622                                                other._boundary.front().Node(1),
10623                                                periodic._nnMap );
10624         if ( err != SMESH_MeshEditor::SEW_OK )
10625           continue;
10626
10627         // check node positions
10628         std::vector< gp_XYZ > srcPnts, tgtPnts;
10629         this->GetBoundaryPoints( srcPnts );
10630         other.GetBoundaryPoints( tgtPnts );
10631         if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10632           continue;
10633         }
10634         double tol = std::numeric_limits<double>::max();
10635         for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10636           tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10637         }
10638         tol = 0.01 * Sqrt( tol );
10639         bool nodeCoincide = true;
10640         TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10641         for ( ; n2n != periodic._nnMap.end() &&  nodeCoincide; ++n2n )
10642         {
10643           SMESH_NodeXYZ nSrc = n2n->first;
10644           SMESH_NodeXYZ nTgt = n2n->second;
10645           gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
10646           nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol );
10647         }
10648         if ( nodeCoincide )
10649           return true;
10650       }
10651       return false;
10652     }
10653
10654     bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
10655     {
10656       SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
10657       SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
10658       return ( sm1->NbElements() == sm2->NbElements() &&
10659                sm1->NbNodes()    == sm2->NbNodes() );
10660     }
10661
10662     void Reverse( std::list< BndPart >& boundary )
10663     {
10664       boundary.reverse();
10665       for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
10666         part->Reverse();
10667     }
10668
10669     void SetBoundary()
10670     {
10671       if ( !_boundary.empty() )
10672         return;
10673
10674       TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
10675       if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
10676       std::list< TopoDS_Edge > edges;
10677       std::list< int > nbEdgesInWire;
10678       /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
10679
10680       // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
10681       // if ( nbWires > 1 ) {
10682       //   edgesEnd = edges.begin();
10683       //   std::advance( edgesEnd, nbEdgesInWire.front() );
10684       // }
10685       StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
10686                                  /*fwd=*/true, /*skipMedium=*/true );
10687       _boundarySize = fSide.NbSegments();
10688
10689       //TopoDS_Vertex vv[2];
10690       //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
10691       for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
10692       {
10693         BndPart bndPart;
10694         _EdgesOnShape*  eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
10695
10696         bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
10697         if ( bndPart._isShrink )
10698           if ((           _data1->_noShrinkShapes.count( eos->_shapeID )) ||
10699               ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
10700             bndPart._isShrink = false;
10701
10702         if ( bndPart._isShrink )
10703         {
10704           bndPart._hyp = & eos->_hyp;
10705           _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
10706                                     _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
10707           for ( int iV = 0; iV < 2; ++iV )
10708           {
10709             bndPart._vertHyp     [iV] = & eov[iV]->_hyp;
10710             bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10711             if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
10712               bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10713             if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
10714             {
10715               eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
10716               if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
10717                 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
10718               else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
10719                 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
10720             }
10721           }
10722         }
10723         std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
10724         bndPart._nodes.assign( nodes.begin(), nodes.end() );
10725         bndPart._nbSegments = bndPart._nodes.size() - 1;
10726
10727         if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
10728           _boundary.push_back( bndPart );
10729         else
10730           _boundary.back().Append( bndPart );
10731       }
10732
10733       _nbBoundaryParts = _boundary.size();
10734       if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
10735       {
10736         _boundary.back().Append( _boundary.front() );
10737         _boundary.pop_front();
10738         --_nbBoundaryParts;
10739       }
10740     }
10741
10742     void GetElements( std::set<const SMDS_MeshElement*>& theElems)
10743     {
10744       if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
10745         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
10746           theElems.insert( theElems.end(), fIt->next() );
10747
10748       return ;
10749     }
10750
10751     void GetBoundaryPoints( std::vector< gp_XYZ >& points )
10752     {
10753       points.reserve( _boundarySize );
10754       size_t  nb = _boundary.rbegin()->_nodes.size();
10755       smIdType lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
10756       std::list< BndPart >::const_iterator part = _boundary.begin();
10757       for ( ; part != _boundary.end(); ++part )
10758       {
10759         size_t nb = part->_nodes.size();
10760         size_t iF = 0;
10761         size_t iR = nb - 1;
10762         size_t* i = part->_isReverse ? &iR : &iF;
10763         if ( part->_nodes[ *i ]->GetID() == lastID )
10764           ++iF, --iR;
10765         for ( ; iF < nb; ++iF, --iR )
10766           points.push_back( part->_nodes[ *i ]);
10767         --iF, ++iR;
10768         lastID = part->_nodes[ *i ]->GetID();
10769       }
10770     }
10771   }; // struct ShrinkFace
10772
10773   //--------------------------------------------------------------------------------
10774   /*!
10775    * \brief Periodic FACEs
10776    */
10777   struct Periodicity
10778   {
10779     std::vector< ShrinkFace >    _shrinkFaces;
10780     std::vector< PeriodicFaces > _periodicFaces;
10781
10782     PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
10783     {
10784       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10785         if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
10786           return & _periodicFaces[ i ];
10787       return 0;
10788     }
10789     void ClearPeriodic( const TopoDS_Face& face )
10790     {
10791       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
10792         if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
10793              _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
10794           _periodicFaces[ i ].Clear();
10795     }
10796   };
10797
10798   //================================================================================
10799   /*!
10800    * Check if a pair includes the given FACE and the other FACE is already shrunk
10801    */
10802   bool PeriodicFaces::IncludeShrunk( const TopoDS_Face&         face,
10803                                      const TopTools_MapOfShape& shrunkFaces ) const
10804   {
10805     if ( IsEmpty() ) return false;
10806     return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
10807             ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
10808   }
10809
10810   //================================================================================
10811   /*!
10812    * Make equal meshes on periodic faces by moving corresponding nodes
10813    */
10814   bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
10815   {
10816     int iTgt = _shriFace[1]->IsSame( tgtFace );
10817     int iSrc = 1 - iTgt;
10818
10819     _SolidData* dataSrc = _shriFace[iSrc]->_data1;
10820     _SolidData* dataTgt = _shriFace[iTgt]->_data1;
10821
10822     Trsf * trsf = & _trsf, trsfInverse;
10823     if ( iSrc != 0 )
10824     {
10825       trsfInverse = _trsf;
10826       if ( !trsfInverse.Invert())
10827         return false;
10828       trsf = &trsfInverse;
10829     }
10830     SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
10831
10832     TNode2Edge::iterator n2e;
10833     TNodeNodeMap::iterator n2n = _nnMap.begin();
10834     for ( ; n2n != _nnMap.end(); ++n2n )
10835     {
10836       const SMDS_MeshNode* const* nn = & n2n->first;
10837       const SMDS_MeshNode*      nSrc = nn[ iSrc ];
10838       const SMDS_MeshNode*      nTgt = nn[ iTgt ];
10839
10840       if (( nSrc->GetPosition()->GetDim() == 2 ) ||
10841           (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
10842       {
10843         SMESH_NodeXYZ pSrc = nSrc;
10844         gp_XYZ pTgt = trsf->Transform( pSrc );
10845         meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
10846       }
10847       else
10848       {
10849         _LayerEdge* leSrc = n2e->second;
10850         n2e = dataTgt->_n2eMap.find( nTgt );
10851         if ( n2e == dataTgt->_n2eMap.end() )
10852           break;
10853         _LayerEdge* leTgt = n2e->second;
10854         if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
10855           break;
10856         for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
10857         {
10858           SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
10859           gp_XYZ pTgt = trsf->Transform( pSrc );
10860           meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
10861         }
10862       }
10863     }
10864     bool done = ( n2n == _nnMap.end() );
10865     debugMsg( "PeriodicFaces::MoveNodes "
10866               << _shriFace[iSrc]->_subMesh->GetId() << " -> "
10867               << _shriFace[iTgt]->_subMesh->GetId() << " -- "
10868               << ( done ? "DONE" : "FAIL"));
10869
10870     return done;
10871   }
10872 } // namespace VISCOUS_3D; Periodicity part
10873
10874
10875 //================================================================================
10876 /*!
10877  * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
10878  *        and should remain equal after shrink
10879  */
10880 //================================================================================
10881
10882 void _ViscousBuilder::findPeriodicFaces()
10883 {
10884   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10885   // _LayerEdge's inflated along FACE or EDGE)
10886   std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
10887   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10888   {
10889     _SolidData& data = _sdVec[i];
10890     std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10891     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10892       if ( s2s->second.ShapeType() == TopAbs_FACE )
10893         id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10894   }
10895
10896   _periodicity.reset( new Periodicity );
10897   _periodicity->_shrinkFaces.resize( id2sdMap.size() );
10898
10899   std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
10900   for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
10901   {
10902     _SolidData* sd1 = id2sdIt->second.front();
10903     _SolidData* sd2 = id2sdIt->second.back();
10904     _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
10905   }
10906
10907   for (   size_t i1 = 0;      i1 < _periodicity->_shrinkFaces.size(); ++i1 )
10908     for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
10909     {
10910       PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
10911                         & _periodicity->_shrinkFaces[ i2 ]);
10912       if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
10913       {
10914         _periodicity->_periodicFaces.push_back( pf );
10915       }
10916     }
10917   return;
10918 }
10919
10920 //================================================================================
10921 /*!
10922  * \brief Shrink 2D mesh on faces to let space for inflated layers
10923  */
10924 //================================================================================
10925
10926 bool _ViscousBuilder::shrink(_SolidData& theData)
10927 {
10928   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
10929   // _LayerEdge's inflated along FACE or EDGE)
10930   map< TGeomID, list< _SolidData* > > f2sdMap;
10931   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
10932   {
10933     _SolidData& data = _sdVec[i];
10934     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
10935     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
10936       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
10937       {
10938         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
10939
10940         // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
10941         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
10942         // by StdMeshers_QuadToTriaAdaptor
10943         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
10944         {
10945           SMESH_ProxyMesh::SubMesh* proxySub =
10946             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
10947           if ( proxySub->NbElements() == 0 )
10948           {
10949             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
10950             while ( fIt->more() )
10951             {
10952               const SMDS_MeshElement* f = fIt->next();
10953               // as a result 3D algo will use elements from proxySub and not from smDS
10954               proxySub->AddElement( f );
10955               f->setIsMarked( true );
10956
10957               // Mark nodes on the FACE to discriminate them from nodes
10958               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
10959               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
10960               {
10961                 const SMDS_MeshNode* n = f->GetNode( iN );
10962                 if ( n->GetPosition()->GetDim() == 2 )
10963                   n->setIsMarked( true );
10964               }
10965             }
10966           }
10967         }
10968       }
10969   }
10970
10971   SMESH_MesherHelper helper( *_mesh );
10972   helper.ToFixNodeParameters( true );
10973
10974   // EDGEs to shrink
10975   map< TGeomID, _Shrinker1D > e2shrMap;
10976   vector< _EdgesOnShape* > subEOS;
10977   vector< _LayerEdge* > lEdges;
10978
10979   // loop on FACEs to shrink mesh on
10980   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
10981   for ( ; f2sd != f2sdMap.end(); ++f2sd )
10982   {
10983     list< _SolidData* > & dataList = f2sd->second;
10984     if ( dataList.front()->_n2eMap.empty() ||
10985          dataList.back() ->_n2eMap.empty() )
10986       continue; // not yet computed
10987     if ( dataList.front() != &theData &&
10988          dataList.back()  != &theData )
10989       continue;
10990
10991     _SolidData&      data = *dataList.front();
10992     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
10993     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
10994     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
10995     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
10996
10997     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
10998
10999     _shrunkFaces.Add( F );
11000     helper.SetSubShape( F );
11001
11002     // ==============================
11003     // Use periodicity to move nodes
11004     // ==============================
11005
11006     PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
11007     bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
11008
11009     // ===========================
11010     // Prepare data for shrinking
11011     // ===========================
11012
11013     // Collect nodes to smooth (they are marked at the beginning of this method)
11014     vector < const SMDS_MeshNode* > smoothNodes;
11015
11016     if ( !movedByPeriod )
11017     {
11018       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11019       while ( nIt->more() )
11020       {
11021         const SMDS_MeshNode* n = nIt->next();
11022         if ( n->isMarked() )
11023           smoothNodes.push_back( n );
11024       }
11025     }
11026     // Find out face orientation
11027     double refSign = 1;
11028     const set<TGeomID> ignoreShapes;
11029     bool isOkUV;
11030     if ( !smoothNodes.empty() )
11031     {
11032       vector<_Simplex> simplices;
11033       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11034       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11035       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11036       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11037       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11038         refSign = -1;
11039     }
11040
11041     // Find _LayerEdge's inflated along F
11042     subEOS.clear();
11043     lEdges.clear();
11044     {
11045       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11046                                                                 /*complexFirst=*/true); //!!!
11047       while ( subIt->more() )
11048       {
11049         const TGeomID subID = subIt->next()->GetId();
11050         if ( data._noShrinkShapes.count( subID ))
11051           continue;
11052         _EdgesOnShape* eos = data.GetShapeEdges( subID );
11053         if ( !eos || eos->_sWOL.IsNull() )
11054           if ( data2 ) // check in adjacent SOLID
11055           {
11056             eos = data2->GetShapeEdges( subID );
11057             if ( !eos || eos->_sWOL.IsNull() )
11058               continue;
11059           }
11060         subEOS.push_back( eos );
11061
11062         if ( !movedByPeriod )
11063           for ( size_t i = 0; i < eos->_edges.size(); ++i )
11064           {
11065             lEdges.push_back( eos->_edges[ i ] );
11066             prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11067           }
11068       }
11069     }
11070
11071     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11072     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11073     while ( fIt->more() )
11074       if ( const SMDS_MeshElement* f = fIt->next() )
11075         dumpChangeNodes( f );
11076     dumpFunctionEnd();
11077
11078     // Replace source nodes by target nodes in mesh faces to shrink
11079     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11080     const SMDS_MeshNode* nodes[20];
11081     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11082     {
11083       _EdgesOnShape& eos = * subEOS[ iS ];
11084       for ( size_t i = 0; i < eos._edges.size(); ++i )
11085       {
11086         _LayerEdge& edge = *eos._edges[i];
11087         const SMDS_MeshNode* srcNode = edge._nodes[0];
11088         const SMDS_MeshNode* tgtNode = edge._nodes.back();
11089         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11090         while ( fIt->more() )
11091         {
11092           const SMDS_MeshElement* f = fIt->next();
11093           if ( !smDS->Contains( f ) || !f->isMarked() )
11094             continue;
11095           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11096           for ( int iN = 0; nIt->more(); ++iN )
11097           {
11098             const SMDS_MeshNode* n = nIt->next();
11099             nodes[iN] = ( n == srcNode ? tgtNode : n );
11100           }
11101           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11102           dumpChangeNodes( f );
11103         }
11104       }
11105     }
11106     dumpFunctionEnd();
11107
11108     // find out if a FACE is concave
11109     const bool isConcaveFace = isConcave( F, helper );
11110
11111     // Create _SmoothNode's on face F
11112     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11113     {
11114       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11115       const bool sortSimplices = isConcaveFace;
11116       for ( size_t i = 0; i < smoothNodes.size(); ++i )
11117       {
11118         const SMDS_MeshNode* n = smoothNodes[i];
11119         nodesToSmooth[ i ]._node = n;
11120         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11121         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11122         // fix up incorrect uv of nodes on the FACE
11123         helper.GetNodeUV( F, n, 0, &isOkUV);
11124         dumpMove( n );
11125       }
11126       dumpFunctionEnd();
11127     }
11128     //if ( nodesToSmooth.empty() ) continue;
11129
11130     // Find EDGE's to shrink and set simpices to LayerEdge's
11131     set< _Shrinker1D* > eShri1D;
11132     {
11133       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11134       {
11135         _EdgesOnShape& eos = * subEOS[ iS ];
11136         if ( eos.SWOLType() == TopAbs_EDGE )
11137         {
11138           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11139           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11140           if ( !movedByPeriod )
11141           {
11142             _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11143             eShri1D.insert( & shrinker );
11144             shrinker.AddEdge( eos._edges[0], eos, helper );
11145             // restore params of nodes on EDGE if the EDGE has been already
11146             // shrunk while shrinking other FACE
11147             shrinker.RestoreParams();
11148           }
11149         }
11150         for ( size_t i = 0; i < eos._edges.size(); ++i )
11151         {
11152           _LayerEdge& edge = * eos._edges[i];
11153           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11154
11155           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11156           // not-marked nodes are those added by refine()
11157           edge._nodes.back()->setIsMarked( true );
11158         }
11159       }
11160     }
11161
11162     bool toFixTria = false; // to improve quality of trias by diagonal swap
11163     if ( isConcaveFace && !movedByPeriod )
11164     {
11165       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11166       if ( hasTria != hasQuad ) {
11167         toFixTria = hasTria;
11168       }
11169       else {
11170         set<int> nbNodesSet;
11171         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11172         while ( fIt->more() && nbNodesSet.size() < 2 )
11173           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11174         toFixTria = ( *nbNodesSet.begin() == 3 );
11175       }
11176     }
11177
11178     // ==================
11179     // Perform shrinking
11180     // ==================
11181
11182     bool shrunk = !movedByPeriod;
11183     int nbBad, shriStep=0, smooStep=0;
11184     _SmoothNode::SmoothType smoothType
11185       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11186     SMESH_Comment errMsg;
11187     while ( shrunk )
11188     {
11189       shriStep++;
11190       // Move boundary nodes (actually just set new UV)
11191       // -----------------------------------------------
11192       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11193       shrunk = false;
11194       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11195       {
11196         _EdgesOnShape& eos = * subEOS[ iS ];
11197         for ( size_t i = 0; i < eos._edges.size(); ++i )
11198         {
11199           shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11200         }
11201       }
11202       dumpFunctionEnd();
11203
11204       // Move nodes on EDGE's
11205       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11206       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11207       for ( ; shr != eShri1D.end(); ++shr )
11208         (*shr)->Compute( /*set3D=*/false, helper );
11209
11210       // Smoothing in 2D
11211       // -----------------
11212       int nbNoImpSteps = 0;
11213       bool       moved = true;
11214       nbBad = 1;
11215       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11216       {
11217         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11218
11219         int oldBadNb = nbBad;
11220         nbBad = 0;
11221         moved = false;
11222         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11223         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11224         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11225         {
11226           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11227                                             smooTy, /*set3D=*/isConcaveFace);
11228         }
11229         if ( nbBad < oldBadNb )
11230           nbNoImpSteps = 0;
11231         else
11232           nbNoImpSteps++;
11233
11234         dumpFunctionEnd();
11235       }
11236
11237       errMsg.clear();
11238       if ( nbBad > 0 )
11239         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11240       if ( shriStep > 200 )
11241         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11242       if ( !errMsg.empty() )
11243         break;
11244
11245       // Fix narrow triangles by swapping diagonals
11246       // ---------------------------------------
11247       if ( toFixTria )
11248       {
11249         set<const SMDS_MeshNode*> usedNodes;
11250         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11251
11252         // update working data
11253         set<const SMDS_MeshNode*>::iterator n;
11254         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11255         {
11256           n = usedNodes.find( nodesToSmooth[ i ]._node );
11257           if ( n != usedNodes.end())
11258           {
11259             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11260                                     nodesToSmooth[ i ]._simplices,
11261                                     ignoreShapes, NULL,
11262                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11263             usedNodes.erase( n );
11264           }
11265         }
11266         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11267         {
11268           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11269           if ( n != usedNodes.end())
11270           {
11271             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11272                                     lEdges[i]->_simplices,
11273                                     ignoreShapes );
11274             usedNodes.erase( n );
11275           }
11276         }
11277       }
11278       // TODO: check effect of this additional smooth
11279       // additional laplacian smooth to increase allowed shrink step
11280       // for ( int st = 1; st; --st )
11281       // {
11282       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11283       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11284       //   {
11285       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11286       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
11287       //   }
11288       // }
11289
11290     } // while ( shrunk )
11291
11292     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11293     {
11294       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11295
11296       // remove faces
11297       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11298       {
11299         vector< const SMDS_MeshElement* > facesToRm;
11300         if ( psm )
11301         {
11302           facesToRm.reserve( psm->NbElements() );
11303           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11304             facesToRm.push_back( ite->next() );
11305
11306           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11307             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11308               psm->Clear();
11309         }
11310         for ( size_t i = 0; i < facesToRm.size(); ++i )
11311           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11312       }
11313       // remove nodes
11314       {
11315         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11316         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11317           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11318             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11319                                 subEOS[iS]->_edges[i]->_nodes.end() );
11320         }
11321         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11322         while ( itn->more() ) {
11323           const SMDS_MeshNode* n = itn->next();
11324           if ( !nodesToKeep.count( n ))
11325             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11326         }
11327       }
11328       _periodicity->ClearPeriodic( F );
11329
11330       // restore position and UV of target nodes
11331       gp_Pnt p;
11332       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11333         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11334         {
11335           _LayerEdge*       edge = subEOS[iS]->_edges[i];
11336           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11337           if ( edge->_pos.empty() ||
11338                edge->Is( _LayerEdge::SHRUNK )) continue;
11339           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11340           {
11341             SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11342             pos->SetUParameter( edge->_pos[0].X() );
11343             pos->SetVParameter( edge->_pos[0].Y() );
11344             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11345           }
11346           else
11347           {
11348             SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11349             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11350             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11351           }
11352           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11353           dumpMove( tgtNode );
11354         }
11355       // shrink EDGE sub-meshes and set proxy sub-meshes
11356       UVPtStructVec uvPtVec;
11357       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11358       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11359       {
11360         _Shrinker1D* shr = (*shrIt);
11361         shr->Compute( /*set3D=*/true, helper );
11362
11363         // set proxy mesh of EDGEs w/o layers
11364         map< double, const SMDS_MeshNode* > nodes;
11365         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11366         // remove refinement nodes
11367         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11368         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11369         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11370         if ( u2n->second == sn0 || u2n->second == sn1 )
11371         {
11372           while ( u2n->second != tn0 && u2n->second != tn1 )
11373             ++u2n;
11374           nodes.erase( nodes.begin(), u2n );
11375         }
11376         u2n = --nodes.end();
11377         if ( u2n->second == sn0 || u2n->second == sn1 )
11378         {
11379           while ( u2n->second != tn0 && u2n->second != tn1 )
11380             --u2n;
11381           nodes.erase( ++u2n, nodes.end() );
11382         }
11383         // set proxy sub-mesh
11384         uvPtVec.resize( nodes.size() );
11385         u2n = nodes.begin();
11386         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11387         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11388         {
11389           uvPtVec[ i ].node = u2n->second;
11390           uvPtVec[ i ].param = u2n->first;
11391           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11392         }
11393         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11394         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11395       }
11396
11397       // set proxy mesh of EDGEs with layers
11398       vector< _LayerEdge* > edges;
11399       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11400       {
11401         _EdgesOnShape& eos = * subEOS[ iS ];
11402         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11403
11404         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11405         data.SortOnEdge( E, eos._edges );
11406
11407         edges.clear();
11408         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11409           if ( !eov->_edges.empty() )
11410             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11411
11412         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11413
11414         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11415           if ( !eov->_edges.empty() )
11416             edges.push_back( eov->_edges[0] ); // on last VERTEX
11417
11418         uvPtVec.resize( edges.size() );
11419         for ( size_t i = 0; i < edges.size(); ++i )
11420         {
11421           uvPtVec[ i ].node = edges[i]->_nodes.back();
11422           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11423           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11424         }
11425         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11426         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11427         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11428       }
11429       // temporary clear the FACE sub-mesh from faces made by refine()
11430       vector< const SMDS_MeshElement* > elems;
11431       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11432       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11433         elems.push_back( ite->next() );
11434       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11435         elems.push_back( ite->next() );
11436       smDS->Clear();
11437
11438       // compute the mesh on the FACE
11439       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11440       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11441
11442       // re-fill proxy sub-meshes of the FACE
11443       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11444         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11445           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11446             psm->AddElement( ite->next() );
11447
11448       // re-fill smDS
11449       for ( size_t i = 0; i < elems.size(); ++i )
11450         smDS->AddElement( elems[i] );
11451
11452       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11453         return error( errMsg );
11454
11455     } // end of re-meshing in case of failed smoothing
11456     else if ( !movedByPeriod )
11457     {
11458       // No wrongly shaped faces remain; final smooth. Set node XYZ.
11459       bool isStructuredFixed = false;
11460       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11461         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11462       if ( !isStructuredFixed )
11463       {
11464         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11465           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11466
11467         for ( int st = 3; st; --st )
11468         {
11469           switch( st ) {
11470           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11471           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11472           case 3: smoothType = _SmoothNode::ANGULAR; break;
11473           }
11474           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11475           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11476           {
11477             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11478                                      smoothType,/*set3D=*/st==1 );
11479           }
11480           dumpFunctionEnd();
11481         }
11482       }
11483       if ( !getMeshDS()->IsEmbeddedMode() )
11484         // Log node movement
11485         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11486         {
11487           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11488           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11489         }
11490     }
11491
11492     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11493     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11494     if ( data2 )
11495       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11496
11497   } // loop on FACES to shrink mesh on
11498
11499
11500   // Replace source nodes by target nodes in shrunk mesh edges
11501
11502   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11503   for ( ; e2shr != e2shrMap.end(); ++e2shr )
11504     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11505
11506   return true;
11507 }
11508
11509 //================================================================================
11510 /*!
11511  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11512  */
11513 //================================================================================
11514
11515 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
11516                                            _EdgesOnShape&         eos,
11517                                            SMESH_MesherHelper&    helper,
11518                                            const SMESHDS_SubMesh* /*faceSubMesh*/)
11519 {
11520   const SMDS_MeshNode* srcNode = edge._nodes[0];
11521   const SMDS_MeshNode* tgtNode = edge._nodes.back();
11522
11523   if ( eos.SWOLType() == TopAbs_FACE )
11524   {
11525     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11526     {
11527       edge._pos.clear();
11528       edge.Set( _LayerEdge::SHRUNK );
11529       return srcNode == tgtNode;
11530     }
11531     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
11532     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11533     gp_Vec2d uvDir( srcUV, tgtUV );
11534     double uvLen = uvDir.Magnitude();
11535     uvDir /= uvLen;
11536     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11537     edge._len = uvLen;
11538
11539     //edge._pos.resize(1);
11540     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11541
11542     // set UV of source node to target node
11543     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11544     pos->SetUParameter( srcUV.X() );
11545     pos->SetVParameter( srcUV.Y() );
11546   }
11547   else // _sWOL is TopAbs_EDGE
11548   {
11549     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11550     {
11551       edge._pos.clear();
11552       edge.Set( _LayerEdge::SHRUNK );
11553       return srcNode == tgtNode;
11554     }
11555     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
11556     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11557     if ( !edgeSM || edgeSM->NbElements() == 0 )
11558       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11559
11560     const SMDS_MeshNode* n2 = 0;
11561     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11562     while ( eIt->more() && !n2 )
11563     {
11564       const SMDS_MeshElement* e = eIt->next();
11565       if ( !edgeSM->Contains(e)) continue;
11566       n2 = e->GetNode( 0 );
11567       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11568     }
11569     if ( !n2 )
11570       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11571
11572     if ( n2 == tgtNode ) // for 3D_mesh_GHS3D_01/B1
11573     {
11574       // shrunk by other SOLID
11575       edge.Set( _LayerEdge::SHRUNK ); // ???
11576       return true;
11577     }
11578
11579     double uSrc = helper.GetNodeU( E, srcNode, n2 );
11580     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11581     double u2   = helper.GetNodeU( E, n2,      srcNode );
11582
11583     //edge._pos.clear();
11584
11585     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11586     {
11587       // tgtNode is located so that it does not make faces with wrong orientation
11588       edge.Set( _LayerEdge::SHRUNK );
11589       return true;
11590     }
11591     //edge._pos.resize(1);
11592     edge._pos[0].SetCoord( U_TGT, uTgt );
11593     edge._pos[0].SetCoord( U_SRC, uSrc );
11594     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11595
11596     edge._simplices.resize( 1 );
11597     edge._simplices[0]._nPrev = n2;
11598
11599     // set U of source node to the target node
11600     SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11601     pos->SetUParameter( uSrc );
11602   }
11603   return true;
11604 }
11605
11606 //================================================================================
11607 /*!
11608  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
11609  */
11610 //================================================================================
11611
11612 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
11613 {
11614   if ( edge._nodes.size() == 1 )
11615   {
11616     edge._pos.clear();
11617     edge._len = 0;
11618
11619     const SMDS_MeshNode* srcNode = edge._nodes[0];
11620     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
11621     if ( S.IsNull() ) return;
11622
11623     gp_Pnt p;
11624
11625     switch ( S.ShapeType() )
11626     {
11627     case TopAbs_EDGE:
11628     {
11629       double f,l;
11630       TopLoc_Location loc;
11631       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
11632       if ( curve.IsNull() ) return;
11633       SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
11634       p = curve->Value( ePos->GetUParameter() );
11635       break;
11636     }
11637     case TopAbs_VERTEX:
11638     {
11639       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
11640       break;
11641     }
11642     default: return;
11643     }
11644     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
11645     dumpMove( srcNode );
11646   }
11647 }
11648
11649 //================================================================================
11650 /*!
11651  * \brief Try to fix triangles with high aspect ratio by swapping diagonals
11652  */
11653 //================================================================================
11654
11655 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
11656                                   SMESH_MesherHelper&         helper,
11657                                   const bool                  is2D,
11658                                   const int                   step,
11659                                   set<const SMDS_MeshNode*> * involvedNodes)
11660 {
11661   SMESH::Controls::AspectRatio qualifier;
11662   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
11663   const double maxAspectRatio = is2D ? 4. : 2;
11664   _NodeCoordHelper xyz( F, helper, is2D );
11665
11666   // find bad triangles
11667
11668   vector< const SMDS_MeshElement* > badTrias;
11669   vector< double >                  badAspects;
11670   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
11671   SMDS_ElemIteratorPtr fIt = sm->GetElements();
11672   while ( fIt->more() )
11673   {
11674     const SMDS_MeshElement * f = fIt->next();
11675     if ( f->NbCornerNodes() != 3 ) continue;
11676     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
11677     double aspect = qualifier.GetValue( points );
11678     if ( aspect > maxAspectRatio )
11679     {
11680       badTrias.push_back( f );
11681       badAspects.push_back( aspect );
11682     }
11683   }
11684   if ( step == 1 )
11685   {
11686     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
11687     SMDS_ElemIteratorPtr fIt = sm->GetElements();
11688     while ( fIt->more() )
11689     {
11690       const SMDS_MeshElement * f = fIt->next();
11691       if ( f->NbCornerNodes() == 3 )
11692         dumpChangeNodes( f );
11693     }
11694     dumpFunctionEnd();
11695   }
11696   if ( badTrias.empty() )
11697     return;
11698
11699   // find couples of faces to swap diagonal
11700
11701   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
11702   vector< T2Trias > triaCouples; 
11703
11704   TIDSortedElemSet involvedFaces, emptySet;
11705   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
11706   {
11707     T2Trias trias    [3];
11708     double  aspRatio [3];
11709     int i1, i2, i3;
11710
11711     if ( !involvedFaces.insert( badTrias[iTia] ).second )
11712       continue;
11713     for ( int iP = 0; iP < 3; ++iP )
11714       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
11715
11716     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
11717     int bestCouple = -1;
11718     for ( int iSide = 0; iSide < 3; ++iSide )
11719     {
11720       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
11721       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
11722       trias [iSide].first  = badTrias[iTia];
11723       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
11724                                                              & i1, & i2 );
11725       if (( ! trias[iSide].second ) ||
11726           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
11727           ( ! sm->Contains( trias[iSide].second )))
11728         continue;
11729
11730       // aspect ratio of an adjacent tria
11731       for ( int iP = 0; iP < 3; ++iP )
11732         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
11733       double aspectInit = qualifier.GetValue( points2 );
11734
11735       // arrange nodes as after diag-swaping
11736       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
11737         i3 = helper.WrapIndex( i1-1, 3 );
11738       else
11739         i3 = helper.WrapIndex( i1+1, 3 );
11740       points1 = points;
11741       points1( 1+ iSide ) = points2( 1+ i3 );
11742       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
11743
11744       // aspect ratio after diag-swaping
11745       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
11746       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
11747         continue;
11748
11749       // prevent inversion of a triangle
11750       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
11751       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
11752       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
11753         continue;
11754
11755       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
11756         bestCouple = iSide;
11757     }
11758
11759     if ( bestCouple >= 0 )
11760     {
11761       triaCouples.push_back( trias[bestCouple] );
11762       involvedFaces.insert ( trias[bestCouple].second );
11763     }
11764     else
11765     {
11766       involvedFaces.erase( badTrias[iTia] );
11767     }
11768   }
11769   if ( triaCouples.empty() )
11770     return;
11771
11772   // swap diagonals
11773
11774   SMESH_MeshEditor editor( helper.GetMesh() );
11775   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11776   for ( size_t i = 0; i < triaCouples.size(); ++i )
11777   {
11778     dumpChangeNodes( triaCouples[i].first );
11779     dumpChangeNodes( triaCouples[i].second );
11780     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
11781   }
11782
11783   if ( involvedNodes )
11784     for ( size_t i = 0; i < triaCouples.size(); ++i )
11785     {
11786       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
11787                              triaCouples[i].first->end_nodes() );
11788       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
11789                              triaCouples[i].second->end_nodes() );
11790     }
11791
11792   // just for debug dump resulting triangles
11793   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
11794   for ( size_t i = 0; i < triaCouples.size(); ++i )
11795   {
11796     dumpChangeNodes( triaCouples[i].first );
11797     dumpChangeNodes( triaCouples[i].second );
11798   }
11799 }
11800
11801 //================================================================================
11802 /*!
11803  * \brief Move target node to it's final position on the FACE during shrinking
11804  */
11805 //================================================================================
11806
11807 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& /*surface*/,
11808                                  const TopoDS_Face&    F,
11809                                  _EdgesOnShape&        eos,
11810                                  SMESH_MesherHelper&   helper )
11811 {
11812   if ( Is( SHRUNK ))
11813     return false; // already at the target position
11814
11815   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
11816
11817   if ( eos.SWOLType() == TopAbs_FACE )
11818   {
11819     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
11820     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
11821     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
11822     const double uvLen = tgtUV.Distance( curUV );
11823     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
11824
11825     // Select shrinking step such that not to make faces with wrong orientation.
11826     double stepSize = 1e100;
11827     for ( size_t i = 0; i < _simplices.size(); ++i )
11828     {
11829       if ( !_simplices[i]._nPrev->isMarked() ||
11830            !_simplices[i]._nNext->isMarked() )
11831         continue; // simplex of quadrangle created by addBoundaryElements()
11832
11833       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
11834       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
11835       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
11836       gp_XY dirN = uvN2 - uvN1;
11837       double det = uvDir.Crossed( dirN );
11838       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
11839       gp_XY dirN2Cur = curUV - uvN1;
11840       double step = dirN.Crossed( dirN2Cur ) / det;
11841       if ( step > 0 )
11842         stepSize = Min( step, stepSize );
11843     }
11844     gp_Pnt2d newUV;
11845     if ( uvLen <= stepSize )
11846     {
11847       newUV = tgtUV;
11848       Set( SHRUNK );
11849       //_pos.clear();
11850     }
11851     else if ( stepSize > 0 )
11852     {
11853       newUV = curUV + uvDir.XY() * stepSize * kSafe;
11854     }
11855     else
11856     {
11857       return true;
11858     }
11859     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11860     pos->SetUParameter( newUV.X() );
11861     pos->SetVParameter( newUV.Y() );
11862
11863 #ifdef __myDEBUG
11864     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11865     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11866     dumpMove( tgtNode );
11867 #endif
11868   }
11869   else // _sWOL is TopAbs_EDGE
11870   {
11871     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
11872     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
11873     SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
11874
11875     const double u2     = helper.GetNodeU( E, n2, tgtNode );
11876     const double uSrc   = _pos[0].Coord( U_SRC );
11877     const double lenTgt = _pos[0].Coord( LEN_TGT );
11878
11879     double newU = _pos[0].Coord( U_TGT );
11880     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
11881     {
11882       Set( _LayerEdge::SHRUNK );
11883       //_pos.clear();
11884     }
11885     else
11886     {
11887       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
11888     }
11889     tgtPos->SetUParameter( newU );
11890 #ifdef __myDEBUG
11891     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
11892     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
11893     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11894     dumpMove( tgtNode );
11895 #endif
11896   }
11897
11898   return true;
11899 }
11900
11901 //================================================================================
11902 /*!
11903  * \brief Perform smooth on the FACE
11904  *  \retval bool - true if the node has been moved
11905  */
11906 //================================================================================
11907
11908 bool _SmoothNode::Smooth(int&                  nbBad,
11909                          Handle(Geom_Surface)& surface,
11910                          SMESH_MesherHelper&   helper,
11911                          const double          refSign,
11912                          SmoothType            how,
11913                          bool                  set3D)
11914 {
11915   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
11916
11917   // get uv of surrounding nodes
11918   vector<gp_XY> uv( _simplices.size() );
11919   for ( size_t i = 0; i < _simplices.size(); ++i )
11920     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
11921
11922   // compute new UV for the node
11923   gp_XY newPos (0,0);
11924   if ( how == TFI && _simplices.size() == 4 )
11925   {
11926     gp_XY corners[4];
11927     for ( size_t i = 0; i < _simplices.size(); ++i )
11928       if ( _simplices[i]._nOpp )
11929         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
11930       else
11931         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
11932
11933     newPos = helper.calcTFI ( 0.5, 0.5,
11934                               corners[0], corners[1], corners[2], corners[3],
11935                               uv[1], uv[2], uv[3], uv[0] );
11936   }
11937   else if ( how == ANGULAR )
11938   {
11939     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
11940   }
11941   else if ( how == CENTROIDAL && _simplices.size() > 3 )
11942   {
11943     // average centers of diagonals wieghted with their reciprocal lengths
11944     if ( _simplices.size() == 4 )
11945     {
11946       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
11947       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
11948       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
11949     }
11950     else
11951     {
11952       double sumWeight = 0;
11953       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
11954       for ( int i = 0; i < nb; ++i )
11955       {
11956         int iFrom = i + 2;
11957         int iTo   = i + _simplices.size() - 1;
11958         for ( int j = iFrom; j < iTo; ++j )
11959         {
11960           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
11961           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
11962           sumWeight += w;
11963           newPos += w * ( uv[i]+uv[i2] );
11964         }
11965       }
11966       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
11967     }
11968   }
11969   else
11970   {
11971     // Laplacian smooth
11972     for ( size_t i = 0; i < _simplices.size(); ++i )
11973       newPos += uv[i];
11974     newPos /= _simplices.size();
11975   }
11976
11977   // count quality metrics (orientation) of triangles around the node
11978   int nbOkBefore = 0;
11979   gp_XY tgtUV = helper.GetNodeUV( face, _node );
11980   for ( size_t i = 0; i < _simplices.size(); ++i )
11981     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
11982
11983   int nbOkAfter = 0;
11984   for ( size_t i = 0; i < _simplices.size(); ++i )
11985     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
11986
11987   if ( nbOkAfter < nbOkBefore )
11988   {
11989     nbBad += _simplices.size() - nbOkBefore;
11990     return false;
11991   }
11992
11993   SMDS_FacePositionPtr pos = _node->GetPosition();
11994   pos->SetUParameter( newPos.X() );
11995   pos->SetVParameter( newPos.Y() );
11996
11997 #ifdef __myDEBUG
11998   set3D = true;
11999 #endif
12000   if ( set3D )
12001   {
12002     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
12003     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
12004     dumpMove( _node );
12005   }
12006
12007   nbBad += _simplices.size() - nbOkAfter;
12008   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
12009 }
12010
12011 //================================================================================
12012 /*!
12013  * \brief Computes new UV using angle based smoothing technique
12014  */
12015 //================================================================================
12016
12017 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12018                                      const gp_XY&   uvToFix,
12019                                      const double   refSign)
12020 {
12021   uv.push_back( uv.front() );
12022
12023   vector< gp_XY >  edgeDir ( uv.size() );
12024   vector< double > edgeSize( uv.size() );
12025   for ( size_t i = 1; i < edgeDir.size(); ++i )
12026   {
12027     edgeDir [i-1] = uv[i] - uv[i-1];
12028     edgeSize[i-1] = edgeDir[i-1].Modulus();
12029     if ( edgeSize[i-1] < numeric_limits<double>::min() )
12030       edgeDir[i-1].SetX( 100 );
12031     else
12032       edgeDir[i-1] /= edgeSize[i-1] * refSign;
12033   }
12034   edgeDir.back()  = edgeDir.front();
12035   edgeSize.back() = edgeSize.front();
12036
12037   gp_XY  newPos(0,0);
12038   //int    nbEdges = 0;
12039   double sumSize = 0;
12040   for ( size_t i = 1; i < edgeDir.size(); ++i )
12041   {
12042     if ( edgeDir[i-1].X() > 1. ) continue;
12043     int i1 = i-1;
12044     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12045     if ( i == edgeDir.size() ) break;
12046     gp_XY p = uv[i];
12047     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12048     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
12049     gp_XY bisec = norm1 + norm2;
12050     double bisecSize = bisec.Modulus();
12051     if ( bisecSize < numeric_limits<double>::min() )
12052     {
12053       bisec = -edgeDir[i1] + edgeDir[i];
12054       bisecSize = bisec.Modulus();
12055     }
12056     bisec /= bisecSize;
12057
12058     gp_XY  dirToN  = uvToFix - p;
12059     double distToN = dirToN.Modulus();
12060     if ( bisec * dirToN < 0 )
12061       distToN = -distToN;
12062
12063     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
12064     //++nbEdges;
12065     sumSize += edgeSize[i1] + edgeSize[i];
12066   }
12067   newPos /= /*nbEdges * */sumSize;
12068   return newPos;
12069 }
12070
12071 //================================================================================
12072 /*!
12073  * \brief Keep a _LayerEdge inflated along the EDGE
12074  */
12075 //================================================================================
12076
12077 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
12078                            _EdgesOnShape&      eos,
12079                            SMESH_MesherHelper& helper )
12080 {
12081   // init
12082   if ( _nodes.empty() )
12083   {
12084     _edges[0] = _edges[1] = 0;
12085     _done = false;
12086   }
12087   // check _LayerEdge
12088   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12089     return;
12090   if ( eos.SWOLType() != TopAbs_EDGE )
12091     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12092   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12093     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12094
12095   // store _LayerEdge
12096   _geomEdge = TopoDS::Edge( eos._sWOL );
12097   double f,l;
12098   BRep_Tool::Range( _geomEdge, f,l );
12099   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12100   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12101
12102   // Update _nodes
12103
12104   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12105   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12106
12107   if ( _nodes.empty() )
12108   {
12109     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12110     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12111       return;
12112     TopLoc_Location loc;
12113     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12114     GeomAdaptor_Curve aCurve(C, f,l);
12115     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12116
12117     smIdType nbExpectNodes = eSubMesh->NbNodes();
12118     _initU  .reserve( nbExpectNodes );
12119     _normPar.reserve( nbExpectNodes );
12120     _nodes  .reserve( nbExpectNodes );
12121     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12122     while ( nIt->more() )
12123     {
12124       const SMDS_MeshNode* node = nIt->next();
12125
12126       // skip refinement nodes
12127       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12128            node == tgtNode0 || node == tgtNode1 )
12129         continue;
12130       bool hasMarkedFace = false;
12131       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12132       while ( fIt->more() && !hasMarkedFace )
12133         hasMarkedFace = fIt->next()->isMarked();
12134       if ( !hasMarkedFace )
12135         continue;
12136
12137       _nodes.push_back( node );
12138       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12139       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12140       _normPar.push_back(  len / totLen );
12141     }
12142   }
12143   else
12144   {
12145     // remove target node of the _LayerEdge from _nodes
12146     size_t nbFound = 0;
12147     for ( size_t i = 0; i < _nodes.size(); ++i )
12148       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12149         _nodes[i] = 0, nbFound++;
12150     if ( nbFound == _nodes.size() )
12151       _nodes.clear();
12152   }
12153 }
12154
12155 //================================================================================
12156 /*!
12157  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12158  */
12159 //================================================================================
12160
12161 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12162 {
12163   if ( _done || _nodes.empty())
12164     return;
12165   const _LayerEdge* e = _edges[0];
12166   if ( !e ) e = _edges[1];
12167   if ( !e ) return;
12168
12169   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12170             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12171
12172   double f,l;
12173   if ( set3D || _done )
12174   {
12175     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12176     GeomAdaptor_Curve aCurve(C, f,l);
12177
12178     if ( _edges[0] )
12179       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12180     if ( _edges[1] )
12181       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12182     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12183
12184     for ( size_t i = 0; i < _nodes.size(); ++i )
12185     {
12186       if ( !_nodes[i] ) continue;
12187       double len = totLen * _normPar[i];
12188       GCPnts_AbscissaPoint discret( aCurve, len, f );
12189       if ( !discret.IsDone() )
12190         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12191       double u = discret.Parameter();
12192       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12193       pos->SetUParameter( u );
12194       gp_Pnt p = C->Value( u );
12195       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12196     }
12197   }
12198   else
12199   {
12200     BRep_Tool::Range( _geomEdge, f,l );
12201     if ( _edges[0] )
12202       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12203     if ( _edges[1] )
12204       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12205     
12206     for ( size_t i = 0; i < _nodes.size(); ++i )
12207     {
12208       if ( !_nodes[i] ) continue;
12209       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12210       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12211       pos->SetUParameter( u );
12212     }
12213   }
12214 }
12215
12216 //================================================================================
12217 /*!
12218  * \brief Restore initial parameters of nodes on EDGE
12219  */
12220 //================================================================================
12221
12222 void _Shrinker1D::RestoreParams()
12223 {
12224   if ( _done )
12225     for ( size_t i = 0; i < _nodes.size(); ++i )
12226     {
12227       if ( !_nodes[i] ) continue;
12228       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12229       pos->SetUParameter( _initU[i] );
12230     }
12231   _done = false;
12232 }
12233
12234 //================================================================================
12235 /*!
12236  * \brief Replace source nodes by target nodes in shrunk mesh edges
12237  */
12238 //================================================================================
12239
12240 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12241 {
12242   const SMDS_MeshNode* nodes[3];
12243   for ( int i = 0; i < 2; ++i )
12244   {
12245     if ( !_edges[i] ) continue;
12246
12247     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12248     if ( !eSubMesh ) return;
12249     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12250     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12251     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12252     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12253     while ( eIt->more() )
12254     {
12255       const SMDS_MeshElement* e = eIt->next();
12256       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12257           continue;
12258       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12259       for ( int iN = 0; iN < e->NbNodes(); ++iN )
12260       {
12261         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12262         nodes[iN] = ( n == srcNode ? tgtNode : n );
12263       }
12264       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12265     }
12266   }
12267 }
12268
12269 //================================================================================
12270 /*!
12271  * \brief Creates 2D and 1D elements on boundaries of new prisms
12272  */
12273 //================================================================================
12274
12275 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12276 {
12277   SMESH_MesherHelper helper( *_mesh );
12278
12279   vector< const SMDS_MeshNode* > faceNodes;
12280
12281   //for ( size_t i = 0; i < _sdVec.size(); ++i )
12282   {
12283     //_SolidData& data = _sdVec[i];
12284     TopTools_IndexedMapOfShape geomEdges;
12285     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12286     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12287     {
12288       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12289       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12290       if ( data._noShrinkShapes.count( edgeID ))
12291         continue;
12292
12293       // Get _LayerEdge's based on E
12294
12295       map< double, const SMDS_MeshNode* > u2nodes;
12296       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12297         continue;
12298
12299       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12300       TNode2Edge & n2eMap = data._n2eMap;
12301       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12302       {
12303         //check if 2D elements are needed on E
12304         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12305         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12306         ledges.push_back( n2e->second );
12307         u2n++;
12308         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12309           continue; // no layers on E
12310         ledges.push_back( n2eMap[ u2n->second ]);
12311
12312         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12313         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12314         int nbSharedPyram = 0;
12315         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12316         while ( vIt->more() )
12317         {
12318           const SMDS_MeshElement* v = vIt->next();
12319           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12320         }
12321         if ( nbSharedPyram > 1 )
12322           continue; // not free border of the pyramid
12323
12324         faceNodes.clear();
12325         faceNodes.push_back( ledges[0]->_nodes[0] );
12326         faceNodes.push_back( ledges[1]->_nodes[0] );
12327         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12328         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12329
12330         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12331           continue; // faces already created
12332       }
12333       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12334         ledges.push_back( n2eMap[ u2n->second ]);
12335
12336       // Find out orientation and type of face to create
12337
12338       bool reverse = false, isOnFace;
12339       TopoDS_Shape F;
12340
12341       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12342       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12343       {
12344         F = e2f->second.Oriented( TopAbs_FORWARD );
12345         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12346         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12347           reverse = !reverse, F.Reverse();
12348         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12349           reverse = !reverse;
12350       }
12351       else if ( !data._ignoreFaceIds.count( e2f->first ))
12352       {
12353         // find FACE with layers sharing E
12354         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12355         if ( fIt->more() )
12356           F = *( fIt->next() );
12357       }
12358       // Find the sub-mesh to add new faces
12359       SMESHDS_SubMesh* sm = 0;
12360       if ( isOnFace )
12361         sm = getMeshDS()->MeshElements( F );
12362       else
12363         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12364       if ( !sm )
12365         return error("error in addBoundaryElements()", data._index);
12366
12367       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12368       // faces for 3D meshing (PAL23414)
12369       SMESHDS_SubMesh* adjSM = 0;
12370       if ( isOnFace )
12371       {
12372         const TGeomID   faceID = sm->GetID();
12373         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12374         while ( const TopoDS_Shape* solid = soIt->next() )
12375           if ( !solid->IsSame( data._solid ))
12376           {
12377             size_t iData = _solids.FindIndex( *solid ) - 1;
12378             if ( iData < _sdVec.size() &&
12379                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12380                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12381             {
12382               SMESH_ProxyMesh::SubMesh* proxySub =
12383                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12384               if ( proxySub && proxySub->NbElements() > 0 )
12385                 adjSM = proxySub;
12386             }
12387           }
12388       }
12389
12390       // Make faces
12391       const int dj1 = reverse ? 0 : 1;
12392       const int dj2 = reverse ? 1 : 0;
12393       vector< const SMDS_MeshElement*> ff; // new faces row
12394       SMESHDS_Mesh* m = getMeshDS();
12395       for ( size_t j = 1; j < ledges.size(); ++j )
12396       {
12397         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
12398         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
12399         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12400         if ( nn1.size() == nn2.size() )
12401         {
12402           if ( isOnFace )
12403             for ( size_t z = 1; z < nn1.size(); ++z )
12404               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12405           else
12406             for ( size_t z = 1; z < nn1.size(); ++z )
12407               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12408         }
12409         else if ( nn1.size() == 1 )
12410         {
12411           if ( isOnFace )
12412             for ( size_t z = 1; z < nn2.size(); ++z )
12413               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12414           else
12415             for ( size_t z = 1; z < nn2.size(); ++z )
12416               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12417         }
12418         else
12419         {
12420           if ( isOnFace )
12421             for ( size_t z = 1; z < nn1.size(); ++z )
12422               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12423           else
12424             for ( size_t z = 1; z < nn1.size(); ++z )
12425               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12426         }
12427
12428         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12429         {
12430           for ( size_t z = 0; z < ff.size(); ++z )
12431             if ( ff[ z ])
12432               adjSM->AddElement( ff[ z ]);
12433           ff.clear();
12434         }
12435       }
12436
12437       // Make edges
12438       for ( int isFirst = 0; isFirst < 2; ++isFirst )
12439       {
12440         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12441         _EdgesOnShape* eos = data.GetShapeEdges( edge );
12442         if ( eos && eos->SWOLType() == TopAbs_EDGE )
12443         {
12444           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
12445           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12446             continue;
12447           helper.SetSubShape( eos->_sWOL );
12448           helper.SetElementsOnShape( true );
12449           for ( size_t z = 1; z < nn.size(); ++z )
12450             helper.AddEdge( nn[z-1], nn[z] );
12451         }
12452       }
12453
12454     } // loop on EDGE's
12455   } // loop on _SolidData's
12456
12457   return true;
12458 }