Salome HOME
bos #26452 [EDF] (2021) SMESH: orientation of faces
[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_Quadrangle_2D.hxx"
53 #include "StdMeshers_ViscousLayers2D.hxx"
54
55 #include <Adaptor3d_HSurface.hxx>
56 #include <BRepAdaptor_Curve.hxx>
57 #include <BRepAdaptor_Curve2d.hxx>
58 #include <BRepAdaptor_Surface.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 #ifndef WIN32
105 #define __myDEBUG
106 #endif
107 //#define __NOT_INVALIDATE_BAD_SMOOTH
108 //#define __NODES_AT_POS
109 #endif
110
111 #define INCREMENTAL_SMOOTH // smooth only if min angle is too small
112 #define BLOCK_INFLATION // of individual _LayerEdge's
113 #define OLD_NEF_POLYGON
114
115 using namespace std;
116
117 //================================================================================
118 namespace VISCOUS_3D
119 {
120   typedef int TGeomID;
121
122   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
123
124   const double theMinSmoothCosin = 0.1;
125   const double theSmoothThickToElemSizeRatio = 0.6;
126   const double theMinSmoothTriaAngle = 30;
127   const double theMinSmoothQuadAngle = 45;
128
129   // what part of thickness is allowed till intersection
130   // (defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5)
131   const double theThickToIntersection = 1.5;
132
133   bool needSmoothing( double cosin, double tgtThick, double elemSize )
134   {
135     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
136   }
137   double getSmoothingThickness( double cosin, double elemSize )
138   {
139     return theSmoothThickToElemSizeRatio * elemSize / cosin;
140   }
141
142   /*!
143    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
144    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
145    */
146   struct _MeshOfSolid : public SMESH_ProxyMesh,
147                         public SMESH_subMeshEventListenerData
148   {
149     bool                  _n2nMapComputed;
150     SMESH_ComputeErrorPtr _warning;
151
152     _MeshOfSolid( SMESH_Mesh* mesh)
153       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
154     {
155       SMESH_ProxyMesh::setMesh( *mesh );
156     }
157
158     // returns submesh for a geom face
159     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
160     {
161       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
162       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
163     }
164     void setNode2Node(const SMDS_MeshNode*                 srcNode,
165                       const SMDS_MeshNode*                 proxyNode,
166                       const SMESH_ProxyMesh::SubMesh* subMesh)
167     {
168       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
169     }
170   };
171   //--------------------------------------------------------------------------------
172   /*!
173    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
174    * It is used to clear an inferior dim sub-meshes modified by viscous layers
175    */
176   class _ShrinkShapeListener : SMESH_subMeshEventListener
177   {
178     _ShrinkShapeListener()
179       : SMESH_subMeshEventListener(/*isDeletable=*/false,
180                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
181   public:
182     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
183     virtual void ProcessEvent(const int                       event,
184                               const int                       eventType,
185                               SMESH_subMesh*                  solidSM,
186                               SMESH_subMeshEventListenerData* data,
187                               const SMESH_Hypothesis*         hyp)
188     {
189       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
190       {
191         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
192       }
193     }
194   };
195   //--------------------------------------------------------------------------------
196   /*!
197    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
198    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
199    * delete the data as soon as it has been used
200    */
201   class _ViscousListener : SMESH_subMeshEventListener
202   {
203     _ViscousListener():
204       SMESH_subMeshEventListener(/*isDeletable=*/false,
205                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
206     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
207   public:
208     virtual void ProcessEvent(const int                       event,
209                               const int                       eventType,
210                               SMESH_subMesh*                  subMesh,
211                               SMESH_subMeshEventListenerData* /*data*/,
212                               const SMESH_Hypothesis*         /*hyp*/)
213     {
214       if (( SMESH_subMesh::COMPUTE_EVENT       == eventType ) &&
215           ( SMESH_subMesh::CHECK_COMPUTE_STATE != event &&
216             SMESH_subMesh::SUBMESH_COMPUTED    != event ))
217       {
218         // delete SMESH_ProxyMesh containing temporary faces
219         subMesh->DeleteEventListener( this );
220       }
221     }
222     // Finds or creates proxy mesh of the solid
223     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
224                                       const TopoDS_Shape& solid,
225                                       bool                toCreate=false)
226     {
227       if ( !mesh ) return 0;
228       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
229       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
230       if ( !data && toCreate )
231       {
232         data = new _MeshOfSolid(mesh);
233         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
234         sm->SetEventListener( Get(), data, sm );
235       }
236       return data;
237     }
238     // Removes proxy mesh of the solid
239     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
240     {
241       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
242     }
243   };
244   
245   //================================================================================
246   /*!
247    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
248    * the main shape when sub-mesh of the main shape is cleared,
249    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
250    * is cleared
251    */
252   //================================================================================
253
254   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
255   {
256     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
257     SMESH_subMeshEventListenerData* data =
258       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
259     if ( data )
260     {
261       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
262            data->mySubMeshes.end())
263         data->mySubMeshes.push_back( sub );
264     }
265     else
266     {
267       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
268       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
269     }
270   }
271   struct _SolidData;
272   //--------------------------------------------------------------------------------
273   /*!
274    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
275    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
276    * The class is used to check validity of face or volumes around a smoothed node;
277    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
278    */
279   struct _Simplex
280   {
281     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
282     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
283     _Simplex(const SMDS_MeshNode* nPrev=0,
284              const SMDS_MeshNode* nNext=0,
285              const SMDS_MeshNode* nOpp=0)
286       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
287     bool IsForward(const gp_XYZ* pntSrc, const gp_XYZ* pntTgt, double& vol) const
288     {
289       const double M[3][3] =
290         {{ _nNext->X() - pntSrc->X(), _nNext->Y() - pntSrc->Y(), _nNext->Z() - pntSrc->Z() },
291          { pntTgt->X() - pntSrc->X(), pntTgt->Y() - pntSrc->Y(), pntTgt->Z() - pntSrc->Z() },
292          { _nPrev->X() - pntSrc->X(), _nPrev->Y() - pntSrc->Y(), _nPrev->Z() - pntSrc->Z() }};
293       vol = ( + M[0][0] * M[1][1] * M[2][2]
294               + M[0][1] * M[1][2] * M[2][0]
295               + M[0][2] * M[1][0] * M[2][1]
296               - M[0][0] * M[1][2] * M[2][1]
297               - M[0][1] * M[1][0] * M[2][2]
298               - M[0][2] * M[1][1] * M[2][0]);
299       return vol > 1e-100;
300     }
301     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ& pTgt, double& vol) const
302     {
303       SMESH_TNodeXYZ pSrc( nSrc );
304       return IsForward( &pSrc, &pTgt, vol );
305     }
306     bool IsForward(const gp_XY&         tgtUV,
307                    const SMDS_MeshNode* smoothedNode,
308                    const TopoDS_Face&   face,
309                    SMESH_MesherHelper&  helper,
310                    const double         refSign) const
311     {
312       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
313       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
314       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
315       double d = v1 ^ v2;
316       return d*refSign > 1e-100;
317     }
318     bool IsMinAngleOK( const gp_XYZ& pTgt, double& minAngle ) const
319     {
320       SMESH_TNodeXYZ pPrev( _nPrev ), pNext( _nNext );
321       if ( !_nOpp ) // triangle
322       {
323         gp_Vec tp( pPrev - pTgt ), pn( pNext - pPrev ), nt( pTgt - pNext );
324         double tp2 = tp.SquareMagnitude();
325         double pn2 = pn.SquareMagnitude();
326         double nt2 = nt.SquareMagnitude();
327
328         if ( tp2 < pn2 && tp2 < nt2 )
329           minAngle = ( nt * -pn ) * ( nt * -pn ) / nt2 / pn2;
330         else if ( pn2 < nt2 )
331           minAngle = ( tp * -nt ) * ( tp * -nt ) / tp2 / nt2;
332         else
333           minAngle = ( pn * -tp ) * ( pn * -tp ) / pn2 / tp2;
334
335         static double theMaxCos2 = ( Cos( theMinSmoothTriaAngle * M_PI / 180. ) *
336                                      Cos( theMinSmoothTriaAngle * M_PI / 180. ));
337         return minAngle < theMaxCos2;
338       }
339       else // quadrangle
340       {
341         SMESH_TNodeXYZ pOpp( _nOpp );
342         gp_Vec tp( pPrev - pTgt ), po( pOpp - pPrev ), on( pNext - pOpp), nt( pTgt - pNext );
343         double tp2 = tp.SquareMagnitude();
344         double po2 = po.SquareMagnitude();
345         double on2 = on.SquareMagnitude();
346         double nt2 = nt.SquareMagnitude();
347         minAngle = Max( Max((( tp * -nt ) * ( tp * -nt ) / tp2 / nt2 ),
348                             (( po * -tp ) * ( po * -tp ) / po2 / tp2 )),
349                         Max((( on * -po ) * ( on * -po ) / on2 / po2 ),
350                             (( nt * -on ) * ( nt * -on ) / nt2 / on2 )));
351
352         static double theMaxCos2 = ( Cos( theMinSmoothQuadAngle * M_PI / 180. ) *
353                                      Cos( theMinSmoothQuadAngle * M_PI / 180. ));
354         return minAngle < theMaxCos2;
355       }
356     }
357     bool IsNeighbour(const _Simplex& other) const
358     {
359       return _nPrev == other._nNext || _nNext == other._nPrev;
360     }
361     bool Includes( const SMDS_MeshNode* node ) const { return _nPrev == node || _nNext == node; }
362     static void GetSimplices( const SMDS_MeshNode* node,
363                               vector<_Simplex>&   simplices,
364                               const set<TGeomID>& ingnoreShapes,
365                               const _SolidData*   dataToCheckOri = 0,
366                               const bool          toSort = false);
367     static void SortSimplices(vector<_Simplex>& simplices);
368   };
369   //--------------------------------------------------------------------------------
370   /*!
371    * Structure used to take into account surface curvature while smoothing
372    */
373   struct _Curvature
374   {
375     double   _r; // radius
376     double   _k; // factor to correct node smoothed position
377     double   _h2lenRatio; // avgNormProj / (2*avgDist)
378     gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
379   public:
380     static _Curvature* New( double avgNormProj, double avgDist );
381     double lenDelta(double len) const { return _k * ( _r + len ); }
382     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
383   };
384   //--------------------------------------------------------------------------------
385
386   struct _2NearEdges;
387   struct _LayerEdge;
388   struct _EdgesOnShape;
389   struct _Smoother1D;
390   struct _Mapper2D;
391   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
392
393   //--------------------------------------------------------------------------------
394   /*!
395    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
396    * and a node of the most internal layer (_nodes.back())
397    */
398   struct _LayerEdge
399   {
400     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
401
402     vector< const SMDS_MeshNode*> _nodes;
403
404     gp_XYZ              _normal;    // to boundary of solid
405     vector<gp_XYZ>      _pos;       // points computed during inflation
406     double              _len;       // length achieved with the last inflation step
407     double              _maxLen;    // maximal possible length
408     double              _cosin;     // of angle (_normal ^ surface)
409     double              _minAngle;  // of _simplices
410     double              _lenFactor; // to compute _len taking _cosin into account
411     int                 _flags;
412
413     // simplices connected to the source node (_nodes[0]);
414     // used for smoothing and quality check of _LayerEdge's based on the FACE
415     vector<_Simplex>    _simplices;
416     vector<_LayerEdge*> _neibors; // all surrounding _LayerEdge's
417     PSmooFun            _smooFunction; // smoothing function
418     _Curvature*         _curvature;
419     // data for smoothing of _LayerEdge's based on the EDGE
420     _2NearEdges*        _2neibors;
421
422     enum EFlags { TO_SMOOTH       = 0x0000001,
423                   MOVED           = 0x0000002, // set by _neibors[i]->SetNewLength()
424                   SMOOTHED        = 0x0000004, // set by _LayerEdge::Smooth()
425                   DIFFICULT       = 0x0000008, // near concave VERTEX
426                   ON_CONCAVE_FACE = 0x0000010,
427                   BLOCKED         = 0x0000020, // not to inflate any more
428                   INTERSECTED     = 0x0000040, // close intersection with a face found
429                   NORMAL_UPDATED  = 0x0000080,
430                   UPD_NORMAL_CONV = 0x0000100, // to update normal on boundary of concave FACE
431                   MARKED          = 0x0000200, // local usage
432                   MULTI_NORMAL    = 0x0000400, // a normal is invisible by some of surrounding faces
433                   NEAR_BOUNDARY   = 0x0000800, // is near FACE boundary forcing smooth
434                   SMOOTHED_C1     = 0x0001000, // is on _eosC1
435                   DISTORTED       = 0x0002000, // was bad before smoothing
436                   RISKY_SWOL      = 0x0004000, // SWOL is parallel to a source FACE
437                   SHRUNK          = 0x0008000, // target node reached a tgt position while shrink()
438                   UNUSED_FLAG     = 0x0100000  // to add user flags after
439     };
440     bool Is   ( int flag ) const { return _flags & flag; }
441     void Set  ( int flag ) { _flags |= flag; }
442     void Unset( int flag ) { _flags &= ~flag; }
443     std::string DumpFlags() const; // debug
444
445     void SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
446     bool SetNewLength2d( Handle(Geom_Surface)& surface,
447                          const TopoDS_Face&    F,
448                          _EdgesOnShape&        eos,
449                          SMESH_MesherHelper&   helper );
450     bool UpdatePositionOnSWOL( SMDS_MeshNode*      n,
451                                double              tol,
452                                _EdgesOnShape&      eos,
453                                SMESH_MesherHelper& helper );
454     void SetDataByNeighbors( const SMDS_MeshNode* n1,
455                              const SMDS_MeshNode* n2,
456                              const _EdgesOnShape& eos,
457                              SMESH_MesherHelper&  helper);
458     void Block( _SolidData& data );
459     void InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength=false );
460     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
461                             const TNode2Edge&     n2eMap);
462     void SmoothPos( const vector< double >& segLen, const double tol );
463     int  GetSmoothedPos( const double tol );
464     int  Smooth(const int step, const bool isConcaveFace, bool findBest);
465     int  Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth );
466     int  CheckNeiborsOnBoundary(vector< _LayerEdge* >* badNeibors = 0, bool * needSmooth = 0 );
467     void SmoothWoCheck();
468     bool SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
469                       const TopoDS_Face&             F,
470                       SMESH_MesherHelper&            helper);
471     void MoveNearConcaVer( const _EdgesOnShape*    eov,
472                            const _EdgesOnShape*    eos,
473                            const int               step,
474                            vector< _LayerEdge* > & badSmooEdges);
475     bool FindIntersection( SMESH_ElementSearcher&   searcher,
476                            double &                 distance,
477                            const double&            epsilon,
478                            _EdgesOnShape&           eos,
479                            const SMDS_MeshElement** face = 0);
480     bool SegTriaInter( const gp_Ax1&        lastSegment,
481                        const gp_XYZ&        p0,
482                        const gp_XYZ&        p1,
483                        const gp_XYZ&        p2,
484                        double&              dist,
485                        const double&        epsilon) const;
486     bool SegTriaInter( const gp_Ax1&        lastSegment,
487                        const SMDS_MeshNode* n0,
488                        const SMDS_MeshNode* n1,
489                        const SMDS_MeshNode* n2,
490                        double&              dist,
491                        const double&        epsilon) const
492     { return SegTriaInter( lastSegment,
493                            SMESH_TNodeXYZ( n0 ), SMESH_TNodeXYZ( n1 ), SMESH_TNodeXYZ( n2 ),
494                            dist, epsilon );
495     }
496     const gp_XYZ& PrevPos() const { return _pos[ _pos.size() - 2 ]; }
497     gp_XYZ PrevCheckPos( _EdgesOnShape* eos=0 ) const;
498     gp_Ax1 LastSegment(double& segLen, _EdgesOnShape& eos) const;
499     gp_XY  LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which=-1 ) const;
500     bool   IsOnEdge() const { return _2neibors; }
501     bool   IsOnFace() const { return ( _nodes[0]->GetPosition()->GetDim() == 2 ); }
502     int    BaseShapeDim() const { return _nodes[0]->GetPosition()->GetDim(); }
503     gp_XYZ Copy( _LayerEdge& other, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
504     double SetCosin( double cosin );
505     void   SetNormal( const gp_XYZ& n ) { _normal = n; }
506     void   SetMaxLen( double l ) { _maxLen = l; }
507     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
508     bool   IsNeiborOnEdge( const _LayerEdge* edge ) const;
509     void   SetSmooLen( double len ) { // set _len at which smoothing is needed
510       _cosin = len; // as for _LayerEdge's on FACE _cosin is not used
511     }
512     double GetSmooLen() { return _cosin; } // for _LayerEdge's on FACE _cosin is not used
513
514     gp_XYZ smoothLaplacian();
515     gp_XYZ smoothAngular();
516     gp_XYZ smoothLengthWeighted();
517     gp_XYZ smoothCentroidal();
518     gp_XYZ smoothNefPolygon();
519
520     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
521     static const int theNbSmooFuns = FUN_NB;
522     static PSmooFun _funs[theNbSmooFuns];
523     static const char* _funNames[theNbSmooFuns+1];
524     int smooFunID( PSmooFun fun=0) const;
525   };
526   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
527                                                             &_LayerEdge::smoothLengthWeighted,
528                                                             &_LayerEdge::smoothCentroidal,
529                                                             &_LayerEdge::smoothNefPolygon,
530                                                             &_LayerEdge::smoothAngular };
531   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
532                                                          "LengthWeighted",
533                                                          "Centroidal",
534                                                          "NefPolygon",
535                                                          "Angular",
536                                                          "None"};
537   struct _LayerEdgeCmp
538   {
539     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
540     {
541       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
542       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
543     }
544   };
545   //--------------------------------------------------------------------------------
546   /*!
547    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
548    */
549   struct _halfPlane
550   {
551     gp_XY _pos, _dir, _inNorm;
552     bool IsOut( const gp_XY p, const double tol ) const
553     {
554       return _inNorm * ( p - _pos ) < -tol;
555     }
556     bool FindIntersection( const _halfPlane& hp, gp_XY & intPnt )
557     {
558       //const double eps = 1e-10;
559       double D = _dir.Crossed( hp._dir );
560       if ( fabs(D) < std::numeric_limits<double>::min())
561         return false;
562       gp_XY vec21 = _pos - hp._pos; 
563       double u = hp._dir.Crossed( vec21 ) / D; 
564       intPnt = _pos + _dir * u;
565       return true;
566     }
567   };
568   //--------------------------------------------------------------------------------
569   /*!
570    * Structure used to smooth a _LayerEdge based on an EDGE.
571    */
572   struct _2NearEdges
573   {
574     double               _wgt  [2]; // weights of _nodes
575     _LayerEdge*          _edges[2];
576
577      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
578     gp_XYZ*              _plnNorm;
579
580     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
581     ~_2NearEdges(){ delete _plnNorm; }
582     const SMDS_MeshNode* tgtNode(bool is2nd) {
583       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
584     }
585     const SMDS_MeshNode* srcNode(bool is2nd) {
586       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
587     }
588     void reverse() {
589       std::swap( _wgt  [0], _wgt  [1] );
590       std::swap( _edges[0], _edges[1] );
591     }
592     void set( _LayerEdge* e1, _LayerEdge* e2, double w1, double w2 ) {
593       _edges[0] = e1; _edges[1] = e2; _wgt[0] = w1; _wgt[1] = w2;
594     }
595     bool include( const _LayerEdge* e ) {
596       return ( _edges[0] == e || _edges[1] == e );
597     }
598   };
599
600
601   //--------------------------------------------------------------------------------
602   /*!
603    * \brief Layers parameters got by averaging several hypotheses
604    */
605   struct AverageHyp
606   {
607     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
608       :_nbLayers(0), _nbHyps(0), _method(0), _thickness(0), _stretchFactor(0)
609     {
610       Add( hyp );
611     }
612     void Add( const StdMeshers_ViscousLayers* hyp )
613     {
614       if ( hyp )
615       {
616         _nbHyps++;
617         _nbLayers       = hyp->GetNumberLayers();
618         //_thickness     += hyp->GetTotalThickness();
619         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
620         _stretchFactor += hyp->GetStretchFactor();
621         _method         = hyp->GetMethod();
622         if ( _groupName.empty() )
623           _groupName = hyp->GetGroupName();
624       }
625     }
626     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
627     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
628     int    GetNumberLayers()   const { return _nbLayers; }
629     int    GetMethod()         const { return _method; }
630     bool   ToCreateGroup()     const { return !_groupName.empty(); }
631     const std::string& GetGroupName() const { return _groupName; }
632
633     double Get1stLayerThickness( double realThickness = 0.) const
634     {
635       const double T = ( realThickness > 0 ) ? realThickness : GetTotalThickness();
636       const double f = GetStretchFactor();
637       const int    N = GetNumberLayers();
638       const double fPowN = pow( f, N );
639       double h0;
640       if ( fPowN - 1 <= numeric_limits<double>::min() )
641         h0 = T / N;
642       else
643         h0 = T * ( f - 1 )/( fPowN - 1 );
644       return h0;
645     }
646
647     bool   UseSurfaceNormal()  const
648     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
649     bool   ToSmooth()          const
650     { return _method == StdMeshers_ViscousLayers::SURF_OFFSET_SMOOTH; }
651     bool   IsOffsetMethod()    const
652     { return _method == StdMeshers_ViscousLayers::FACE_OFFSET; }
653
654     bool operator==( const AverageHyp& other ) const
655     {
656       return ( _nbLayers == other._nbLayers &&
657                _method   == other._method   &&
658                Equals( GetTotalThickness(), other.GetTotalThickness() ) &&
659                Equals( GetStretchFactor(), other.GetStretchFactor() ));
660     }
661     static bool Equals( double v1, double v2 ) { return Abs( v1 - v2 ) < 0.01 * ( v1 + v2 ); }
662
663   private:
664     int         _nbLayers, _nbHyps, _method;
665     double      _thickness, _stretchFactor;
666     std::string _groupName;
667   };
668
669   //--------------------------------------------------------------------------------
670   /*!
671    * \brief _LayerEdge's on a shape and other shape data
672    */
673   struct _EdgesOnShape
674   {
675     vector< _LayerEdge* > _edges;
676
677     TopoDS_Shape          _shape;
678     TGeomID               _shapeID;
679     SMESH_subMesh *       _subMesh;
680     // face or edge w/o layer along or near which _edges are inflated
681     TopoDS_Shape          _sWOL;
682     bool                  _isRegularSWOL; // w/o singularities
683     // averaged StdMeshers_ViscousLayers parameters
684     AverageHyp            _hyp;
685     bool                  _toSmooth;
686     _Smoother1D*          _edgeSmoother;
687     vector< _EdgesOnShape* > _eosConcaVer; // edges at concave VERTEXes of a FACE
688     vector< _EdgesOnShape* > _eosC1; // to smooth together several C1 continues shapes
689
690     typedef std::unordered_map< const SMDS_MeshElement*, gp_XYZ > TFace2NormMap;
691     TFace2NormMap            _faceNormals; // if _shape is FACE
692     vector< _EdgesOnShape* > _faceEOS; // to get _faceNormals of adjacent FACEs
693
694     Handle(ShapeAnalysis_Surface) _offsetSurf;
695     _LayerEdge*                   _edgeForOffset;
696     double                        _offsetValue;
697     _Mapper2D*                    _mapper2D;
698
699     _SolidData*            _data; // parent SOLID
700
701     _LayerEdge*      operator[](size_t i) const { return (_LayerEdge*) _edges[i]; }
702     size_t           size() const { return _edges.size(); }
703     TopAbs_ShapeEnum ShapeType() const
704     { return _shape.IsNull() ? TopAbs_SHAPE : _shape.ShapeType(); }
705     TopAbs_ShapeEnum SWOLType() const
706     { return _sWOL.IsNull() ? TopAbs_SHAPE : _sWOL.ShapeType(); }
707     bool             HasC1( const _EdgesOnShape* other ) const
708     { return std::find( _eosC1.begin(), _eosC1.end(), other ) != _eosC1.end(); }
709     bool             GetNormal( const SMDS_MeshElement* face, gp_Vec& norm );
710     _SolidData&      GetData() const { return *_data; }
711     char             ShapeTypeLetter() const
712     { switch ( ShapeType() ) { case TopAbs_FACE: return 'F'; case TopAbs_EDGE: return 'E';
713       case TopAbs_VERTEX: return 'V'; default: return 'S'; }}
714
715     _EdgesOnShape(): _shapeID(-1), _subMesh(0), _toSmooth(false), _edgeSmoother(0), _mapper2D(0) {}
716     ~_EdgesOnShape();
717   };
718
719   //--------------------------------------------------------------------------------
720   /*!
721    * \brief Convex FACE whose radius of curvature is less than the thickness of
722    *        layers. It is used to detect distortion of prisms based on a convex
723    *        FACE and to update normals to enable further increasing the thickness
724    */
725   struct _ConvexFace
726   {
727     TopoDS_Face                     _face;
728
729     // edges whose _simplices are used to detect prism distortion
730     vector< _LayerEdge* >           _simplexTestEdges;
731
732     // map a sub-shape to _SolidData::_edgesOnShape
733     map< TGeomID, _EdgesOnShape* >  _subIdToEOS;
734
735     bool                            _isTooCurved;
736     bool                            _normalsFixed;
737     bool                            _normalsFixedOnBorders; // used in putOnOffsetSurface()
738
739     double GetMaxCurvature( _SolidData&         data,
740                             _EdgesOnShape&      eof,
741                             BRepLProp_SLProps&  surfProp,
742                             SMESH_MesherHelper& helper);
743
744     bool GetCenterOfCurvature( _LayerEdge*         ledge,
745                                BRepLProp_SLProps&  surfProp,
746                                SMESH_MesherHelper& helper,
747                                gp_Pnt &            center ) const;
748     bool CheckPrisms() const;
749   };
750
751   //--------------------------------------------------------------------------------
752   /*!
753    * \brief Structure holding _LayerEdge's based on EDGEs that will collide
754    *        at inflation up to the full thickness. A detected collision
755    *        is fixed in updateNormals()
756    */
757   struct _CollisionEdges
758   {
759     _LayerEdge*           _edge;
760     vector< _LayerEdge* > _intEdges; // each pair forms an intersected quadrangle
761     const SMDS_MeshNode* nSrc(int i) const { return _intEdges[i]->_nodes[0]; }
762     const SMDS_MeshNode* nTgt(int i) const { return _intEdges[i]->_nodes.back(); }
763   };
764
765   //--------------------------------------------------------------------------------
766   /*!
767    * \brief Data of a SOLID
768    */
769   struct _SolidData
770   {
771     typedef const StdMeshers_ViscousLayers* THyp;
772     TopoDS_Shape                    _solid;
773     TopTools_MapOfShape             _before; // SOLIDs to be computed before _solid
774     TGeomID                         _index; // SOLID id
775     _MeshOfSolid*                   _proxyMesh;
776     bool                            _done;
777     list< THyp >                    _hyps;
778     list< TopoDS_Shape >            _hypShapes;
779     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
780     set< TGeomID >                  _reversedFaceIds;
781     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
782
783     double                          _stepSize, _stepSizeCoeff, _geomSize;
784     const SMDS_MeshNode*            _stepSizeNodes[2];
785
786     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
787
788     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
789     map< TGeomID, TNode2Edge* >     _s2neMap;
790     // _LayerEdge's with underlying shapes
791     vector< _EdgesOnShape >         _edgesOnShape;
792
793     // key:   an ID of shape (EDGE or VERTEX) shared by a FACE with
794     //        layers and a FACE w/o layers
795     // value: the shape (FACE or EDGE) to shrink mesh on.
796     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
797     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
798
799     // Convex FACEs whose radius of curvature is less than the thickness of layers
800     map< TGeomID, _ConvexFace >      _convexFaces;
801
802     // shapes (EDGEs and VERTEXes) shrink from which is forbidden due to collisions with
803     // the adjacent SOLID
804     set< TGeomID >                   _noShrinkShapes;
805
806     int                              _nbShapesToSmooth;
807
808     vector< _CollisionEdges >        _collisionEdges;
809     set< TGeomID >                   _concaveFaces;
810
811     double                           _maxThickness; // of all _hyps
812     double                           _minThickness; // of all _hyps
813
814     double                           _epsilon; // precision for SegTriaInter()
815
816     SMESH_MesherHelper*              _helper;
817
818     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
819                _MeshOfSolid*       m=0)
820       :_solid(s), _proxyMesh(m), _done(false),_helper(0) {}
821     ~_SolidData() { delete _helper; _helper = 0; }
822
823     void SortOnEdge( const TopoDS_Edge& E, vector< _LayerEdge* >& edges);
824     void Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges );
825
826     _ConvexFace* GetConvexFace( const TGeomID faceID ) {
827       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
828       return id2face == _convexFaces.end() ? 0 : & id2face->second;
829     }
830     _EdgesOnShape* GetShapeEdges(const TGeomID       shapeID );
831     _EdgesOnShape* GetShapeEdges(const TopoDS_Shape& shape );
832     _EdgesOnShape* GetShapeEdges(const _LayerEdge*   edge )
833     { return GetShapeEdges( edge->_nodes[0]->getshapeId() ); }
834
835     SMESH_MesherHelper& GetHelper() const { return *_helper; }
836
837     void UnmarkEdges( int flag = _LayerEdge::MARKED ) {
838       for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
839         for ( size_t j = 0; j < _edgesOnShape[i]._edges.size(); ++j )
840           _edgesOnShape[i]._edges[j]->Unset( flag );
841     }
842     void AddShapesToSmooth( const set< _EdgesOnShape* >& shape,
843                             const set< _EdgesOnShape* >* edgesNoAnaSmooth=0 );
844
845     void PrepareEdgesToSmoothOnFace( _EdgesOnShape* eof, bool substituteSrcNodes );
846   };
847   //--------------------------------------------------------------------------------
848   /*!
849    * \brief Offset plane used in getNormalByOffset()
850    */
851   struct _OffsetPlane
852   {
853     gp_Pln _plane;
854     int    _faceIndex;
855     int    _faceIndexNext[2];
856     gp_Lin _lines[2]; // line of intersection with neighbor _OffsetPlane's
857     bool   _isLineOK[2];
858     _OffsetPlane() {
859       _isLineOK[0] = _isLineOK[1] = false; _faceIndexNext[0] = _faceIndexNext[1] = -1;
860     }
861     void   ComputeIntersectionLine( _OffsetPlane&        pln, 
862                                     const TopoDS_Edge&   E,
863                                     const TopoDS_Vertex& V );
864     gp_XYZ GetCommonPoint(bool& isFound, const TopoDS_Vertex& V) const;
865     int    NbLines() const { return _isLineOK[0] + _isLineOK[1]; }
866   };
867   //--------------------------------------------------------------------------------
868   /*!
869    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
870    */
871   struct _CentralCurveOnEdge
872   {
873     bool                  _isDegenerated;
874     vector< gp_Pnt >      _curvaCenters;
875     vector< _LayerEdge* > _ledges;
876     vector< gp_XYZ >      _normals; // new normal for each of _ledges
877     vector< double >      _segLength2;
878
879     TopoDS_Edge           _edge;
880     TopoDS_Face           _adjFace;
881     bool                  _adjFaceToSmooth;
882
883     void Append( const gp_Pnt& center, _LayerEdge* ledge )
884     {
885       if ( ledge->Is( _LayerEdge::MULTI_NORMAL ))
886         return;
887       if ( _curvaCenters.size() > 0 )
888         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
889       _curvaCenters.push_back( center );
890       _ledges.push_back( ledge );
891       _normals.push_back( ledge->_normal );
892     }
893     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
894     void SetShapes( const TopoDS_Edge&  edge,
895                     const _ConvexFace&  convFace,
896                     _SolidData&         data,
897                     SMESH_MesherHelper& helper);
898   };
899   //--------------------------------------------------------------------------------
900   /*!
901    * \brief Data of node on a shrinked FACE
902    */
903   struct _SmoothNode
904   {
905     const SMDS_MeshNode*         _node;
906     vector<_Simplex>             _simplices; // for quality check
907
908     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
909
910     bool Smooth(int&                  badNb,
911                 Handle(Geom_Surface)& surface,
912                 SMESH_MesherHelper&   helper,
913                 const double          refSign,
914                 SmoothType            how,
915                 bool                  set3D);
916
917     gp_XY computeAngularPos(vector<gp_XY>& uv,
918                             const gp_XY&   uvToFix,
919                             const double   refSign );
920   };
921   struct PyDump;
922   struct Periodicity;
923   //--------------------------------------------------------------------------------
924   /*!
925    * \brief Builder of viscous layers
926    */
927   class _ViscousBuilder
928   {
929   public:
930     _ViscousBuilder();
931     // does it's job
932     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
933                                   const TopoDS_Shape& shape);
934     // check validity of hypotheses
935     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
936                                            const TopoDS_Shape& shape );
937
938     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
939     void RestoreListeners();
940
941     // computes SMESH_ProxyMesh::SubMesh::_n2n;
942     bool MakeN2NMap( _MeshOfSolid* pm );
943
944   private:
945
946     bool findSolidsWithLayers(const bool checkFaceMesh=true);
947     bool setBefore( _SolidData& solidBefore, _SolidData& solidAfter );
948     bool findFacesWithLayers(const bool onlyWith=false);
949     void findPeriodicFaces();
950     void getIgnoreFaces(const TopoDS_Shape&             solid,
951                         const StdMeshers_ViscousLayers* hyp,
952                         const TopoDS_Shape&             hypShape,
953                         set<TGeomID>&                   ignoreFaces);
954     int makeEdgesOnShape();
955     bool makeLayer(_SolidData& data);
956     void setShapeData( _EdgesOnShape& eos, SMESH_subMesh* sm, _SolidData& data );
957     bool setEdgeData( _LayerEdge& edge, _EdgesOnShape& eos,
958                       SMESH_MesherHelper& helper, _SolidData& data);
959     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
960                          const TopoDS_Face&   face,
961                          SMESH_MesherHelper&  helper,
962                          bool&                isOK,
963                          bool                 shiftInside=false);
964     bool getFaceNormalAtSingularity(const gp_XY&        uv,
965                                     const TopoDS_Face&  face,
966                                     SMESH_MesherHelper& helper,
967                                     gp_Dir&             normal );
968     gp_XYZ getWeigthedNormal( const _LayerEdge*                edge );
969     gp_XYZ getNormalByOffset( _LayerEdge*                      edge,
970                               std::pair< TopoDS_Face, gp_XYZ > fId2Normal[],
971                               int                              nbFaces,
972                               bool                             lastNoOffset = false);
973     bool findNeiborsOnEdge(const _LayerEdge*     edge,
974                            const SMDS_MeshNode*& n1,
975                            const SMDS_MeshNode*& n2,
976                            _EdgesOnShape&        eos,
977                            _SolidData&           data);
978     void findSimplexTestEdges( _SolidData&                    data,
979                                vector< vector<_LayerEdge*> >& edgesByGeom);
980     void computeGeomSize( _SolidData& data );
981     bool findShapesToSmooth( _SolidData& data);
982     void limitStepSizeByCurvature( _SolidData&  data );
983     void limitStepSize( _SolidData&             data,
984                         const SMDS_MeshElement* face,
985                         const _LayerEdge*       maxCosinEdge );
986     void limitStepSize( _SolidData& data, const double minSize);
987     bool inflate(_SolidData& data);
988     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
989     int  invalidateBadSmooth( _SolidData&               data,
990                               SMESH_MesherHelper&       helper,
991                               vector< _LayerEdge* >&    badSmooEdges,
992                               vector< _EdgesOnShape* >& eosC1,
993                               const int                 infStep );
994     void makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& );
995     void putOnOffsetSurface( _EdgesOnShape& eos, int infStep,
996                              vector< _EdgesOnShape* >& eosC1,
997                              int smooStep=0, int moveAll=false );
998     void findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper );
999     void findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
1000                                                 _SolidData&         data,
1001                                                 SMESH_MesherHelper& helper );
1002     void limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& helper );
1003     void limitMaxLenByCurvature( _LayerEdge* e1, _LayerEdge* e2,
1004                                  _EdgesOnShape& eos1, _EdgesOnShape& eos2,
1005                                  const bool isSmoothable );
1006     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb, double stepSize );
1007     bool updateNormalsOfConvexFaces( _SolidData&         data,
1008                                      SMESH_MesherHelper& helper,
1009                                      int                 stepNb );
1010     void updateNormalsOfC1Vertices( _SolidData& data );
1011     bool updateNormalsOfSmoothed( _SolidData&         data,
1012                                   SMESH_MesherHelper& helper,
1013                                   const int           nbSteps,
1014                                   const double        stepSize );
1015     bool isNewNormalOk( _SolidData&   data,
1016                         _LayerEdge&   edge,
1017                         const gp_XYZ& newNormal);
1018     bool refine(_SolidData& data);
1019     bool shrink(_SolidData& data);
1020     bool prepareEdgeToShrink( _LayerEdge& edge, _EdgesOnShape& eos,
1021                               SMESH_MesherHelper& helper,
1022                               const SMESHDS_SubMesh* faceSubMesh );
1023     void restoreNoShrink( _LayerEdge& edge ) const;
1024     void fixBadFaces(const TopoDS_Face&          F,
1025                      SMESH_MesherHelper&         helper,
1026                      const bool                  is2D,
1027                      const int                   step,
1028                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
1029     bool addBoundaryElements(_SolidData& data);
1030
1031     bool error( const string& text, int solidID=-1 );
1032     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
1033
1034     // debug
1035     void makeGroupOfLE();
1036
1037     SMESH_Mesh*                  _mesh;
1038     SMESH_ComputeErrorPtr        _error;
1039
1040     vector<                      _SolidData >  _sdVec;
1041     TopTools_IndexedMapOfShape   _solids; // to find _SolidData by a solid
1042     TopTools_MapOfShape          _shrunkFaces;
1043     std::unique_ptr<Periodicity> _periodicity;
1044
1045     int                          _tmpFaceID;
1046     PyDump*                      _pyDump;
1047   };
1048   //--------------------------------------------------------------------------------
1049   /*!
1050    * \brief Shrinker of nodes on the EDGE
1051    */
1052   class _Shrinker1D
1053   {
1054     TopoDS_Edge                   _geomEdge;
1055     vector<double>                _initU;
1056     vector<double>                _normPar;
1057     vector<const SMDS_MeshNode*>  _nodes;
1058     const _LayerEdge*             _edges[2];
1059     bool                          _done;
1060   public:
1061     void AddEdge( const _LayerEdge* e, _EdgesOnShape& eos, SMESH_MesherHelper& helper );
1062     void Compute(bool set3D, SMESH_MesherHelper& helper);
1063     void RestoreParams();
1064     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
1065     const TopoDS_Edge& GeomEdge() const { return _geomEdge; }
1066     const SMDS_MeshNode* TgtNode( bool is2nd ) const
1067     { return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0; }
1068     const SMDS_MeshNode* SrcNode( bool is2nd ) const
1069     { return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0; }
1070   };
1071   //--------------------------------------------------------------------------------
1072   /*!
1073    * \brief Smoother of _LayerEdge's on EDGE.
1074    */
1075   struct _Smoother1D
1076   {
1077     struct OffPnt // point of the offsetted EDGE
1078     {
1079       gp_XYZ      _xyz;    // coord of a point inflated from EDGE w/o smooth
1080       double      _len;    // length reached at previous inflation step
1081       double      _param;  // on EDGE
1082       _2NearEdges _2edges; // 2 neighbor _LayerEdge's
1083       gp_XYZ      _edgeDir;// EDGE tangent at _param
1084       double Distance( const OffPnt& p ) const { return ( _xyz - p._xyz ).Modulus(); }
1085     };
1086     vector< OffPnt >   _offPoints;
1087     vector< double >   _leParams; // normalized param of _eos._edges on EDGE
1088     Handle(Geom_Curve) _anaCurve; // for analytic smooth
1089     _LayerEdge         _leOnV[2]; // _LayerEdge's holding normal to the EDGE at VERTEXes
1090     gp_XYZ             _edgeDir[2]; // tangent at VERTEXes
1091     size_t             _iSeg[2];  // index of segment where extreme tgt node is projected
1092     _EdgesOnShape&     _eos;
1093     double             _curveLen; // length of the EDGE
1094     std::pair<int,int> _eToSmooth[2]; // <from,to> indices of _LayerEdge's in _eos
1095
1096     static Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&  E,
1097                                               _EdgesOnShape&      eos,
1098                                               SMESH_MesherHelper& helper);
1099
1100     _Smoother1D( Handle(Geom_Curve) curveForSmooth,
1101                  _EdgesOnShape&     eos )
1102       : _anaCurve( curveForSmooth ), _eos( eos )
1103     {
1104     }
1105     bool Perform(_SolidData&                    data,
1106                  Handle(ShapeAnalysis_Surface)& surface,
1107                  const TopoDS_Face&             F,
1108                  SMESH_MesherHelper&            helper );
1109
1110     void prepare(_SolidData& data );
1111
1112     void findEdgesToSmooth();
1113
1114     bool isToSmooth( int iE );
1115
1116     bool smoothAnalyticEdge( _SolidData&                    data,
1117                              Handle(ShapeAnalysis_Surface)& surface,
1118                              const TopoDS_Face&             F,
1119                              SMESH_MesherHelper&            helper);
1120     bool smoothComplexEdge( _SolidData&                     data,
1121                             Handle(ShapeAnalysis_Surface)& surface,
1122                             const TopoDS_Face&             F,
1123                             SMESH_MesherHelper&            helper);
1124     gp_XYZ getNormalNormal( const gp_XYZ & normal,
1125                             const gp_XYZ&  edgeDir);
1126     _LayerEdge* getLEdgeOnV( bool is2nd )
1127     {
1128       return _eos._edges[ is2nd ? _eos._edges.size()-1 : 0 ]->_2neibors->_edges[ is2nd ];
1129     }
1130     bool isAnalytic() const { return !_anaCurve.IsNull(); }
1131
1132     void offPointsToPython() const; // debug
1133   };
1134
1135   //--------------------------------------------------------------------------------
1136   /*!
1137    * \brief Compute positions of nodes of 2D structured mesh using TFI
1138    */
1139   class _Mapper2D
1140   {
1141     FaceQuadStruct _quadPoints;
1142
1143     UVPtStruct& uvPnt( size_t i, size_t j ) { return _quadPoints.UVPt( i, j ); }
1144
1145   public:
1146     _Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap );
1147     bool ComputeNodePositions();
1148   };
1149
1150   //--------------------------------------------------------------------------------
1151   /*!
1152    * \brief Class of temporary mesh face.
1153    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
1154    * needed because SMESH_ElementSearcher internally uses set of elements sorted by ID
1155    */
1156   struct _TmpMeshFace : public SMDS_PolygonalFaceOfNodes
1157   {
1158     const SMDS_MeshElement* _srcFace;
1159
1160     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes,
1161                   int                                 ID,
1162                   int                                 faceID=-1,
1163                   const SMDS_MeshElement*             srcFace=0 ):
1164       SMDS_PolygonalFaceOfNodes(nodes), _srcFace( srcFace ) { setID( ID ); setShapeID( faceID ); }
1165     virtual SMDSAbs_EntityType  GetEntityType() const
1166     { return _srcFace ? _srcFace->GetEntityType() : SMDSEntity_Quadrangle; }
1167     virtual SMDSAbs_GeometryType GetGeomType()  const
1168     { return _srcFace ? _srcFace->GetGeomType() : SMDSGeom_QUADRANGLE; }
1169   };
1170   //--------------------------------------------------------------------------------
1171   /*!
1172    * \brief Class of temporary mesh quadrangle face storing _LayerEdge it's based on
1173    */
1174   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
1175   {
1176     _LayerEdge *_le1, *_le2;
1177     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
1178       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
1179     {
1180       myNodes[0]=_le1->_nodes[0];
1181       myNodes[1]=_le1->_nodes.back();
1182       myNodes[2]=_le2->_nodes.back();
1183       myNodes[3]=_le2->_nodes[0];
1184     }
1185     const SMDS_MeshNode* n( size_t i ) const
1186     {
1187       return myNodes[ i ];
1188     }
1189     gp_XYZ GetDir() const // return average direction of _LayerEdge's, normal to EDGE
1190     {
1191       SMESH_TNodeXYZ p0s( myNodes[0] );
1192       SMESH_TNodeXYZ p0t( myNodes[1] );
1193       SMESH_TNodeXYZ p1t( myNodes[2] );
1194       SMESH_TNodeXYZ p1s( myNodes[3] );
1195       gp_XYZ  v0 = p0t - p0s;
1196       gp_XYZ  v1 = p1t - p1s;
1197       gp_XYZ v01 = p1s - p0s;
1198       gp_XYZ   n = ( v0 ^ v01 ) + ( v1 ^ v01 );
1199       gp_XYZ   d = v01 ^ n;
1200       d.Normalize();
1201       return d;
1202     }
1203     gp_XYZ GetDir(_LayerEdge* le1, _LayerEdge* le2) // return average direction of _LayerEdge's
1204     {
1205       myNodes[0]=le1->_nodes[0];
1206       myNodes[1]=le1->_nodes.back();
1207       myNodes[2]=le2->_nodes.back();
1208       myNodes[3]=le2->_nodes[0];
1209       return GetDir();
1210     }
1211   };
1212   //--------------------------------------------------------------------------------
1213   /*!
1214    * \brief Retriever of node coordinates either directly or from a surface by node UV.
1215    * \warning Location of a surface is ignored
1216    */
1217   struct _NodeCoordHelper
1218   {
1219     SMESH_MesherHelper&        _helper;
1220     const TopoDS_Face&         _face;
1221     Handle(Geom_Surface)       _surface;
1222     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
1223
1224     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
1225       : _helper( helper ), _face( F )
1226     {
1227       if ( is2D )
1228       {
1229         TopLoc_Location loc;
1230         _surface = BRep_Tool::Surface( _face, loc );
1231       }
1232       if ( _surface.IsNull() )
1233         _fun = & _NodeCoordHelper::direct;
1234       else
1235         _fun = & _NodeCoordHelper::byUV;
1236     }
1237     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
1238
1239   private:
1240     gp_XYZ direct(const SMDS_MeshNode* n) const
1241     {
1242       return SMESH_TNodeXYZ( n );
1243     }
1244     gp_XYZ byUV  (const SMDS_MeshNode* n) const
1245     {
1246       gp_XY uv = _helper.GetNodeUV( _face, n );
1247       return _surface->Value( uv.X(), uv.Y() ).XYZ();
1248     }
1249   };
1250
1251   //================================================================================
1252   /*!
1253    * \brief Check angle between vectors 
1254    */
1255   //================================================================================
1256
1257   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
1258   {
1259     double dot = v1 * v2; // cos * |v1| * |v2|
1260     double l1  = v1.SquareMagnitude();
1261     double l2  = v2.SquareMagnitude();
1262     return (( dot * cos >= 0 ) && 
1263             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
1264   }
1265
1266   class _Factory
1267   {
1268     ObjectPool< _LayerEdge >  _edgePool;
1269     ObjectPool< _Curvature >  _curvaturePool;
1270     ObjectPool< _2NearEdges > _nearEdgesPool;
1271
1272     static _Factory* & me()
1273     {
1274       static _Factory* theFactory = 0;
1275       return theFactory;
1276     }
1277   public:
1278
1279     _Factory()  { me() = this; }
1280     ~_Factory() { me() = 0; }
1281
1282     static _LayerEdge*  NewLayerEdge() { return me()->_edgePool.getNew(); }
1283     static _Curvature * NewCurvature() { return me()->_curvaturePool.getNew(); }
1284     static _2NearEdges* NewNearEdges() { return me()->_nearEdgesPool.getNew(); }
1285   };
1286
1287 } // namespace VISCOUS_3D
1288
1289
1290
1291 //================================================================================
1292 // StdMeshers_ViscousLayers hypothesis
1293 //
1294 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, SMESH_Gen* gen)
1295   :SMESH_Hypothesis(hypId, gen),
1296    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1),
1297    _method( SURF_OFFSET_SMOOTH ),
1298    _groupName("")
1299 {
1300   _name = StdMeshers_ViscousLayers::GetHypType();
1301   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
1302 } // --------------------------------------------------------------------------------
1303 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
1304 {
1305   if ( faceIds != _shapeIds )
1306     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
1307   if ( _isToIgnoreShapes != toIgnore )
1308     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
1309 } // --------------------------------------------------------------------------------
1310 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
1311 {
1312   if ( thickness != _thickness )
1313     _thickness = thickness, NotifySubMeshesHypothesisModification();
1314 } // --------------------------------------------------------------------------------
1315 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
1316 {
1317   if ( _nbLayers != nb )
1318     _nbLayers = nb, NotifySubMeshesHypothesisModification();
1319 } // --------------------------------------------------------------------------------
1320 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
1321 {
1322   if ( _stretchFactor != factor )
1323     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
1324 } // --------------------------------------------------------------------------------
1325 void StdMeshers_ViscousLayers::SetMethod( ExtrusionMethod method )
1326 {
1327   if ( _method != method )
1328     _method = method, NotifySubMeshesHypothesisModification();
1329 } // --------------------------------------------------------------------------------
1330 void StdMeshers_ViscousLayers::SetGroupName(const std::string& name)
1331 {
1332   if ( _groupName != name )
1333   {
1334     _groupName = name;
1335     if ( !_groupName.empty() )
1336       NotifySubMeshesHypothesisModification();
1337   }
1338 } // --------------------------------------------------------------------------------
1339 SMESH_ProxyMesh::Ptr
1340 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
1341                                   const TopoDS_Shape& theShape,
1342                                   const bool          toMakeN2NMap) const
1343 {
1344   using namespace VISCOUS_3D;
1345   _ViscousBuilder builder;
1346   SMESH_ComputeErrorPtr err = builder.Compute( theMesh, theShape );
1347   if ( err && !err->IsOK() )
1348     return SMESH_ProxyMesh::Ptr();
1349
1350   vector<SMESH_ProxyMesh::Ptr> components;
1351   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1352   for ( ; exp.More(); exp.Next() )
1353   {
1354     if ( _MeshOfSolid* pm =
1355          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
1356     {
1357       if ( toMakeN2NMap && !pm->_n2nMapComputed )
1358         if ( !builder.MakeN2NMap( pm ))
1359           return SMESH_ProxyMesh::Ptr();
1360       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
1361       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
1362
1363       if ( pm->_warning && !pm->_warning->IsOK() )
1364       {
1365         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
1366         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1367         if ( !smError || smError->IsOK() )
1368           smError = pm->_warning;
1369       }
1370     }
1371     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
1372   }
1373   switch ( components.size() )
1374   {
1375   case 0: break;
1376
1377   case 1: return components[0];
1378
1379   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
1380   }
1381   return SMESH_ProxyMesh::Ptr();
1382 } // --------------------------------------------------------------------------------
1383 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
1384 {
1385   save << " " << _nbLayers
1386        << " " << _thickness
1387        << " " << _stretchFactor
1388        << " " << _shapeIds.size();
1389   for ( size_t i = 0; i < _shapeIds.size(); ++i )
1390     save << " " << _shapeIds[i];
1391   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
1392   save << " " << _method;
1393   save << " " << _groupName.size();
1394   if ( !_groupName.empty() )
1395     save << " " << _groupName;
1396   return save;
1397 } // --------------------------------------------------------------------------------
1398 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
1399 {
1400   int nbFaces, faceID, shapeToTreat, method;
1401   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
1402   while ( (int) _shapeIds.size() < nbFaces && load >> faceID )
1403     _shapeIds.push_back( faceID );
1404   if ( load >> shapeToTreat ) {
1405     _isToIgnoreShapes = !shapeToTreat;
1406     if ( load >> method )
1407       _method = (ExtrusionMethod) method;
1408     int nameSize = 0;
1409     if ( load >> nameSize && nameSize > 0 )
1410     {
1411       _groupName.resize( nameSize );
1412       load.get( _groupName[0] ); // remove a white-space
1413       load.getline( &_groupName[0], nameSize + 1 );
1414     }
1415   }
1416   else {
1417     _isToIgnoreShapes = true; // old behavior
1418   }
1419   return load;
1420 } // --------------------------------------------------------------------------------
1421 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   /*theMesh*/,
1422                                                    const TopoDS_Shape& /*theShape*/)
1423 {
1424   // TODO
1425   return false;
1426 } // --------------------------------------------------------------------------------
1427 SMESH_ComputeErrorPtr
1428 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
1429                                           const TopoDS_Shape&                  theShape,
1430                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
1431 {
1432   VISCOUS_3D::_ViscousBuilder builder;
1433   SMESH_ComputeErrorPtr err = builder.CheckHypotheses( theMesh, theShape );
1434   if ( err && !err->IsOK() )
1435     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
1436   else
1437     theStatus = SMESH_Hypothesis::HYP_OK;
1438
1439   return err;
1440 }
1441 // --------------------------------------------------------------------------------
1442 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
1443 {
1444   bool isIn =
1445     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
1446   return IsToIgnoreShapes() ? !isIn : isIn;
1447 }
1448
1449 // --------------------------------------------------------------------------------
1450 SMDS_MeshGroup* StdMeshers_ViscousLayers::CreateGroup( const std::string&  theName,
1451                                                        SMESH_Mesh&         theMesh,
1452                                                        SMDSAbs_ElementType theType)
1453 {
1454   SMESH_Group*      group = 0;
1455   SMDS_MeshGroup* groupDS = 0;
1456
1457   if ( theName.empty() )
1458     return groupDS;
1459        
1460   if ( SMESH_Mesh::GroupIteratorPtr grIt = theMesh.GetGroups() )
1461     while( grIt->more() && !group )
1462     {
1463       group = grIt->next();
1464       if ( !group ||
1465            group->GetGroupDS()->GetType() != theType ||
1466            group->GetName()               != theName ||
1467            !dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() ))
1468         group = 0;
1469     }
1470   if ( !group )
1471     group = theMesh.AddGroup( theType, theName.c_str() );
1472
1473   groupDS = & dynamic_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
1474
1475   return groupDS;
1476 }
1477
1478 // END StdMeshers_ViscousLayers hypothesis
1479 //================================================================================
1480
1481 namespace VISCOUS_3D
1482 {
1483   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV,
1484                      const double h0, bool* isRegularEdge = nullptr )
1485   {
1486     gp_Vec dir;
1487     double f,l;
1488     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1489     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1490     gp_Pnt  p = BRep_Tool::Pnt( fromV );
1491     gp_Pnt pf = c->Value( f ), pl = c->Value( l );
1492     double distF = p.SquareDistance( pf );
1493     double distL = p.SquareDistance( pl );
1494     c->D1(( distF < distL ? f : l), p, dir );
1495     if ( distL < distF ) dir.Reverse();
1496     bool isDifficult = false;
1497     if ( dir.SquareMagnitude() < h0 * h0 ) // check dir orientation
1498     {
1499       gp_Pnt& pClose = distF < distL ? pf : pl;
1500       gp_Pnt&   pFar = distF < distL ? pl : pf;
1501       gp_Pnt    pMid = 0.9 * pClose.XYZ() + 0.1 * pFar.XYZ();
1502       gp_Vec vMid( p, pMid );
1503       double     dot = vMid * dir;
1504       double    cos2 = dot * dot / dir.SquareMagnitude() / vMid.SquareMagnitude();
1505       if ( cos2 < 0.7 * 0.7 || dot < 0 ) // large angle between dir and vMid
1506       {
1507         double uClose = distF < distL ? f : l;
1508         double   uFar = distF < distL ? l : f;
1509         double      r = h0 / SMESH_Algo::EdgeLength( E );
1510         double   uMid = ( 1 - r ) * uClose + r * uFar;
1511         pMid = c->Value( uMid );
1512         dir = gp_Vec( p, pMid );
1513         isDifficult = true;
1514       }
1515     }
1516     if ( isRegularEdge )
1517       *isRegularEdge = !isDifficult;
1518
1519     return dir.XYZ();
1520   }
1521   //--------------------------------------------------------------------------------
1522   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
1523                      SMESH_MesherHelper& helper)
1524   {
1525     gp_Vec dir;
1526     double f,l; gp_Pnt p;
1527     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1528     if ( c.IsNull() ) return gp_XYZ( Precision::Infinite(), 1e100, 1e100 );
1529     double u = helper.GetNodeU( E, atNode );
1530     c->D1( u, p, dir );
1531     return dir.XYZ();
1532   }
1533   //--------------------------------------------------------------------------------
1534   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1535                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok/*,
1536                      double* cosin=0*/);
1537   //--------------------------------------------------------------------------------
1538   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1539                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1540   {
1541     double f,l;
1542     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1543     if ( c.IsNull() )
1544     {
1545       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1546       return getFaceDir( F, v, node, helper, ok );
1547     }
1548     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1549     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1550     gp_Pnt p; gp_Vec du, dv, norm;
1551     surface->D1( uv.X(),uv.Y(), p, du,dv );
1552     norm = du ^ dv;
1553
1554     double u = helper.GetNodeU( fromE, node, 0, &ok );
1555     c->D1( u, p, du );
1556     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1557     if ( o == TopAbs_REVERSED )
1558       du.Reverse();
1559
1560     gp_Vec dir = norm ^ du;
1561
1562     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1563          helper.IsClosedEdge( fromE ))
1564     {
1565       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1566       else                        c->D1( f, p, dv );
1567       if ( o == TopAbs_REVERSED )
1568         dv.Reverse();
1569       gp_Vec dir2 = norm ^ dv;
1570       dir = dir.Normalized() + dir2.Normalized();
1571     }
1572     return dir.XYZ();
1573   }
1574   //--------------------------------------------------------------------------------
1575   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1576                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1577                      bool& ok/*, double* cosin*/)
1578   {
1579     TopoDS_Face faceFrw = F;
1580     faceFrw.Orientation( TopAbs_FORWARD );
1581     //double f,l; TopLoc_Location loc;
1582     TopoDS_Edge edges[2]; // sharing a vertex
1583     size_t nbEdges = 0;
1584     {
1585       TopoDS_Vertex VV[2];
1586       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1587       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1588       {
1589         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1590         if ( SMESH_Algo::isDegenerated( e )) continue;
1591         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1592         if ( VV[1].IsSame( fromV )) {
1593           nbEdges += edges[ 0 ].IsNull();
1594           edges[ 0 ] = e;
1595         }
1596         else if ( VV[0].IsSame( fromV )) {
1597           nbEdges += edges[ 1 ].IsNull();
1598           edges[ 1 ] = e;
1599         }
1600       }
1601     }
1602     gp_XYZ dir(0,0,0), edgeDir[2];
1603     if ( nbEdges == 2 )
1604     {
1605       // get dirs of edges going fromV
1606       ok = true;
1607       for ( size_t i = 0; i < nbEdges && ok; ++i )
1608       {
1609         edgeDir[i] = getEdgeDir( edges[i], fromV, 0.1 * SMESH_Algo::EdgeLength( edges[i] ));
1610         double size2 = edgeDir[i].SquareModulus();
1611         if (( ok = size2 > numeric_limits<double>::min() ))
1612           edgeDir[i] /= sqrt( size2 );
1613       }
1614       if ( !ok ) return dir;
1615
1616       // get angle between the 2 edges
1617       gp_Vec faceNormal;
1618       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1619       if ( Abs( angle ) < 5 * M_PI/180 )
1620       {
1621         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1622       }
1623       else
1624       {
1625         dir = edgeDir[0] + edgeDir[1];
1626         if ( angle < 0 )
1627           dir.Reverse();
1628       }
1629       // if ( cosin ) {
1630       //   double angle = faceNormal.Angle( dir );
1631       //   *cosin = Cos( angle );
1632       // }
1633     }
1634     else if ( nbEdges == 1 )
1635     {
1636       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1637       //if ( cosin ) *cosin = 1.;
1638     }
1639     else
1640     {
1641       ok = false;
1642     }
1643
1644     return dir;
1645   }
1646
1647   //================================================================================
1648   /*!
1649    * \brief Finds concave VERTEXes of a FACE
1650    */
1651   //================================================================================
1652
1653   bool getConcaveVertices( const TopoDS_Face&  F,
1654                            SMESH_MesherHelper& helper,
1655                            set< TGeomID >*     vertices = 0)
1656   {
1657     // check angles at VERTEXes
1658     TError error;
1659     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1660     for ( size_t iW = 0; iW < wires.size(); ++iW )
1661     {
1662       const int nbEdges = wires[iW]->NbEdges();
1663       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1664         continue;
1665       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1666       {
1667         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1668         int iE2 = ( iE1 + 1 ) % nbEdges;
1669         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1670           iE2 = ( iE2 + 1 ) % nbEdges;
1671         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1672         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1673                                         wires[iW]->Edge( iE2 ), F, V );
1674         if ( angle < -5. * M_PI / 180. )
1675         {
1676           if ( !vertices )
1677             return true;
1678           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1679         }
1680       }
1681     }
1682     return vertices ? !vertices->empty() : false;
1683   }
1684
1685   //================================================================================
1686   /*!
1687    * \brief Returns true if a FACE is bound by a concave EDGE
1688    */
1689   //================================================================================
1690
1691   bool isConcave( const TopoDS_Face&  F,
1692                   SMESH_MesherHelper& helper,
1693                   set< TGeomID >*     vertices = 0 )
1694   {
1695     bool isConcv = false;
1696     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1697     //   return true;
1698     gp_Vec2d drv1, drv2;
1699     gp_Pnt2d p;
1700     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1701     for ( ; eExp.More(); eExp.Next() )
1702     {
1703       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1704       if ( SMESH_Algo::isDegenerated( E )) continue;
1705       // check if 2D curve is concave
1706       BRepAdaptor_Curve2d curve( E, F );
1707       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1708       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1709       curve.Intervals( intervals, GeomAbs_C2 );
1710       bool isConvex = true;
1711       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1712       {
1713         double u1 = intervals( i );
1714         double u2 = intervals( i+1 );
1715         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1716         double cross = drv1 ^ drv2;
1717         if ( E.Orientation() == TopAbs_REVERSED )
1718           cross = -cross;
1719         isConvex = ( cross > -1e-9 ); // 0.1 );
1720       }
1721       if ( !isConvex )
1722       {
1723         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1724         isConcv = true;
1725         if ( vertices )
1726           break;
1727         else
1728           return true;
1729       }
1730     }
1731
1732     // check angles at VERTEXes
1733     if ( getConcaveVertices( F, helper, vertices ))
1734       isConcv = true;
1735
1736     return isConcv;
1737   }
1738
1739   //================================================================================
1740   /*!
1741    * \brief Computes minimal distance of face in-FACE nodes from an EDGE
1742    *  \param [in] face - the mesh face to treat
1743    *  \param [in] nodeOnEdge - a node on the EDGE
1744    *  \param [out] faceSize - the computed distance
1745    *  \return bool - true if faceSize computed
1746    */
1747   //================================================================================
1748
1749   bool getDistFromEdge( const SMDS_MeshElement* face,
1750                         const SMDS_MeshNode*    nodeOnEdge,
1751                         double &                faceSize )
1752   {
1753     faceSize = Precision::Infinite();
1754     bool done = false;
1755
1756     int nbN  = face->NbCornerNodes();
1757     int iOnE = face->GetNodeIndex( nodeOnEdge );
1758     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1759                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1760     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1761                                       face->GetNode( iNext[1] ) };
1762     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1763     double segLen = -1.;
1764     // look for two neighbor not in-FACE nodes of face
1765     for ( int i = 0; i < 2; ++i )
1766     {
1767       if (( nNext[i]->GetPosition()->GetDim() != 2 ) &&
1768           ( nodeOnEdge->GetPosition()->GetDim() == 0 || nNext[i]->GetID() < nodeOnEdge->GetID() ))
1769       {
1770         // look for an in-FACE node
1771         for ( int iN = 0; iN < nbN; ++iN )
1772         {
1773           if ( iN == iOnE || iN == iNext[i] )
1774             continue;
1775           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1776           gp_XYZ v = pInFace - segEnd;
1777           if ( segLen < 0 )
1778           {
1779             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1780             segLen = segVec.Modulus();
1781           }
1782           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1783           faceSize = Min( faceSize, distToSeg );
1784           done = true;
1785         }
1786         segLen = -1;
1787       }
1788     }
1789     return done;
1790   }
1791   //================================================================================
1792   /*!
1793    * \brief Return direction of axis or revolution of a surface
1794    */
1795   //================================================================================
1796
1797   bool getRovolutionAxis( const Adaptor3d_Surface& surface,
1798                           gp_Dir &                 axis )
1799   {
1800     switch ( surface.GetType() ) {
1801     case GeomAbs_Cone:
1802     {
1803       gp_Cone cone = surface.Cone();
1804       axis = cone.Axis().Direction();
1805       break;
1806     }
1807     case GeomAbs_Sphere:
1808     {
1809       gp_Sphere sphere = surface.Sphere();
1810       axis = sphere.Position().Direction();
1811       break;
1812     }
1813     case GeomAbs_SurfaceOfRevolution:
1814     {
1815       axis = surface.AxeOfRevolution().Direction();
1816       break;
1817     }
1818     //case GeomAbs_SurfaceOfExtrusion:
1819     case GeomAbs_OffsetSurface:
1820     {
1821       Handle(Adaptor3d_HSurface) base = surface.BasisSurface();
1822       return getRovolutionAxis( base->Surface(), axis );
1823     }
1824     default: return false;
1825     }
1826     return true;
1827   }
1828
1829   //--------------------------------------------------------------------------------
1830   // DEBUG. Dump intermediate node positions into a python script
1831   // HOWTO use: run python commands written in a console and defined in /tmp/viscous.py
1832   // to see construction steps of viscous layers
1833 #ifdef __myDEBUG
1834   ostream* py;
1835   int      theNbPyFunc;
1836   struct PyDump
1837   {
1838     PyDump(SMESH_Mesh& m) {
1839       int tag = 3 + m.GetId();
1840       const char* fname = "/tmp/viscous.py";
1841       cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
1842       py = _pyStream = new ofstream(fname);
1843       *py << "import SMESH" << endl
1844           << "from salome.smesh import smeshBuilder" << endl
1845           << "smesh  = smeshBuilder.New()" << endl
1846           << "meshSO = salome.myStudy.FindObjectID('0:1:2:" << tag <<"')" << endl
1847           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1848       theNbPyFunc = 0;
1849     }
1850     void Finish() {
1851       if (py) {
1852         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1853           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1854         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1855           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1856       }
1857       delete py; py=0;
1858     }
1859     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1860     struct MyStream : public ostream
1861     {
1862       template <class T> ostream & operator<<( const T &anything ) { return *this ; }
1863     };
1864     void Pause() { py = &_mystream; }
1865     void Resume() { py = _pyStream; }
1866     MyStream _mystream;
1867     ostream* _pyStream;
1868   };
1869 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1870 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1871 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1872 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1873   void _dumpFunction(const string& fun, int ln)
1874   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1875   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1876   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1877                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1878   void _dumpCmd(const string& txt, int ln)
1879   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1880   void dumpFunctionEnd()
1881   { if (py) *py<< "  return"<< endl; }
1882   void dumpChangeNodes( const SMDS_MeshElement* f )
1883   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1884       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1885       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1886 #define debugMsg( txt ) { cout << "# "<< txt << " (line: " << __LINE__ << ")" << endl; }
1887
1888 #else
1889
1890   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} void Pause() {} void Resume() {} };
1891 #define dumpFunction(f) f
1892 #define dumpMove(n)
1893 #define dumpMoveComm(n,txt)
1894 #define dumpCmd(txt)
1895 #define dumpFunctionEnd()
1896 #define dumpChangeNodes(f) { if(f) {} } // prevent "unused variable 'f'" warning
1897 #define debugMsg( txt ) {}
1898
1899 #endif
1900 }
1901
1902 using namespace VISCOUS_3D;
1903
1904 //================================================================================
1905 /*!
1906  * \brief Constructor of _ViscousBuilder
1907  */
1908 //================================================================================
1909
1910 _ViscousBuilder::_ViscousBuilder()
1911 {
1912   _error = SMESH_ComputeError::New(COMPERR_OK);
1913   _tmpFaceID = 0;
1914 }
1915
1916 //================================================================================
1917 /*!
1918  * \brief Stores error description and returns false
1919  */
1920 //================================================================================
1921
1922 bool _ViscousBuilder::error(const string& text, int solidId )
1923 {
1924   const string prefix = string("Viscous layers builder: ");
1925   _error->myName    = COMPERR_ALGO_FAILED;
1926   _error->myComment = prefix + text;
1927   if ( _mesh )
1928   {
1929     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1930     if ( !sm && !_sdVec.empty() )
1931       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1932     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1933     {
1934       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1935       if ( smError && smError->myAlgo )
1936         _error->myAlgo = smError->myAlgo;
1937       smError = _error;
1938       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1939     }
1940     // set KO to all solids
1941     for ( size_t i = 0; i < _sdVec.size(); ++i )
1942     {
1943       if ( _sdVec[i]._index == solidId )
1944         continue;
1945       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1946       if ( !sm->IsEmpty() )
1947         continue;
1948       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1949       if ( !smError || smError->IsOK() )
1950       {
1951         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1952         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1953       }
1954     }
1955   }
1956   makeGroupOfLE(); // debug
1957
1958   return false;
1959 }
1960
1961 //================================================================================
1962 /*!
1963  * \brief At study restoration, restore event listeners used to clear an inferior
1964  *  dim sub-mesh modified by viscous layers
1965  */
1966 //================================================================================
1967
1968 void _ViscousBuilder::RestoreListeners()
1969 {
1970   // TODO
1971 }
1972
1973 //================================================================================
1974 /*!
1975  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1976  */
1977 //================================================================================
1978
1979 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1980 {
1981   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1982   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1983   for ( ; fExp.More(); fExp.Next() )
1984   {
1985     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1986     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1987
1988     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1989       continue;
1990     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1991       continue;
1992
1993     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1994       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1995
1996     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1997     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1998     while( prxIt->more() )
1999     {
2000       const SMDS_MeshElement* fSrc = srcIt->next();
2001       const SMDS_MeshElement* fPrx = prxIt->next();
2002       if ( fSrc->NbNodes() != fPrx->NbNodes())
2003         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
2004       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
2005         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
2006     }
2007   }
2008   pm->_n2nMapComputed = true;
2009   return true;
2010 }
2011
2012 //================================================================================
2013 /*!
2014  * \brief Does its job
2015  */
2016 //================================================================================
2017
2018 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
2019                                                const TopoDS_Shape& theShape)
2020 {
2021   _mesh = & theMesh;
2022
2023   _Factory factory;
2024
2025   // check if proxy mesh already computed
2026   TopExp_Explorer exp( theShape, TopAbs_SOLID );
2027   if ( !exp.More() )
2028     return error("No SOLID's in theShape"), _error;
2029
2030   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
2031     return SMESH_ComputeErrorPtr(); // everything already computed
2032
2033   // TODO: ignore already computed SOLIDs
2034   if ( !findSolidsWithLayers())
2035     return _error;
2036
2037   if ( !findFacesWithLayers() )
2038     return _error;
2039
2040   if ( !makeEdgesOnShape() )
2041     return _error;
2042
2043   findPeriodicFaces();
2044
2045   PyDump debugDump( theMesh );
2046   _pyDump = &debugDump;
2047
2048
2049   for ( size_t i = 0; i < _sdVec.size(); ++i )
2050   {
2051     size_t iSD = 0;
2052     for ( iSD = 0; iSD < _sdVec.size(); ++iSD ) // find next SOLID to compute
2053       if ( _sdVec[iSD]._before.IsEmpty() &&
2054            !_sdVec[iSD]._solid.IsNull() &&
2055            !_sdVec[iSD]._done )
2056         break;
2057     if ( iSD == _sdVec.size() )
2058       break; // all done
2059
2060     if ( ! makeLayer(_sdVec[iSD]) )   // create _LayerEdge's
2061       return _error;
2062
2063     if ( _sdVec[iSD]._n2eMap.size() == 0 ) // no layers in a SOLID
2064     {
2065       _sdVec[iSD]._solid.Nullify();
2066       continue;
2067     }
2068
2069     if ( ! inflate(_sdVec[iSD]) )     // increase length of _LayerEdge's
2070       return _error;
2071
2072     if ( ! refine(_sdVec[iSD]) )      // create nodes and prisms
2073       return _error;
2074
2075     if ( ! shrink(_sdVec[iSD]) )      // shrink 2D mesh on FACEs w/o layer
2076       return _error;
2077
2078     addBoundaryElements(_sdVec[iSD]); // create quadrangles on prism bare sides
2079
2080     _sdVec[iSD]._done = true;
2081
2082     const TopoDS_Shape& solid = _sdVec[iSD]._solid;
2083     for ( iSD = 0; iSD < _sdVec.size(); ++iSD )
2084       _sdVec[iSD]._before.Remove( solid );
2085   }
2086
2087   makeGroupOfLE(); // debug
2088   debugDump.Finish();
2089
2090   return _error;
2091 }
2092
2093 //================================================================================
2094 /*!
2095  * \brief Check validity of hypotheses
2096  */
2097 //================================================================================
2098
2099 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
2100                                                         const TopoDS_Shape& shape )
2101 {
2102   _mesh = & mesh;
2103
2104   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
2105     return SMESH_ComputeErrorPtr(); // everything already computed
2106
2107
2108   findSolidsWithLayers( /*checkFaceMesh=*/false );
2109   bool ok = findFacesWithLayers( true );
2110
2111   // remove _MeshOfSolid's of _SolidData's
2112   for ( size_t i = 0; i < _sdVec.size(); ++i )
2113     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
2114
2115   if ( !ok )
2116     return _error;
2117
2118   return SMESH_ComputeErrorPtr();
2119 }
2120
2121 //================================================================================
2122 /*!
2123  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
2124  */
2125 //================================================================================
2126
2127 bool _ViscousBuilder::findSolidsWithLayers(const bool checkFaceMesh)
2128 {
2129   // get all solids
2130   TopTools_IndexedMapOfShape allSolids;
2131   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
2132   _sdVec.reserve( allSolids.Extent());
2133
2134   SMESH_HypoFilter filter;
2135   for ( int i = 1; i <= allSolids.Extent(); ++i )
2136   {
2137     SMESH_subMesh* sm = _mesh->GetSubMesh( allSolids(i) );
2138     if ( sm->GetSubMeshDS() && sm->GetSubMeshDS()->NbElements() > 0 )
2139       continue; // solid is already meshed
2140     // TODO: check if algo is hidden
2141     SMESH_Algo* algo = sm->GetAlgo();
2142     if ( !algo ) continue;
2143     // check if all FACEs are meshed, which can be false if Compute() a sub-shape
2144     if ( checkFaceMesh )
2145     {
2146       bool facesMeshed = true;
2147       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,true);
2148       while ( smIt->more() && facesMeshed )
2149       {
2150         SMESH_subMesh * faceSM = smIt->next();
2151         if ( faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2152           break;
2153         facesMeshed = faceSM->IsMeshComputed();
2154       }
2155       if ( !facesMeshed )
2156         continue;
2157     }
2158     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
2159     const list <const SMESHDS_Hypothesis *> & allHyps =
2160       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
2161     _SolidData* soData = 0;
2162     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
2163     const StdMeshers_ViscousLayers* viscHyp = 0;
2164     for ( ; hyp != allHyps.end(); ++hyp )
2165       if (( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp )))
2166       {
2167         TopoDS_Shape hypShape;
2168         filter.Init( filter.Is( viscHyp ));
2169         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
2170
2171         if ( !soData )
2172         {
2173           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
2174                                                                     allSolids(i),
2175                                                                     /*toCreate=*/true);
2176           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
2177           soData = & _sdVec.back();
2178           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
2179           soData->_helper = new SMESH_MesherHelper( *_mesh );
2180           soData->_helper->SetSubShape( allSolids(i) );
2181           _solids.Add( allSolids(i) );
2182         }
2183         soData->_hyps.push_back( viscHyp );
2184         soData->_hypShapes.push_back( hypShape );
2185       }
2186   }
2187   if ( _sdVec.empty() )
2188     return error
2189       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
2190
2191   return true;
2192 }
2193
2194 //================================================================================
2195 /*!
2196  * \brief Set a _SolidData to be computed before another
2197  */
2198 //================================================================================
2199
2200 bool _ViscousBuilder::setBefore( _SolidData& solidBefore, _SolidData& solidAfter )
2201 {
2202   // check possibility to set this order; get all solids before solidBefore
2203   TopTools_IndexedMapOfShape allSolidsBefore;
2204   allSolidsBefore.Add( solidBefore._solid );
2205   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2206   {
2207     int iSD = _solids.FindIndex( allSolidsBefore(i) );
2208     if ( iSD )
2209     {
2210       TopTools_MapIteratorOfMapOfShape soIt( _sdVec[ iSD-1 ]._before );
2211       for ( ; soIt.More(); soIt.Next() )
2212         allSolidsBefore.Add( soIt.Value() );
2213     }
2214   }
2215   if ( allSolidsBefore.Contains( solidAfter._solid ))
2216     return false;
2217
2218   for ( int i = 1; i <= allSolidsBefore.Extent(); ++i )
2219     solidAfter._before.Add( allSolidsBefore(i) );
2220
2221   return true;
2222 }
2223
2224 //================================================================================
2225 /*!
2226  * \brief
2227  */
2228 //================================================================================
2229
2230 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
2231 {
2232   SMESH_MesherHelper helper( *_mesh );
2233   TopExp_Explorer exp;
2234
2235   // collect all faces-to-ignore defined by hyp
2236   for ( size_t i = 0; i < _sdVec.size(); ++i )
2237   {
2238     // get faces-to-ignore defined by each hyp
2239     typedef const StdMeshers_ViscousLayers* THyp;
2240     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
2241     list< TFacesOfHyp > ignoreFacesOfHyps;
2242     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
2243     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
2244     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
2245     {
2246       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
2247       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
2248     }
2249
2250     // fill _SolidData::_face2hyp and check compatibility of hypotheses
2251     const int nbHyps = _sdVec[i]._hyps.size();
2252     if ( nbHyps > 1 )
2253     {
2254       // check if two hypotheses define different parameters for the same FACE
2255       list< TFacesOfHyp >::iterator igFacesOfHyp;
2256       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2257       {
2258         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
2259         THyp hyp = 0;
2260         igFacesOfHyp = ignoreFacesOfHyps.begin();
2261         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2262           if ( ! igFacesOfHyp->first.count( faceID ))
2263           {
2264             if ( hyp )
2265               return error(SMESH_Comment("Several hypotheses define "
2266                                          "Viscous Layers on the face #") << faceID );
2267             hyp = igFacesOfHyp->second;
2268           }
2269         if ( hyp )
2270           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
2271         else
2272           _sdVec[i]._ignoreFaceIds.insert( faceID );
2273       }
2274
2275       // check if two hypotheses define different number of viscous layers for
2276       // adjacent faces of a solid
2277       set< int > nbLayersSet;
2278       igFacesOfHyp = ignoreFacesOfHyps.begin();
2279       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
2280       {
2281         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
2282       }
2283       if ( nbLayersSet.size() > 1 )
2284       {
2285         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
2286         {
2287           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
2288           THyp hyp1 = 0, hyp2 = 0;
2289           while( const TopoDS_Shape* face = fIt->next() )
2290           {
2291             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2292             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
2293             if ( f2h != _sdVec[i]._face2hyp.end() )
2294             {
2295               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
2296             }
2297           }
2298           if ( hyp1 && hyp2 &&
2299                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
2300           {
2301             return error("Two hypotheses define different number of "
2302                          "viscous layers on adjacent faces");
2303           }
2304         }
2305       }
2306     } // if ( nbHyps > 1 )
2307     else
2308     {
2309       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
2310     }
2311   } // loop on _sdVec
2312
2313   if ( onlyWith ) // is called to check hypotheses compatibility only
2314     return true;
2315
2316   // fill _SolidData::_reversedFaceIds
2317   for ( size_t i = 0; i < _sdVec.size(); ++i )
2318   {
2319     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
2320     for ( ; exp.More(); exp.Next() )
2321     {
2322       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2323       const TGeomID    faceID = getMeshDS()->ShapeToIndex( face );
2324       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
2325           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
2326           helper.IsReversedSubMesh( face ))
2327       {
2328         _sdVec[i]._reversedFaceIds.insert( faceID );
2329       }
2330     }
2331   }
2332
2333   // Find FACEs to shrink mesh on (solution 2 in issue 0020832): fill in _shrinkShape2Shape
2334   TopTools_IndexedMapOfShape shapes;
2335   std::string structAlgoName = "Hexa_3D";
2336   for ( size_t i = 0; i < _sdVec.size(); ++i )
2337   {
2338     shapes.Clear();
2339     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
2340     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2341     {
2342       const TopoDS_Shape& edge = shapes(iE);
2343       // find 2 FACEs sharing an EDGE
2344       TopoDS_Shape FF[2];
2345       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE, &_sdVec[i]._solid);
2346       while ( fIt->more())
2347       {
2348         const TopoDS_Shape* f = fIt->next();
2349         FF[ int( !FF[0].IsNull()) ] = *f;
2350       }
2351       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
2352
2353       // check presence of layers on them
2354       int ignore[2];
2355       for ( int j = 0; j < 2; ++j )
2356         ignore[j] = _sdVec[i]._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( FF[j] ));
2357       if ( ignore[0] == ignore[1] )
2358         continue; // nothing interesting
2359       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ]; // FACE w/o layers
2360
2361       // add EDGE to maps
2362       if ( !fWOL.IsNull())
2363       {
2364         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
2365         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
2366       }
2367     }
2368   }
2369
2370   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
2371
2372   for ( size_t i = 0; i < _sdVec.size(); ++i )
2373   {
2374     shapes.Clear();
2375     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
2376     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
2377     {
2378       const TopoDS_Shape& vertex = shapes(iV);
2379       // find faces WOL sharing the vertex
2380       vector< TopoDS_Shape > facesWOL;
2381       size_t totalNbFaces = 0;
2382       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE, &_sdVec[i]._solid );
2383       while ( fIt->more())
2384       {
2385         const TopoDS_Shape* f = fIt->next();
2386         totalNbFaces++;
2387         const int fID = getMeshDS()->ShapeToIndex( *f );
2388         if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&& !_sdVec[i]._noShrinkShapes.count( fID )*/)
2389           facesWOL.push_back( *f );
2390       }
2391       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
2392         continue; // no layers at this vertex or no WOL
2393       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
2394       switch ( facesWOL.size() )
2395       {
2396       case 1:
2397       {
2398         helper.SetSubShape( facesWOL[0] );
2399         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
2400         {
2401           TopoDS_Shape seamEdge;
2402           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2403           while ( eIt->more() && seamEdge.IsNull() )
2404           {
2405             const TopoDS_Shape* e = eIt->next();
2406             if ( helper.IsRealSeam( *e ) )
2407               seamEdge = *e;
2408           }
2409           if ( !seamEdge.IsNull() )
2410           {
2411             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
2412             break;
2413           }
2414         }
2415         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
2416         break;
2417       }
2418       case 2:
2419       {
2420         // find an edge shared by 2 faces
2421         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
2422         while ( eIt->more())
2423         {
2424           const TopoDS_Shape* e = eIt->next();
2425           if ( helper.IsSubShape( *e, facesWOL[0]) &&
2426                helper.IsSubShape( *e, facesWOL[1]))
2427           {
2428             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
2429           }
2430         }
2431         break;
2432       }
2433       default:
2434         return error("Not yet supported case", _sdVec[i]._index);
2435       }
2436     }
2437   }
2438
2439   // Add to _noShrinkShapes sub-shapes of FACE's that can't be shrunk since
2440   // the algo of the SOLID sharing the FACE does not support it or for other reasons
2441   set< string > notSupportAlgos; notSupportAlgos.insert( structAlgoName );
2442   for ( size_t i = 0; i < _sdVec.size(); ++i )
2443   {
2444     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
2445     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
2446     {
2447       const TopoDS_Shape& fWOL = e2f->second;
2448       const TGeomID     edgeID = e2f->first;
2449       TGeomID           faceID = getMeshDS()->ShapeToIndex( fWOL );
2450       TopoDS_Shape        edge = getMeshDS()->IndexToShape( edgeID );
2451       if ( edge.ShapeType() != TopAbs_EDGE )
2452         continue; // shrink shape is VERTEX
2453
2454       TopoDS_Shape solid;
2455       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
2456       while ( soIt->more() && solid.IsNull() )
2457       {
2458         const TopoDS_Shape* so = soIt->next();
2459         if ( !so->IsSame( _sdVec[i]._solid ))
2460           solid = *so;
2461       }
2462       if ( solid.IsNull() )
2463         continue;
2464
2465       bool noShrinkE = false;
2466       SMESH_Algo*  algo = _mesh->GetSubMesh( solid )->GetAlgo();
2467       bool isStructured = ( algo && algo->GetName() == structAlgoName );
2468       size_t     iSolid = _solids.FindIndex( solid ) - 1;
2469       if ( iSolid < _sdVec.size() && _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2470       {
2471         // the adjacent SOLID has NO layers on fWOL;
2472         // shrink allowed if
2473         // - there are layers on the EDGE in the adjacent SOLID
2474         // - there are NO layers in the adjacent SOLID && algo is unstructured and computed later
2475         bool hasWLAdj = (_sdVec[iSolid]._shrinkShape2Shape.count( edgeID ));
2476         bool shrinkAllowed = (( hasWLAdj ) ||
2477                               ( !isStructured && setBefore( _sdVec[ i ], _sdVec[ iSolid ] )));
2478         noShrinkE = !shrinkAllowed;
2479       }
2480       else if ( iSolid < _sdVec.size() )
2481       {
2482         // the adjacent SOLID has layers on fWOL;
2483         // check if SOLID's mesh is unstructured and then try to set it
2484         // to be computed after the i-th solid
2485         if ( isStructured || !setBefore( _sdVec[ i ], _sdVec[ iSolid ] ))
2486           noShrinkE = true; // don't shrink fWOL
2487       }
2488       else
2489       {
2490         // the adjacent SOLID has NO layers at all
2491         noShrinkE = isStructured;
2492       }
2493
2494       if ( noShrinkE )
2495       {
2496         _sdVec[i]._noShrinkShapes.insert( edgeID );
2497
2498         // check if there is a collision with to-shrink-from EDGEs in iSolid
2499         // if ( iSolid < _sdVec.size() )
2500         // {
2501         //   shapes.Clear();
2502         //   TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
2503         //   for ( int iE = 1; iE <= shapes.Extent(); ++iE )
2504         //   {
2505         //     const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
2506         //     const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
2507         //     if ( eID == edgeID ||
2508         //          !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
2509         //          _sdVec[i]._noShrinkShapes.count( eID ))
2510         //       continue;
2511         //     for ( int is1st = 0; is1st < 2; ++is1st )
2512         //     {
2513         //       TopoDS_Vertex V = helper.IthVertex( is1st, E );
2514         //       if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
2515         //       {
2516         //         return error("No way to make a conformal mesh with "
2517         //                      "the given set of faces with layers", _sdVec[i]._index);
2518         //       }
2519         //     }
2520         //   }
2521         // }
2522       }
2523
2524       // add VERTEXes of the edge in _noShrinkShapes, which is necessary if
2525       // _shrinkShape2Shape is different in the adjacent SOLID
2526       for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
2527       {
2528         TGeomID vID = getMeshDS()->ShapeToIndex( vIt.Value() );
2529         bool noShrinkV = false, noShrinkIfAdjMeshed = false;
2530
2531         if ( iSolid < _sdVec.size() )
2532         {
2533           if ( _sdVec[ iSolid ]._ignoreFaceIds.count( faceID ))
2534           {
2535             map< TGeomID, TopoDS_Shape >::iterator i2S, i2SAdj;
2536             i2S    = _sdVec[i     ]._shrinkShape2Shape.find( vID );
2537             i2SAdj = _sdVec[iSolid]._shrinkShape2Shape.find( vID );
2538             if ( i2SAdj == _sdVec[iSolid]._shrinkShape2Shape.end() )
2539               noShrinkV = (( isStructured ) ||
2540                            ( noShrinkIfAdjMeshed = i2S->second.ShapeType() == TopAbs_EDGE ));
2541             else
2542               noShrinkV = ( ! i2S->second.IsSame( i2SAdj->second ));
2543           }
2544           else
2545           {
2546             noShrinkV = noShrinkE;
2547           }
2548         }
2549         else
2550         {
2551           // the adjacent SOLID has NO layers at all
2552           if ( isStructured )
2553           {
2554             noShrinkV = true;
2555           }
2556           else
2557           {
2558             noShrinkV = noShrinkIfAdjMeshed =
2559               ( _sdVec[i]._shrinkShape2Shape[ vID ].ShapeType() == TopAbs_EDGE );
2560           }
2561         }
2562
2563         if ( noShrinkV && noShrinkIfAdjMeshed )
2564         {
2565           // noShrinkV if FACEs in the adjacent SOLID are meshed
2566           PShapeIteratorPtr fIt = helper.GetAncestors( _sdVec[i]._shrinkShape2Shape[ vID ],
2567                                                        *_mesh, TopAbs_FACE, &solid );
2568           while ( fIt->more() )
2569           {
2570             const TopoDS_Shape* f = fIt->next();
2571             if ( !f->IsSame( fWOL ))
2572             {
2573               noShrinkV = ! _mesh->GetSubMesh( *f )->IsEmpty();
2574               break;
2575             }
2576           }
2577         }
2578         if ( noShrinkV )
2579           _sdVec[i]._noShrinkShapes.insert( vID );
2580       }
2581
2582     } // loop on _sdVec[i]._shrinkShape2Shape
2583   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
2584
2585
2586     // add FACEs of other SOLIDs to _ignoreFaceIds
2587   for ( size_t i = 0; i < _sdVec.size(); ++i )
2588   {
2589     shapes.Clear();
2590     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
2591
2592     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
2593     {
2594       if ( !shapes.Contains( exp.Current() ))
2595         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
2596     }
2597   }
2598
2599   return true;
2600 }
2601
2602 //================================================================================
2603 /*!
2604  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
2605  */
2606 //================================================================================
2607
2608 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
2609                                      const StdMeshers_ViscousLayers* hyp,
2610                                      const TopoDS_Shape&             hypShape,
2611                                      set<TGeomID>&                   ignoreFaceIds)
2612 {
2613   TopExp_Explorer exp;
2614
2615   vector<TGeomID> ids = hyp->GetBndShapes();
2616   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
2617   {
2618     for ( size_t ii = 0; ii < ids.size(); ++ii )
2619     {
2620       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
2621       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
2622         ignoreFaceIds.insert( ids[ii] );
2623     }
2624   }
2625   else // FACEs with layers are given
2626   {
2627     exp.Init( solid, TopAbs_FACE );
2628     for ( ; exp.More(); exp.Next() )
2629     {
2630       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
2631       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
2632         ignoreFaceIds.insert( faceInd );
2633     }
2634   }
2635
2636   // ignore internal FACEs if inlets and outlets are specified
2637   if ( hyp->IsToIgnoreShapes() )
2638   {
2639     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
2640     TopExp::MapShapesAndAncestors( hypShape,
2641                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
2642
2643     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
2644     {
2645       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
2646       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
2647         continue;
2648
2649       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
2650       if ( nbSolids > 1 )
2651         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
2652     }
2653   }
2654 }
2655
2656 //================================================================================
2657 /*!
2658  * \brief Create the inner surface of the viscous layer and prepare data for infation
2659  */
2660 //================================================================================
2661
2662 bool _ViscousBuilder::makeLayer(_SolidData& data)
2663 {
2664   // make a map to find new nodes on sub-shapes shared with other SOLID
2665   map< TGeomID, TNode2Edge* >::iterator s2ne;
2666   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
2667   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
2668   {
2669     TGeomID shapeInd = s2s->first;
2670     for ( size_t i = 0; i < _sdVec.size(); ++i )
2671     {
2672       if ( _sdVec[i]._index == data._index ) continue;
2673       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
2674       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
2675            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
2676       {
2677         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
2678         break;
2679       }
2680     }
2681   }
2682
2683   // Create temporary faces and _LayerEdge's
2684
2685   debugMsg( "######################" );
2686   dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
2687
2688   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
2689
2690   data._stepSize = Precision::Infinite();
2691   data._stepSizeNodes[0] = 0;
2692
2693   SMESH_MesherHelper helper( *_mesh );
2694   helper.SetSubShape( data._solid );
2695   helper.SetElementsOnShape( true );
2696
2697   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2698   TNode2Edge::iterator n2e2;
2699
2700   // make _LayerEdge's
2701   for ( TopExp_Explorer exp( data._solid, TopAbs_FACE ); exp.More(); exp.Next() )
2702   {
2703     const TopoDS_Face& F = TopoDS::Face( exp.Current() );
2704     SMESH_subMesh*    sm = _mesh->GetSubMesh( F );
2705     const TGeomID     id = sm->GetId();
2706     if ( edgesByGeom[ id ]._shape.IsNull() )
2707       continue; // no layers
2708     SMESH_ProxyMesh::SubMesh* proxySub =
2709       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2710
2711     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2712     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << id, data._index );
2713
2714     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2715     while ( eIt->more() )
2716     {
2717       const SMDS_MeshElement* face = eIt->next();
2718       double          faceMaxCosin = -1;
2719       _LayerEdge*     maxCosinEdge = 0;
2720       int             nbDegenNodes = 0;
2721
2722       newNodes.resize( face->NbCornerNodes() );
2723       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2724       {
2725         const SMDS_MeshNode* n = face->GetNode( i );
2726         const int      shapeID = n->getshapeId();
2727         const bool onDegenShap = helper.IsDegenShape( shapeID );
2728         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2729         if ( onDegenShap )
2730         {
2731           if ( onDegenEdge )
2732           {
2733             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2734             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2735             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2736             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2737               n = vN;
2738               nbDegenNodes++;
2739             }
2740           }
2741           else
2742           {
2743             nbDegenNodes++;
2744           }
2745         }
2746         TNode2Edge::iterator n2e = data._n2eMap.insert({ n, nullptr }).first;
2747         if ( !(*n2e).second )
2748         {
2749           // add a _LayerEdge
2750           _LayerEdge* edge = _Factory::NewLayerEdge();
2751           edge->_nodes.push_back( n );
2752           n2e->second = edge;
2753           edgesByGeom[ shapeID ]._edges.push_back( edge );
2754           const bool noShrink = data._noShrinkShapes.count( shapeID );
2755
2756           SMESH_TNodeXYZ xyz( n );
2757
2758           // set edge data or find already refined _LayerEdge and get data from it
2759           if (( !noShrink                                                     ) &&
2760               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2761               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2762               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2763           {
2764             _LayerEdge* foundEdge = (*n2e2).second;
2765             gp_XYZ        lastPos = edge->Copy( *foundEdge, edgesByGeom[ shapeID ], helper );
2766             foundEdge->_pos.push_back( lastPos );
2767             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2768             const_cast< SMDS_MeshNode* >
2769               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2770           }
2771           else
2772           {
2773             if ( !noShrink )
2774             {
2775               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2776             }
2777             if ( !setEdgeData( *edge, edgesByGeom[ shapeID ], helper, data ))
2778               return false;
2779
2780             if ( edge->_nodes.size() < 2 && !noShrink )
2781               edge->Block( data ); // a sole node is moved only if noShrink
2782           }
2783           dumpMove(edge->_nodes.back());
2784
2785           if ( edge->_cosin > faceMaxCosin && edge->_nodes.size() > 1 )
2786           {
2787             faceMaxCosin = edge->_cosin;
2788             maxCosinEdge = edge;
2789           }
2790         }
2791         newNodes[ i ] = n2e->second->_nodes.back();
2792
2793         if ( onDegenEdge )
2794           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2795       }
2796       if ( newNodes.size() - nbDegenNodes < 2 )
2797         continue;
2798
2799       // create a temporary face
2800       const SMDS_MeshElement* newFace =
2801         new _TmpMeshFace( newNodes, --_tmpFaceID, face->GetShapeID(), face );
2802       proxySub->AddElement( newFace );
2803
2804       // compute inflation step size by min size of element on a convex surface
2805       if ( faceMaxCosin > theMinSmoothCosin )
2806         limitStepSize( data, face, maxCosinEdge );
2807
2808     } // loop on 2D elements on a FACE
2809   } // loop on FACEs of a SOLID to create _LayerEdge's
2810
2811
2812   // Set _LayerEdge::_neibors
2813   TNode2Edge::iterator n2e;
2814   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2815   {
2816     _EdgesOnShape& eos = data._edgesOnShape[iS];
2817     for ( size_t i = 0; i < eos._edges.size(); ++i )
2818     {
2819       _LayerEdge* edge = eos._edges[i];
2820       TIDSortedNodeSet nearNodes;
2821       SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2822       while ( fIt->more() )
2823       {
2824         const SMDS_MeshElement* f = fIt->next();
2825         if ( !data._ignoreFaceIds.count( f->getshapeId() ))
2826           nearNodes.insert( f->begin_nodes(), f->end_nodes() );
2827       }
2828       nearNodes.erase( edge->_nodes[0] );
2829       edge->_neibors.reserve( nearNodes.size() );
2830       TIDSortedNodeSet::iterator node = nearNodes.begin();
2831       for ( ; node != nearNodes.end(); ++node )
2832         if (( n2e = data._n2eMap.find( *node )) != data._n2eMap.end() )
2833           edge->_neibors.push_back( n2e->second );
2834     }
2835
2836     // Fix uv of nodes on periodic FACEs (bos #20643)
2837
2838     if ( eos.ShapeType() != TopAbs_EDGE ||
2839          eos.SWOLType()  != TopAbs_FACE ||
2840          eos.size() == 0 )
2841       continue;
2842
2843     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
2844     SMESH_MesherHelper faceHelper( *_mesh );
2845     faceHelper.SetSubShape( F );
2846     faceHelper.ToFixNodeParameters( true );
2847     if ( faceHelper.GetPeriodicIndex() == 0 )
2848       continue;
2849
2850     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( F );
2851     if ( !smDS || smDS->GetNodes() == 0 )
2852       continue;
2853
2854     bool toCheck = true;
2855     const double tol = 2 * helper.MaxTolerance( F );
2856     for ( SMDS_NodeIteratorPtr nIt = smDS->GetNodes(); nIt->more(); )
2857     {
2858       const SMDS_MeshNode* node = nIt->next();
2859       gp_XY uvNew( Precision::Infinite(), 0 );
2860       if ( toCheck )
2861       {
2862         toCheck = false;
2863         gp_XY uv = faceHelper.GetNodeUV( F, node );
2864         if ( ! faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true ))
2865           break; // projection on F failed
2866         if (( uv - uvNew ).Modulus() < Precision::Confusion() )
2867           break; // current uv is OK
2868       }
2869       faceHelper.CheckNodeUV( F, node, uvNew, tol, /*force=*/true );
2870     }
2871   }
2872
2873   data._epsilon = 1e-7;
2874   if ( data._stepSize < 1. )
2875     data._epsilon *= data._stepSize;
2876
2877   if ( !findShapesToSmooth( data )) // _LayerEdge::_maxLen is computed here
2878     return false;
2879
2880   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2881   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2882
2883   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2884   const SMDS_MeshNode* nn[2];
2885   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
2886   {
2887     _EdgesOnShape& eos = data._edgesOnShape[iS];
2888     for ( size_t i = 0; i < eos._edges.size(); ++i )
2889     {
2890       _LayerEdge* edge = eos._edges[i];
2891       if ( edge->IsOnEdge() )
2892       {
2893         // get neighbor nodes
2894         bool hasData = ( edge->_2neibors->_edges[0] );
2895         if ( hasData ) // _LayerEdge is a copy of another one
2896         {
2897           nn[0] = edge->_2neibors->srcNode(0);
2898           nn[1] = edge->_2neibors->srcNode(1);
2899         }
2900         else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], eos, data ))
2901         {
2902           return false;
2903         }
2904         // set neighbor _LayerEdge's
2905         for ( int j = 0; j < 2; ++j )
2906         {
2907           if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2908             return error("_LayerEdge not found by src node", data._index);
2909           edge->_2neibors->_edges[j] = n2e->second;
2910         }
2911         if ( !hasData )
2912           edge->SetDataByNeighbors( nn[0], nn[1], eos, helper );
2913       }
2914
2915       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2916       {
2917         _Simplex& s = edge->_simplices[j];
2918         s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2919         s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2920       }
2921
2922       // For an _LayerEdge on a degenerated EDGE, copy some data from
2923       // a corresponding _LayerEdge on a VERTEX
2924       // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2925       if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2926       {
2927         // Generally we should not get here
2928         if ( eos.ShapeType() != TopAbs_EDGE )
2929           continue;
2930         TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( eos._shape ));
2931         const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2932         if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2933           continue;
2934         const _LayerEdge* vEdge = n2e->second;
2935         edge->_normal    = vEdge->_normal;
2936         edge->_lenFactor = vEdge->_lenFactor;
2937         edge->_cosin     = vEdge->_cosin;
2938       }
2939
2940     } // loop on data._edgesOnShape._edges
2941   } // loop on data._edgesOnShape
2942
2943   // fix _LayerEdge::_2neibors on EDGEs to smooth
2944   // map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2945   // for ( ; e2c != data._edge2curve.end(); ++e2c )
2946   //   if ( !e2c->second.IsNull() )
2947   //   {
2948   //     if ( _EdgesOnShape* eos = data.GetShapeEdges( e2c->first ))
2949   //       data.Sort2NeiborsOnEdge( eos->_edges );
2950   //   }
2951
2952   dumpFunctionEnd();
2953   return true;
2954 }
2955
2956 //================================================================================
2957 /*!
2958  * \brief Compute inflation step size by min size of element on a convex surface
2959  */
2960 //================================================================================
2961
2962 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2963                                      const SMDS_MeshElement* face,
2964                                      const _LayerEdge*       maxCosinEdge )
2965 {
2966   int iN = 0;
2967   double minSize = 10 * data._stepSize;
2968   const int nbNodes = face->NbCornerNodes();
2969   for ( int i = 0; i < nbNodes; ++i )
2970   {
2971     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2972     const SMDS_MeshNode*  curN = face->GetNode( i );
2973     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2974          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2975     {
2976       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2977       if ( dist < minSize )
2978         minSize = dist, iN = i;
2979     }
2980   }
2981   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2982   if ( newStep < data._stepSize )
2983   {
2984     data._stepSize = newStep;
2985     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2986     data._stepSizeNodes[0] = face->GetNode( iN );
2987     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2988   }
2989 }
2990
2991 //================================================================================
2992 /*!
2993  * \brief Compute inflation step size by min size of element on a convex surface
2994  */
2995 //================================================================================
2996
2997 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2998 {
2999   if ( minSize < data._stepSize )
3000   {
3001     data._stepSize = minSize;
3002     if ( data._stepSizeNodes[0] )
3003     {
3004       double dist =
3005         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3006       data._stepSizeCoeff = data._stepSize / dist;
3007     }
3008   }
3009 }
3010
3011 //================================================================================
3012 /*!
3013  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
3014  */
3015 //================================================================================
3016
3017 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
3018 {
3019   SMESH_MesherHelper helper( *_mesh );
3020
3021   BRepLProp_SLProps surfProp( 2, 1e-6 );
3022   data._convexFaces.clear();
3023
3024   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
3025   {
3026     _EdgesOnShape& eof = data._edgesOnShape[iS];
3027     if ( eof.ShapeType() != TopAbs_FACE ||
3028          data._ignoreFaceIds.count( eof._shapeID ))
3029       continue;
3030
3031     TopoDS_Face        F = TopoDS::Face( eof._shape );
3032     const TGeomID faceID = eof._shapeID;
3033
3034     BRepAdaptor_Surface surface( F, false );
3035     surfProp.SetSurface( surface );
3036
3037     _ConvexFace cnvFace;
3038     cnvFace._face = F;
3039     cnvFace._normalsFixed = false;
3040     cnvFace._isTooCurved = false;
3041
3042     double maxCurvature = cnvFace.GetMaxCurvature( data, eof, surfProp, helper );
3043     if ( maxCurvature > 0 )
3044     {
3045       limitStepSize( data, 0.9 / maxCurvature );
3046       findEdgesToUpdateNormalNearConvexFace( cnvFace, data, helper );
3047     }
3048     if ( !cnvFace._isTooCurved ) continue;
3049
3050     _ConvexFace & convFace =
3051       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
3052
3053     // skip a closed surface (data._convexFaces is useful anyway)
3054     bool isClosedF = false;
3055     helper.SetSubShape( F );
3056     if ( helper.HasRealSeam() )
3057     {
3058       // in the closed surface there must be a closed EDGE
3059       for ( TopExp_Explorer eIt( F, TopAbs_EDGE ); eIt.More() && !isClosedF; eIt.Next() )
3060         isClosedF = helper.IsClosedEdge( TopoDS::Edge( eIt.Current() ));
3061     }
3062     if ( isClosedF )
3063     {
3064       // limit _LayerEdge::_maxLen on the FACE
3065       const double oriFactor    = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
3066       const double minCurvature =
3067         1. / ( eof._hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
3068       map< TGeomID, _EdgesOnShape* >::iterator id2eos = cnvFace._subIdToEOS.find( faceID );
3069       if ( id2eos != cnvFace._subIdToEOS.end() )
3070       {
3071         _EdgesOnShape& eos = * id2eos->second;
3072         for ( size_t i = 0; i < eos._edges.size(); ++i )
3073         {
3074           _LayerEdge* ledge = eos._edges[ i ];
3075           gp_XY uv = helper.GetNodeUV( F, ledge->_nodes[0] );
3076           surfProp.SetParameters( uv.X(), uv.Y() );
3077           if ( surfProp.IsCurvatureDefined() )
3078           {
3079             double curvature = Max( surfProp.MaxCurvature() * oriFactor,
3080                                     surfProp.MinCurvature() * oriFactor );
3081             if ( curvature > minCurvature )
3082               ledge->SetMaxLen( Min( ledge->_maxLen, 1. / curvature ));
3083           }
3084         }
3085       }
3086       continue;
3087     }
3088
3089     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
3090     // prism distortion.
3091     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
3092     if ( id2eos != convFace._subIdToEOS.end() && !id2eos->second->_edges.empty() )
3093     {
3094       // there are _LayerEdge's on the FACE it-self;
3095       // select _LayerEdge's near EDGEs
3096       _EdgesOnShape& eos = * id2eos->second;
3097       for ( size_t i = 0; i < eos._edges.size(); ++i )
3098       {
3099         _LayerEdge* ledge = eos._edges[ i ];
3100         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
3101           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
3102           {
3103             // do not select _LayerEdge's neighboring sharp EDGEs
3104             bool sharpNbr = false;
3105             for ( size_t iN = 0; iN < ledge->_neibors.size()  && !sharpNbr; ++iN )
3106               sharpNbr = ( ledge->_neibors[iN]->_cosin > theMinSmoothCosin );
3107             if ( !sharpNbr )
3108               convFace._simplexTestEdges.push_back( ledge );
3109             break;
3110           }
3111       }
3112     }
3113     else
3114     {
3115       // where there are no _LayerEdge's on a _ConvexFace,
3116       // as e.g. on a fillet surface with no internal nodes - issue 22580,
3117       // so that collision of viscous internal faces is not detected by check of
3118       // intersection of _LayerEdge's with the viscous internal faces.
3119
3120       set< const SMDS_MeshNode* > usedNodes;
3121
3122       // look for _LayerEdge's with null _sWOL
3123       id2eos = convFace._subIdToEOS.begin();
3124       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
3125       {
3126         _EdgesOnShape& eos = * id2eos->second;
3127         if ( !eos._sWOL.IsNull() )
3128           continue;
3129         for ( size_t i = 0; i < eos._edges.size(); ++i )
3130         {
3131           _LayerEdge* ledge = eos._edges[ i ];
3132           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
3133           if ( !usedNodes.insert( srcNode ).second ) continue;
3134
3135           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
3136           {
3137             usedNodes.insert( ledge->_simplices[i]._nPrev );
3138             usedNodes.insert( ledge->_simplices[i]._nNext );
3139           }
3140           convFace._simplexTestEdges.push_back( ledge );
3141         }
3142       }
3143     }
3144   } // loop on FACEs of data._solid
3145 }
3146
3147 //================================================================================
3148 /*!
3149  * \brief Detect shapes (and _LayerEdge's on them) to smooth
3150  */
3151 //================================================================================
3152
3153 bool _ViscousBuilder::findShapesToSmooth( _SolidData& data )
3154 {
3155   // define allowed thickness
3156   computeGeomSize( data ); // compute data._geomSize and _LayerEdge::_maxLen
3157
3158
3159   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
3160   // boundary inclined to the shape at a sharp angle
3161
3162   TopTools_MapOfShape edgesOfSmooFaces;
3163   SMESH_MesherHelper helper( *_mesh );
3164   bool ok = true;
3165
3166   vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3167   data._nbShapesToSmooth = 0;
3168
3169   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3170   {
3171     _EdgesOnShape& eos = edgesByGeom[iS];
3172     eos._toSmooth = false;
3173     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
3174       continue;
3175
3176     double tgtThick = eos._hyp.GetTotalThickness();
3177     SMESH_subMeshIteratorPtr subIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false );
3178     while ( subIt->more() && !eos._toSmooth )
3179     {
3180       TGeomID iSub = subIt->next()->GetId();
3181       const vector<_LayerEdge*>& eSub = edgesByGeom[ iSub ]._edges;
3182       if ( eSub.empty() ) continue;
3183
3184       double faceSize;
3185       for ( size_t i = 0; i < eSub.size() && !eos._toSmooth; ++i )
3186         if ( eSub[i]->_cosin > theMinSmoothCosin )
3187         {
3188           SMDS_ElemIteratorPtr fIt = eSub[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3189           while ( fIt->more() && !eos._toSmooth )
3190           {
3191             const SMDS_MeshElement* face = fIt->next();
3192             if ( face->getshapeId() == eos._shapeID &&
3193                  getDistFromEdge( face, eSub[i]->_nodes[0], faceSize ))
3194             {
3195               eos._toSmooth = needSmoothing( eSub[i]->_cosin,
3196                                              tgtThick * eSub[i]->_lenFactor,
3197                                              faceSize);
3198             }
3199           }
3200         }
3201     }
3202     if ( eos._toSmooth )
3203     {
3204       for ( TopExp_Explorer eExp( edgesByGeom[iS]._shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
3205         edgesOfSmooFaces.Add( eExp.Current() );
3206
3207       data.PrepareEdgesToSmoothOnFace( &edgesByGeom[iS], /*substituteSrcNodes=*/false );
3208     }
3209     data._nbShapesToSmooth += eos._toSmooth;
3210
3211   }  // check FACEs
3212
3213   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check EDGEs
3214   {
3215     _EdgesOnShape& eos = edgesByGeom[iS];
3216     eos._edgeSmoother = NULL;
3217     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_EDGE ) continue;
3218     if ( !eos._hyp.ToSmooth() ) continue;
3219
3220     const TopoDS_Edge& E = TopoDS::Edge( edgesByGeom[iS]._shape );
3221     if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
3222       continue;
3223
3224     double tgtThick = eos._hyp.GetTotalThickness(), h0 = eos._hyp.Get1stLayerThickness();
3225     for ( TopoDS_Iterator vIt( E ); vIt.More() && !eos._toSmooth; vIt.Next() )
3226     {
3227       TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
3228       vector<_LayerEdge*>& eV = edgesByGeom[ iV ]._edges;
3229       if ( eV.empty() || eV[0]->Is( _LayerEdge::MULTI_NORMAL )) continue;
3230       gp_Vec  eDir    = getEdgeDir( E, TopoDS::Vertex( vIt.Value() ), h0 );
3231       double angle    = eDir.Angle( eV[0]->_normal );
3232       double cosin    = Cos( angle );
3233       double cosinAbs = Abs( cosin );
3234       if ( cosinAbs > theMinSmoothCosin )
3235       {
3236         // always smooth analytic EDGEs
3237         Handle(Geom_Curve) curve = _Smoother1D::CurveForSmooth( E, eos, helper );
3238         eos._toSmooth = ! curve.IsNull();
3239
3240         // compare tgtThick with the length of an end segment
3241         SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
3242         while ( eIt->more() && !eos._toSmooth )
3243         {
3244           const SMDS_MeshElement* endSeg = eIt->next();
3245           if ( endSeg->getshapeId() == (int) iS )
3246           {
3247             double segLen =
3248               SMESH_TNodeXYZ( endSeg->GetNode( 0 )).Distance( endSeg->GetNode( 1 ));
3249             eos._toSmooth = needSmoothing( cosinAbs, tgtThick * eV[0]->_lenFactor, segLen );
3250           }
3251         }
3252         if ( eos._toSmooth )
3253         {
3254           eos._edgeSmoother = new _Smoother1D( curve, eos );
3255
3256           // for ( size_t i = 0; i < eos._edges.size(); ++i )
3257           //   eos._edges[i]->Set( _LayerEdge::TO_SMOOTH );
3258         }
3259       }
3260     }
3261     data._nbShapesToSmooth += eos._toSmooth;
3262
3263   } // check EDGEs
3264
3265   // Reset _cosin if no smooth is allowed by the user
3266   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
3267   {
3268     _EdgesOnShape& eos = edgesByGeom[iS];
3269     if ( eos._edges.empty() ) continue;
3270
3271     if ( !eos._hyp.ToSmooth() )
3272       for ( size_t i = 0; i < eos._edges.size(); ++i )
3273         //eos._edges[i]->SetCosin( 0 ); // keep _cosin to use in limitMaxLenByCurvature()
3274         eos._edges[i]->_lenFactor = 1;
3275   }
3276
3277
3278   // Fill _eosC1 to make that C1 FACEs and EDGEs between them to be smoothed as a whole
3279
3280   TopTools_MapOfShape c1VV;
3281
3282   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check FACEs
3283   {
3284     _EdgesOnShape& eos = edgesByGeom[iS];
3285     if ( eos._edges.empty() ||
3286          eos.ShapeType() != TopAbs_FACE ||
3287          !eos._toSmooth )
3288       continue;
3289
3290     // check EDGEs of a FACE
3291     TopTools_MapOfShape checkedEE, allVV;
3292     list< SMESH_subMesh* > smQueue( 1, eos._subMesh ); // sm of FACEs
3293     while ( !smQueue.empty() )
3294     {
3295       SMESH_subMesh* sm = smQueue.front();
3296       smQueue.pop_front();
3297       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3298       while ( smIt->more() )
3299       {
3300         sm = smIt->next();
3301         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
3302           allVV.Add( sm->GetSubShape() );
3303         if ( sm->GetSubShape().ShapeType() != TopAbs_EDGE ||
3304              !checkedEE.Add( sm->GetSubShape() ))
3305           continue;
3306
3307         _EdgesOnShape*      eoe = data.GetShapeEdges( sm->GetId() );
3308         vector<_LayerEdge*>& eE = eoe->_edges;
3309         if ( eE.empty() || !eoe->_sWOL.IsNull() )
3310           continue;
3311
3312         bool isC1 = true; // check continuity along an EDGE
3313         for ( size_t i = 0; i < eE.size() && isC1; ++i )
3314           isC1 = ( Abs( eE[i]->_cosin ) < theMinSmoothCosin );
3315         if ( !isC1 )
3316           continue;
3317
3318         // check that mesh faces are C1 as well
3319         {
3320           gp_XYZ norm1, norm2;
3321           const SMDS_MeshNode*   n = eE[ eE.size() / 2 ]->_nodes[0];
3322           SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator(SMDSAbs_Face);
3323           if ( !SMESH_MeshAlgos::FaceNormal( fIt->next(), norm1, /*normalized=*/true ))
3324             continue;
3325           while ( fIt->more() && isC1 )
3326             isC1 = ( SMESH_MeshAlgos::FaceNormal( fIt->next(), norm2, /*normalized=*/true ) &&
3327                      Abs( norm1 * norm2 ) >= ( 1. - theMinSmoothCosin ));
3328           if ( !isC1 )
3329             continue;
3330         }
3331
3332         // add the EDGE and an adjacent FACE to _eosC1
3333         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
3334         while ( const TopoDS_Shape* face = fIt->next() )
3335         {
3336           _EdgesOnShape* eof = data.GetShapeEdges( *face );
3337           if ( !eof ) continue; // other solid
3338           if ( eos._shapeID == eof->_shapeID ) continue;
3339           if ( !eos.HasC1( eof ))
3340           {
3341             // check the FACEs
3342             eos._eosC1.push_back( eof );
3343             eof->_toSmooth = false;
3344             data.PrepareEdgesToSmoothOnFace( eof, /*substituteSrcNodes=*/false );
3345             smQueue.push_back( eof->_subMesh );
3346           }
3347           if ( !eos.HasC1( eoe ))
3348           {
3349             eos._eosC1.push_back( eoe );
3350             eoe->_toSmooth = false;
3351             data.PrepareEdgesToSmoothOnFace( eoe, /*substituteSrcNodes=*/false );
3352           }
3353         }
3354       }
3355     }
3356     if ( eos._eosC1.empty() )
3357       continue;
3358
3359     // check VERTEXes of C1 FACEs
3360     TopTools_MapIteratorOfMapOfShape vIt( allVV );
3361     for ( ; vIt.More(); vIt.Next() )
3362     {
3363       _EdgesOnShape* eov = data.GetShapeEdges( vIt.Key() );
3364       if ( !eov || eov->_edges.empty() || !eov->_sWOL.IsNull() )
3365         continue;
3366
3367       bool isC1 = true; // check if all adjacent FACEs are in eos._eosC1
3368       PShapeIteratorPtr fIt = helper.GetAncestors( vIt.Key(), *_mesh, TopAbs_FACE );
3369       while ( const TopoDS_Shape* face = fIt->next() )
3370       {
3371         _EdgesOnShape* eof = data.GetShapeEdges( *face );
3372         if ( !eof ) continue; // other solid
3373         isC1 = ( face->IsSame( eos._shape ) || eos.HasC1( eof ));
3374         if ( !isC1 )
3375           break;
3376       }
3377       if ( isC1 )
3378       {
3379         eos._eosC1.push_back( eov );
3380         data.PrepareEdgesToSmoothOnFace( eov, /*substituteSrcNodes=*/false );
3381         c1VV.Add( eov->_shape );
3382       }
3383     }
3384
3385   } // fill _eosC1 of FACEs
3386
3387
3388   // Find C1 EDGEs
3389
3390   vector< pair< _EdgesOnShape*, gp_XYZ > > dirOfEdges;
3391
3392   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS ) // check VERTEXes
3393   {
3394     _EdgesOnShape& eov = edgesByGeom[iS];
3395     if ( eov._edges.empty() ||
3396          eov.ShapeType() != TopAbs_VERTEX ||
3397          c1VV.Contains( eov._shape ))
3398       continue;
3399     const TopoDS_Vertex& V = TopoDS::Vertex( eov._shape );
3400
3401     // get directions of surrounding EDGEs
3402     dirOfEdges.clear();
3403     PShapeIteratorPtr fIt = helper.GetAncestors( eov._shape, *_mesh, TopAbs_EDGE );
3404     while ( const TopoDS_Shape* e = fIt->next() )
3405     {
3406       _EdgesOnShape* eoe = data.GetShapeEdges( *e );
3407       if ( !eoe ) continue; // other solid
3408       gp_XYZ eDir = getEdgeDir( TopoDS::Edge( *e ), V, eoe->_hyp.Get1stLayerThickness() );
3409       if ( !Precision::IsInfinite( eDir.X() ))
3410         dirOfEdges.push_back( make_pair( eoe, eDir.Normalized() ));
3411     }
3412
3413     // find EDGEs with C1 directions
3414     for ( size_t i = 0; i < dirOfEdges.size(); ++i )
3415       for ( size_t j = i+1; j < dirOfEdges.size(); ++j )
3416         if ( dirOfEdges[i].first && dirOfEdges[j].first )
3417         {
3418           double dot = dirOfEdges[i].second * dirOfEdges[j].second;
3419           bool isC1 = ( dot < - ( 1. - theMinSmoothCosin ));
3420           if ( isC1 )
3421           {
3422             double maxEdgeLen = 3 * Min( eov._edges[0]->_maxLen, eov._hyp.GetTotalThickness() );
3423             for ( int isJ = 0; isJ < 2; ++isJ ) // loop on [i,j]
3424             {
3425               size_t k = isJ ? j : i;
3426               const TopoDS_Edge& e = TopoDS::Edge( dirOfEdges[k].first->_shape );
3427               double eLen = SMESH_Algo::EdgeLength( e );
3428               if ( eLen < maxEdgeLen )
3429               {
3430                 TopoDS_Shape oppV = SMESH_MesherHelper::IthVertex( 0, e );
3431                 if ( oppV.IsSame( V ))
3432                   oppV = SMESH_MesherHelper::IthVertex( 1, e );
3433                 _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
3434                 if ( dirOfEdges[k].second * eovOpp->_edges[0]->_normal < 0 )
3435                   eov._eosC1.push_back( dirOfEdges[k].first );
3436               }
3437               dirOfEdges[k].first = 0;
3438             }
3439           }
3440         }
3441   } // fill _eosC1 of VERTEXes
3442
3443
3444
3445   return ok;
3446 }
3447
3448 //================================================================================
3449 /*!
3450  * \brief Set up _SolidData::_edgesOnShape
3451  */
3452 //================================================================================
3453
3454 int _ViscousBuilder::makeEdgesOnShape()
3455 {
3456   const int nbShapes = getMeshDS()->MaxShapeIndex();
3457   int nbSolidsWL = 0;
3458
3459   for ( size_t i = 0; i < _sdVec.size(); ++i )
3460   {
3461     _SolidData& data = _sdVec[ i ];
3462     vector< _EdgesOnShape >& edgesByGeom = data._edgesOnShape;
3463     edgesByGeom.resize( nbShapes+1 );
3464
3465     // set data of _EdgesOnShape's
3466     int nbShapesWL = 0;
3467     if ( SMESH_subMesh* sm = _mesh->GetSubMesh( data._solid ))
3468     {
3469       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/false);
3470       while ( smIt->more() )
3471       {
3472         sm = smIt->next();
3473         if ( sm->GetSubShape().ShapeType() == TopAbs_FACE &&
3474              data._ignoreFaceIds.count( sm->GetId() ))
3475           continue;
3476
3477         setShapeData( edgesByGeom[ sm->GetId() ], sm, data );
3478
3479         nbShapesWL += ( sm->GetSubShape().ShapeType() == TopAbs_FACE );
3480       }
3481     }
3482     if ( nbShapesWL == 0 ) // no shapes with layers in a SOLID
3483     {
3484       data._done = true;
3485       SMESHUtils::FreeVector( edgesByGeom );
3486     }
3487     else
3488     {
3489       ++nbSolidsWL;
3490     }
3491   }
3492   return nbSolidsWL;
3493 }
3494
3495 //================================================================================
3496 /*!
3497  * \brief initialize data of _EdgesOnShape
3498  */
3499 //================================================================================
3500
3501 void _ViscousBuilder::setShapeData( _EdgesOnShape& eos,
3502                                     SMESH_subMesh* sm,
3503                                     _SolidData&    data )
3504 {
3505   if ( !eos._shape.IsNull() ||
3506        sm->GetSubShape().ShapeType() == TopAbs_WIRE )
3507     return;
3508
3509   SMESH_MesherHelper helper( *_mesh );
3510
3511   eos._subMesh = sm;
3512   eos._shapeID = sm->GetId();
3513   eos._shape   = sm->GetSubShape();
3514   if ( eos.ShapeType() == TopAbs_FACE )
3515     eos._shape.Orientation( helper.GetSubShapeOri( data._solid, eos._shape ));
3516   eos._toSmooth = false;
3517   eos._data = &data;
3518   eos._mapper2D = nullptr;
3519
3520   // set _SWOL
3521   map< TGeomID, TopoDS_Shape >::const_iterator s2s =
3522     data._shrinkShape2Shape.find( eos._shapeID );
3523   if ( s2s != data._shrinkShape2Shape.end() )
3524     eos._sWOL = s2s->second;
3525
3526   eos._isRegularSWOL = true;
3527   if ( eos.SWOLType() == TopAbs_FACE )
3528   {
3529     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
3530     Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( F );
3531     eos._isRegularSWOL = ( ! surface->HasSingularities( 1e-7 ));
3532   }
3533
3534   // set _hyp
3535   if ( data._hyps.size() == 1 )
3536   {
3537     eos._hyp = data._hyps.back();
3538   }
3539   else
3540   {
3541     // compute average StdMeshers_ViscousLayers parameters
3542     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
3543     if ( eos.ShapeType() == TopAbs_FACE )
3544     {
3545       if (( f2hyp = data._face2hyp.find( eos._shapeID )) != data._face2hyp.end() )
3546         eos._hyp = f2hyp->second;
3547     }
3548     else
3549     {
3550       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3551       while ( const TopoDS_Shape* face = fIt->next() )
3552       {
3553         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3554         if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
3555           eos._hyp.Add( f2hyp->second );
3556       }
3557     }
3558   }
3559
3560   // set _faceNormals
3561   if ( ! eos._hyp.UseSurfaceNormal() )
3562   {
3563     if ( eos.ShapeType() == TopAbs_FACE ) // get normals to elements on a FACE
3564     {
3565       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3566       if ( !smDS ) return;
3567       eos._faceNormals.reserve( smDS->NbElements() );
3568
3569       double oriFactor = helper.IsReversedSubMesh( TopoDS::Face( eos._shape )) ? 1.: -1.;
3570       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
3571       for ( ; eIt->more(); )
3572       {
3573         const SMDS_MeshElement* face = eIt->next();
3574         gp_XYZ&                 norm = eos._faceNormals[face];
3575         if ( !SMESH_MeshAlgos::FaceNormal( face, norm, /*normalized=*/true ))
3576           norm.SetCoord( 0,0,0 );
3577         norm *= oriFactor;
3578       }
3579     }
3580     else // find EOS of adjacent FACEs
3581     {
3582       PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
3583       while ( const TopoDS_Shape* face = fIt->next() )
3584       {
3585         TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
3586         eos._faceEOS.push_back( & data._edgesOnShape[ faceID ]);
3587         if ( eos._faceEOS.back()->_shape.IsNull() )
3588           // avoid using uninitialised _shapeID in GetNormal()
3589           eos._faceEOS.back()->_shapeID = faceID;
3590       }
3591     }
3592   }
3593 }
3594
3595 //================================================================================
3596 /*!
3597  * \brief Returns normal of a face
3598  */
3599 //================================================================================
3600
3601 bool _EdgesOnShape::GetNormal( const SMDS_MeshElement* face, gp_Vec& norm )
3602 {
3603   bool ok = false;
3604   _EdgesOnShape* eos = 0;
3605
3606   if ( face->getshapeId() == _shapeID )
3607   {
3608     eos = this;
3609   }
3610   else
3611   {
3612     for ( size_t iF = 0; iF < _faceEOS.size() && !eos; ++iF )
3613       if ( face->getshapeId() == _faceEOS[ iF ]->_shapeID )
3614         eos = _faceEOS[ iF ];
3615   }
3616
3617   if (( eos ) &&
3618       ( ok = ( eos->_faceNormals.count( face ) )))
3619   {
3620     norm = eos->_faceNormals[ face ];
3621   }
3622   else if ( !eos )
3623   {
3624     debugMsg( "_EdgesOnShape::Normal() failed for face "<<face->GetID()
3625               << " on _shape #" << _shapeID );
3626   }
3627   return ok;
3628 }
3629
3630 //================================================================================
3631 /*!
3632  * \brief EdgesOnShape destructor
3633  */
3634 //================================================================================
3635
3636 _EdgesOnShape::~_EdgesOnShape()
3637 {
3638   delete _edgeSmoother;
3639   delete _mapper2D;
3640 }
3641
3642 //================================================================================
3643 /*!
3644  * \brief Set data of _LayerEdge needed for smoothing
3645  */
3646 //================================================================================
3647
3648 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
3649                                   _EdgesOnShape&      eos,
3650                                   SMESH_MesherHelper& helper,
3651                                   _SolidData&         data)
3652 {
3653   const SMDS_MeshNode* node = edge._nodes[0]; // source node
3654
3655   edge._len          = 0;
3656   edge._maxLen       = Precision::Infinite();
3657   edge._minAngle     = 0;
3658   edge._2neibors     = 0;
3659   edge._curvature    = 0;
3660   edge._flags        = 0;
3661   edge._smooFunction = 0;
3662
3663   // --------------------------
3664   // Compute _normal and _cosin
3665   // --------------------------
3666
3667   edge._cosin     = 0;
3668   edge._lenFactor = 1.;
3669   edge._normal.SetCoord(0,0,0);
3670   _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
3671
3672   int totalNbFaces = 0;
3673   TopoDS_Face F;
3674   std::pair< TopoDS_Face, gp_XYZ > face2Norm[20];
3675   gp_Vec geomNorm;
3676   bool normOK = true;
3677
3678   const bool onShrinkShape = !eos._sWOL.IsNull();
3679   const bool useGeometry   = (( eos._hyp.UseSurfaceNormal() ) ||
3680                               ( eos.ShapeType() != TopAbs_FACE /*&& !onShrinkShape*/ ));
3681
3682   // get geom FACEs the node lies on
3683   //if ( useGeometry )
3684   {
3685     set<TGeomID> faceIds;
3686     if  ( eos.ShapeType() == TopAbs_FACE )
3687     {
3688       faceIds.insert( eos._shapeID );
3689     }
3690     else
3691     {
3692       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3693       while ( fIt->more() )
3694         faceIds.insert( fIt->next()->getshapeId() );
3695     }
3696     set<TGeomID>::iterator id = faceIds.begin();
3697     for ( ; id != faceIds.end(); ++id )
3698     {
3699       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
3700       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || data._ignoreFaceIds.count( *id ))
3701         continue;
3702       F = TopoDS::Face( s );
3703       face2Norm[ totalNbFaces ].first = F;
3704       totalNbFaces++;
3705     }
3706   }
3707
3708   // find _normal
3709   bool fromVonF = false;
3710   if ( useGeometry )
3711   {
3712     fromVonF = ( eos.ShapeType() == TopAbs_VERTEX &&
3713                  eos.SWOLType()  == TopAbs_FACE  &&
3714                  totalNbFaces > 1 );
3715
3716     if ( onShrinkShape && !fromVonF ) // one of faces the node is on has no layers
3717     {
3718       if ( eos.SWOLType() == TopAbs_EDGE )
3719       {
3720         // inflate from VERTEX along EDGE
3721         edge._normal = getEdgeDir( TopoDS::Edge( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3722                                    eos._hyp.Get1stLayerThickness(), &eos._isRegularSWOL );
3723       }
3724       else if ( eos.ShapeType() == TopAbs_VERTEX )
3725       {
3726         // inflate from VERTEX along FACE
3727         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Vertex( eos._shape ),
3728                                    node, helper, normOK/*, &edge._cosin*/);
3729       }
3730       else
3731       {
3732         // inflate from EDGE along FACE
3733         edge._normal = getFaceDir( TopoDS::Face( eos._sWOL ), TopoDS::Edge( eos._shape ),
3734                                    node, helper, normOK);
3735       }
3736     }
3737     else // layers are on all FACEs of SOLID the node is on (or fromVonF)
3738     {
3739       if ( fromVonF )
3740         face2Norm[ totalNbFaces++ ].first = TopoDS::Face( eos._sWOL );
3741
3742       int nbOkNorms = 0;
3743       for ( int iF = totalNbFaces - 1; iF >= 0; --iF )
3744       {
3745         F = face2Norm[ iF ].first;
3746         geomNorm = getFaceNormal( node, F, helper, normOK );
3747         if ( !normOK ) continue;
3748         nbOkNorms++;
3749
3750         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3751           geomNorm.Reverse();
3752         face2Norm[ iF ].second = geomNorm.XYZ();
3753         edge._normal += geomNorm.XYZ();
3754       }
3755       if ( nbOkNorms == 0 )
3756         return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
3757
3758       if ( totalNbFaces >= 3 )
3759       {
3760         edge._normal = getNormalByOffset( &edge, face2Norm, totalNbFaces, fromVonF );
3761       }
3762
3763       if ( edge._normal.Modulus() < 1e-3 && nbOkNorms > 1 )
3764       {
3765         // opposite normals, re-get normals at shifted positions (IPAL 52426)
3766         edge._normal.SetCoord( 0,0,0 );
3767         for ( int iF = 0; iF < totalNbFaces - fromVonF; ++iF )
3768         {
3769           const TopoDS_Face& F = face2Norm[iF].first;
3770           geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
3771           if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3772             geomNorm.Reverse();
3773           if ( normOK )
3774             face2Norm[ iF ].second = geomNorm.XYZ();
3775           edge._normal += face2Norm[ iF ].second;
3776         }
3777       }
3778     }
3779   }
3780   else // !useGeometry - get _normal using surrounding mesh faces
3781   {
3782     edge._normal = getWeigthedNormal( &edge );
3783
3784     // set<TGeomID> faceIds;
3785     //
3786     // SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3787     // while ( fIt->more() )
3788     // {
3789     //   const SMDS_MeshElement* face = fIt->next();
3790     //   if ( eos.GetNormal( face, geomNorm ))
3791     //   {
3792     //     if ( onShrinkShape && !faceIds.insert( face->getshapeId() ).second )
3793     //       continue; // use only one mesh face on FACE
3794     //     edge._normal += geomNorm.XYZ();
3795     //     totalNbFaces++;
3796     //   }
3797     // }
3798   }
3799
3800   // compute _cosin
3801   //if ( eos._hyp.UseSurfaceNormal() )
3802   {
3803     switch ( eos.ShapeType() )
3804     {
3805     case TopAbs_FACE: {
3806       edge._cosin = 0;
3807       break;
3808     }
3809     case TopAbs_EDGE: {
3810       TopoDS_Edge E    = TopoDS::Edge( eos._shape );
3811       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
3812       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3813       edge._cosin      = Cos( angle );
3814       break;
3815     }
3816     case TopAbs_VERTEX: {
3817       TopoDS_Vertex V  = TopoDS::Vertex( eos._shape );
3818       gp_Vec inFaceDir = getFaceDir( face2Norm[0].first , V, node, helper, normOK );
3819       double angle     = inFaceDir.Angle( edge._normal ); // [0,PI]
3820       edge._cosin      = Cos( angle );
3821       if ( fromVonF )
3822         totalNbFaces--;
3823       if ( totalNbFaces > 1 || helper.IsSeamShape( node->getshapeId() ))
3824         for ( int iF = 1; iF < totalNbFaces; ++iF )
3825         {
3826           F = face2Norm[ iF ].first;
3827           inFaceDir = getFaceDir( F, V, node, helper, normOK=true );
3828           if ( normOK ) {
3829             if ( onShrinkShape )
3830             {
3831               gp_Vec faceNorm = getFaceNormal( node, F, helper, normOK );
3832               if ( !normOK ) continue;
3833               if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3834                 faceNorm.Reverse();
3835               angle = 0.5 * M_PI - faceNorm.Angle( edge._normal );
3836               if ( inFaceDir * edge._normal < 0 )
3837                 angle = M_PI - angle;
3838             }
3839             else
3840             {
3841               angle = inFaceDir.Angle( edge._normal );
3842             }
3843             double cosin = Cos( angle );
3844             if ( Abs( cosin ) > Abs( edge._cosin ))
3845               edge._cosin = cosin;
3846           }
3847         }
3848       break;
3849     }
3850     default:
3851       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
3852     }
3853   }
3854
3855   double normSize = edge._normal.SquareModulus();
3856   if ( normSize < numeric_limits<double>::min() )
3857     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
3858
3859   edge._normal /= sqrt( normSize );
3860
3861   if ( edge.Is( _LayerEdge::MULTI_NORMAL ) && edge._nodes.size() == 2 )
3862   {
3863     getMeshDS()->RemoveFreeNode( edge._nodes.back(), 0, /*fromGroups=*/false );
3864     edge._nodes.resize( 1 );
3865     edge._normal.SetCoord( 0,0,0 );
3866     edge.SetMaxLen( 0 );
3867   }
3868
3869   // Set the rest data
3870   // --------------------
3871
3872   double realLenFactor = edge.SetCosin( edge._cosin ); // to update edge._lenFactor
3873   // if ( realLenFactor > 3 )
3874   // {
3875   //   edge._cosin = 1;
3876   //   if ( onShrinkShape )
3877   //   {
3878   //     edge.Set( _LayerEdge::RISKY_SWOL );
3879   //     edge._lenFactor = 2;
3880   //   }
3881   //   else
3882   //   {
3883   //     edge._lenFactor = 1;
3884   //   }
3885   // }
3886
3887   if ( onShrinkShape )
3888   {
3889     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3890     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
3891       sm->RemoveNode( tgtNode );
3892
3893     // set initial position which is parameters on _sWOL in this case
3894     if ( eos.SWOLType() == TopAbs_EDGE )
3895     {
3896       double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), node, 0, &normOK );
3897       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
3898       if ( edge._nodes.size() > 1 )
3899         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( eos._sWOL ), u );
3900     }
3901     else // eos.SWOLType() == TopAbs_FACE
3902     {
3903       gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), node, 0, &normOK );
3904       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3905       if ( edge._nodes.size() > 1 )
3906         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( eos._sWOL ), uv.X(), uv.Y() );
3907     }
3908
3909     //if ( edge._nodes.size() > 1 ) -- allow RISKY_SWOL on noShrink shape
3910     {
3911       // check if an angle between a FACE with layers and SWOL is sharp,
3912       // else the edge should not inflate
3913       F.Nullify();
3914       for ( int iF = 0; iF < totalNbFaces  &&  F.IsNull();  ++iF ) // find a FACE with VL
3915         if ( ! helper.IsSubShape( eos._sWOL, face2Norm[iF].first ))
3916           F = face2Norm[iF].first;
3917       if ( !F.IsNull())
3918       {
3919         geomNorm = getFaceNormal( node, F, helper, normOK );
3920         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
3921           geomNorm.Reverse(); // inside the SOLID
3922         if ( geomNorm * edge._normal < -0.001 )
3923         {
3924           if ( edge._nodes.size() > 1 )
3925           {
3926             getMeshDS()->RemoveFreeNode( tgtNode, 0, /*fromGroups=*/false );
3927             edge._nodes.resize( 1 );
3928           }
3929         }
3930         else if ( realLenFactor > 3 ) ///  -- moved to SetCosin()
3931           //else if ( edge._lenFactor > 3 )
3932         {
3933           edge._lenFactor = 2;
3934           edge.Set( _LayerEdge::RISKY_SWOL );
3935         }
3936       }
3937     }
3938   }
3939   else
3940   {
3941     edge._pos.push_back( SMESH_TNodeXYZ( node ));
3942
3943     if ( eos.ShapeType() == TopAbs_FACE )
3944     {
3945       double angle;
3946       for ( size_t i = 0; i < edge._simplices.size(); ++i )
3947       {
3948         edge._simplices[i].IsMinAngleOK( edge._pos.back(), angle );
3949         edge._minAngle = Max( edge._minAngle, angle ); // "angle" is actually cosine
3950       }
3951     }
3952   }
3953
3954   // Set neighbor nodes for a _LayerEdge based on EDGE
3955
3956   if ( eos.ShapeType() == TopAbs_EDGE /*||
3957        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
3958   {
3959     edge._2neibors = _Factory::NewNearEdges();
3960     // target nodes instead of source ones will be set later
3961   }
3962
3963   return true;
3964 }
3965
3966 //================================================================================
3967 /*!
3968  * \brief Return normal to a FACE at a node
3969  *  \param [in] n - node
3970  *  \param [in] face - FACE
3971  *  \param [in] helper - helper
3972  *  \param [out] isOK - true or false
3973  *  \param [in] shiftInside - to find normal at a position shifted inside the face
3974  *  \return gp_XYZ - normal
3975  */
3976 //================================================================================
3977
3978 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
3979                                       const TopoDS_Face&   face,
3980                                       SMESH_MesherHelper&  helper,
3981                                       bool&                isOK,
3982                                       bool                 shiftInside)
3983 {
3984   gp_XY uv;
3985   if ( shiftInside )
3986   {
3987     // get a shifted position
3988     gp_Pnt p = SMESH_TNodeXYZ( node );
3989     gp_XYZ shift( 0,0,0 );
3990     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
3991     switch ( S.ShapeType() ) {
3992     case TopAbs_VERTEX:
3993     {
3994       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
3995       break;
3996     }
3997     case TopAbs_EDGE:
3998     {
3999       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
4000       break;
4001     }
4002     default:
4003       isOK = false;
4004     }
4005     if ( isOK )
4006       shift.Normalize();
4007     p.Translate( shift * 1e-5 );
4008
4009     TopLoc_Location loc;
4010     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
4011
4012     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
4013     
4014     projector.Perform( p );
4015     if ( !projector.IsDone() || projector.NbPoints() < 1 )
4016     {
4017       isOK = false;
4018       return p.XYZ();
4019     }
4020     Standard_Real U,V;
4021     projector.LowerDistanceParameters(U,V);
4022     uv.SetCoord( U,V );
4023   }
4024   else
4025   {
4026     uv = helper.GetNodeUV( face, node, 0, &isOK );
4027   }
4028
4029   gp_Dir normal;
4030   isOK = false;
4031
4032   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4033
4034   if ( !shiftInside &&
4035        helper.IsDegenShape( node->getshapeId() ) &&
4036        getFaceNormalAtSingularity( uv, face, helper, normal ))
4037   {
4038     isOK = true;
4039     return normal.XYZ();
4040   }
4041
4042   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
4043   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4044
4045   if ( pointKind == IMPOSSIBLE &&
4046        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
4047   {
4048     // probably NormEstim() failed due to a too high tolerance
4049     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
4050     isOK = ( pointKind < IMPOSSIBLE );
4051   }
4052   if ( pointKind < IMPOSSIBLE )
4053   {
4054     if ( pointKind != REGULAR &&
4055          !shiftInside &&
4056          node->GetPosition()->GetDim() < 2 ) // FACE boundary
4057     {
4058       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
4059       if ( normShift * normal.XYZ() < 0. )
4060         normal = normShift;
4061     }
4062     isOK = true;
4063   }
4064
4065   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
4066   {
4067     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
4068
4069     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4070     while ( fIt->more() )
4071     {
4072       const SMDS_MeshElement* f = fIt->next();
4073       if ( f->getshapeId() == faceID )
4074       {
4075         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
4076         if ( isOK )
4077         {
4078           TopoDS_Face ff = face;
4079           ff.Orientation( TopAbs_FORWARD );
4080           if ( helper.IsReversedSubMesh( ff ))
4081             normal.Reverse();
4082           break;
4083         }
4084       }
4085     }
4086   }
4087   return normal.XYZ();
4088 }
4089
4090 //================================================================================
4091 /*!
4092  * \brief Try to get normal at a singularity of a surface basing on it's nature
4093  */
4094 //================================================================================
4095
4096 bool _ViscousBuilder::getFaceNormalAtSingularity( const gp_XY&        uv,
4097                                                   const TopoDS_Face&  face,
4098                                                   SMESH_MesherHelper& /*helper*/,
4099                                                   gp_Dir&             normal )
4100 {
4101   BRepAdaptor_Surface surface( face );
4102   gp_Dir axis;
4103   if ( !getRovolutionAxis( surface, axis ))
4104     return false;
4105
4106   double f,l, d, du, dv;
4107   f = surface.FirstUParameter();
4108   l = surface.LastUParameter();
4109   d = ( uv.X() - f ) / ( l - f );
4110   du = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4111   f = surface.FirstVParameter();
4112   l = surface.LastVParameter();
4113   d = ( uv.Y() - f ) / ( l - f );
4114   dv = ( d < 0.5 ? +1. : -1 ) * 1e-5 * ( l - f );
4115
4116   gp_Dir refDir;
4117   gp_Pnt2d testUV = uv;
4118   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
4119   double tol = 1e-5;
4120   Handle(Geom_Surface) geomsurf = surface.Surface().Surface();
4121   for ( int iLoop = 0; true ; ++iLoop )
4122   {
4123     testUV.SetCoord( testUV.X() + du, testUV.Y() + dv );
4124     if ( GeomLib::NormEstim( geomsurf, testUV, tol, refDir ) == REGULAR )
4125       break;
4126     if ( iLoop > 20 )
4127       return false;
4128     tol /= 10.;
4129   }
4130
4131   if ( axis * refDir < 0. )
4132     axis.Reverse();
4133
4134   normal = axis;
4135
4136   return true;
4137 }
4138
4139 //================================================================================
4140 /*!
4141  * \brief Return a normal at a node weighted with angles taken by faces
4142  */
4143 //================================================================================
4144
4145 gp_XYZ _ViscousBuilder::getWeigthedNormal( const _LayerEdge* edge )
4146 {
4147   const SMDS_MeshNode* n = edge->_nodes[0];
4148
4149   gp_XYZ resNorm(0,0,0);
4150   SMESH_TNodeXYZ p0( n ), pP, pN;
4151   for ( size_t i = 0; i < edge->_simplices.size(); ++i )
4152   {
4153     pP.Set( edge->_simplices[i]._nPrev );
4154     pN.Set( edge->_simplices[i]._nNext );
4155     gp_Vec v0P( p0, pP ), v0N( p0, pN ), vPN( pP, pN ), norm = v0P ^ v0N;
4156     double l0P = v0P.SquareMagnitude();
4157     double l0N = v0N.SquareMagnitude();
4158     double lPN = vPN.SquareMagnitude();
4159     if ( l0P < std::numeric_limits<double>::min() ||
4160          l0N < std::numeric_limits<double>::min() ||
4161          lPN < std::numeric_limits<double>::min() )
4162       continue;
4163     double lNorm = norm.SquareMagnitude();
4164     double  sin2 = lNorm / l0P / l0N;
4165     double angle = ACos(( v0P * v0N ) / Sqrt( l0P ) / Sqrt( l0N ));
4166
4167     double weight = sin2 * angle / lPN;
4168     resNorm += weight * norm.XYZ() / Sqrt( lNorm );
4169   }
4170
4171   return resNorm;
4172 }
4173
4174 //================================================================================
4175 /*!
4176  * \brief Return a normal at a node by getting a common point of offset planes
4177  *        defined by the FACE normals
4178  */
4179 //================================================================================
4180
4181 gp_XYZ _ViscousBuilder::getNormalByOffset( _LayerEdge*                      edge,
4182                                            std::pair< TopoDS_Face, gp_XYZ > f2Normal[],
4183                                            int                              nbFaces,
4184                                            bool                             lastNoOffset)
4185 {
4186   SMESH_TNodeXYZ p0 = edge->_nodes[0];
4187
4188   gp_XYZ resNorm(0,0,0);
4189   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( p0._node, getMeshDS() );
4190   if ( V.ShapeType() != TopAbs_VERTEX || nbFaces < 3 )
4191   {
4192     for ( int i = 0; i < nbFaces; ++i )
4193       resNorm += f2Normal[i].second;
4194     return resNorm;
4195   }
4196
4197   // prepare _OffsetPlane's
4198   vector< _OffsetPlane > pln( nbFaces );
4199   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4200   {
4201     pln[i]._faceIndex = i;
4202     pln[i]._plane = gp_Pln( p0 + f2Normal[i].second, f2Normal[i].second );
4203   }
4204   if ( lastNoOffset )
4205   {
4206     pln[ nbFaces - 1 ]._faceIndex = nbFaces - 1;
4207     pln[ nbFaces - 1 ]._plane = gp_Pln( p0, f2Normal[ nbFaces - 1 ].second );
4208   }
4209
4210   // intersect neighboring OffsetPlane's
4211   PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
4212   while ( const TopoDS_Shape* edge = edgeIt->next() )
4213   {
4214     int f1 = -1, f2 = -1;
4215     for ( int i = 0; i < nbFaces &&  f2 < 0;  ++i )
4216       if ( SMESH_MesherHelper::IsSubShape( *edge, f2Normal[i].first ))
4217         (( f1 < 0 ) ? f1 : f2 ) = i;
4218
4219     if ( f2 >= 0 )
4220       pln[ f1 ].ComputeIntersectionLine( pln[ f2 ], TopoDS::Edge( *edge ), TopoDS::Vertex( V ));
4221   }
4222
4223   // get a common point
4224   gp_XYZ commonPnt( 0, 0, 0 );
4225   int nbPoints = 0;
4226   bool isPointFound;
4227   for ( int i = 0; i < nbFaces; ++i )
4228   {
4229     commonPnt += pln[ i ].GetCommonPoint( isPointFound, TopoDS::Vertex( V ));
4230     nbPoints  += isPointFound;
4231   }
4232   gp_XYZ wgtNorm = getWeigthedNormal( edge );
4233   if ( nbPoints == 0 )
4234     return wgtNorm;
4235
4236   commonPnt /= nbPoints;
4237   resNorm = commonPnt - p0;
4238   if ( lastNoOffset )
4239     return resNorm;
4240
4241   // choose the best among resNorm and wgtNorm
4242   resNorm.Normalize();
4243   wgtNorm.Normalize();
4244   double resMinDot = std::numeric_limits<double>::max();
4245   double wgtMinDot = std::numeric_limits<double>::max();
4246   for ( int i = 0; i < nbFaces - lastNoOffset; ++i )
4247   {
4248     resMinDot = Min( resMinDot, resNorm * f2Normal[i].second );
4249     wgtMinDot = Min( wgtMinDot, wgtNorm * f2Normal[i].second );
4250   }
4251
4252   if ( Max( resMinDot, wgtMinDot ) < theMinSmoothCosin )
4253   {
4254     edge->Set( _LayerEdge::MULTI_NORMAL );
4255   }
4256
4257   return ( resMinDot > wgtMinDot ) ? resNorm : wgtNorm;
4258 }
4259
4260 //================================================================================
4261 /*!
4262  * \brief Compute line of intersection of 2 planes
4263  */
4264 //================================================================================
4265
4266 void _OffsetPlane::ComputeIntersectionLine( _OffsetPlane&        pln,
4267                                             const TopoDS_Edge&   E,
4268                                             const TopoDS_Vertex& V )
4269 {
4270   int iNext = bool( _faceIndexNext[0] >= 0 );
4271   _faceIndexNext[ iNext ] = pln._faceIndex;
4272
4273   gp_XYZ n1 = _plane.Axis().Direction().XYZ();
4274   gp_XYZ n2 = pln._plane.Axis().Direction().XYZ();
4275
4276   gp_XYZ lineDir = n1 ^ n2;
4277
4278   double x = Abs( lineDir.X() );
4279   double y = Abs( lineDir.Y() );
4280   double z = Abs( lineDir.Z() );
4281
4282   int cooMax; // max coordinate
4283   if (x > y) {
4284     if (x > z) cooMax = 1;
4285     else       cooMax = 3;
4286   }
4287   else {
4288     if (y > z) cooMax = 2;
4289     else       cooMax = 3;
4290   }
4291
4292   gp_Pnt linePos;
4293   if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
4294   {
4295     // parallel planes - intersection is an offset of the common EDGE
4296     gp_Pnt p = BRep_Tool::Pnt( V );
4297     linePos  = 0.5 * (( p.XYZ() + n1 ) + ( p.XYZ() + n2 ));
4298     lineDir  = getEdgeDir( E, V, 0.1 * SMESH_Algo::EdgeLength( E ));
4299   }
4300   else
4301   {
4302     // the constants in the 2 plane equations
4303     double d1 = - ( _plane.Axis().Direction().XYZ()     * _plane.Location().XYZ() );
4304     double d2 = - ( pln._plane.Axis().Direction().XYZ() * pln._plane.Location().XYZ() );
4305
4306     switch ( cooMax ) {
4307     case 1:
4308       linePos.SetX(  0 );
4309       linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
4310       linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
4311       break;
4312     case 2:
4313       linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
4314       linePos.SetY(  0 );
4315       linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
4316       break;
4317     case 3:
4318       linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
4319       linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
4320       linePos.SetZ(  0 );
4321     }
4322   }
4323   gp_Lin& line = _lines[ iNext ];
4324   line.SetDirection( lineDir );
4325   line.SetLocation ( linePos );
4326
4327   _isLineOK[ iNext ] = true;
4328
4329
4330   iNext = bool( pln._faceIndexNext[0] >= 0 );
4331   pln._lines        [ iNext ] = line;
4332   pln._faceIndexNext[ iNext ] = this->_faceIndex;
4333   pln._isLineOK     [ iNext ] = true;
4334 }
4335
4336 //================================================================================
4337 /*!
4338  * \brief Computes intersection point of two _lines
4339  */
4340 //================================================================================
4341
4342 gp_XYZ _OffsetPlane::GetCommonPoint(bool&                 isFound,
4343                                     const TopoDS_Vertex & V) const
4344 {
4345   gp_XYZ p( 0,0,0 );
4346   isFound = false;
4347
4348   if ( NbLines() == 2 )
4349   {
4350     gp_Vec lPerp0 = _lines[0].Direction().XYZ() ^ _plane.Axis().Direction().XYZ();
4351     double  dot01 = lPerp0 * _lines[1].Direction().XYZ();
4352     if ( Abs( dot01 ) > 0.05 )
4353     {
4354       gp_Vec l0l1 = _lines[1].Location().XYZ() - _lines[0].Location().XYZ();
4355       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
4356       p = ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * u1 );
4357       isFound = true;
4358     }
4359     else
4360     {
4361       gp_Pnt  pV ( BRep_Tool::Pnt( V ));
4362       gp_Vec  lv0( _lines[0].Location(), pV    ),  lv1(_lines[1].Location(), pV     );
4363       double dot0( lv0 * _lines[0].Direction() ), dot1( lv1 * _lines[1].Direction() );
4364       p += 0.5 * ( _lines[0].Location().XYZ() + _lines[0].Direction().XYZ() * dot0 );
4365       p += 0.5 * ( _lines[1].Location().XYZ() + _lines[1].Direction().XYZ() * dot1 );
4366       isFound = true;
4367     }
4368   }
4369
4370   return p;
4371 }
4372
4373 //================================================================================
4374 /*!
4375  * \brief Find 2 neighbor nodes of a node on EDGE
4376  */
4377 //================================================================================
4378
4379 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
4380                                         const SMDS_MeshNode*& n1,
4381                                         const SMDS_MeshNode*& n2,
4382                                         _EdgesOnShape&        eos,
4383                                         _SolidData&           data)
4384 {
4385   const SMDS_MeshNode* node = edge->_nodes[0];
4386   const int        shapeInd = eos._shapeID;
4387   SMESHDS_SubMesh*   edgeSM = 0;
4388   if ( eos.ShapeType() == TopAbs_EDGE )
4389   {
4390     edgeSM = eos._subMesh->GetSubMeshDS();
4391     if ( !edgeSM || edgeSM->NbElements() == 0 )
4392       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
4393   }
4394   int iN = 0;
4395   n2 = 0;
4396   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
4397   while ( eIt->more() && !n2 )
4398   {
4399     const SMDS_MeshElement* e = eIt->next();
4400     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
4401     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
4402     if ( edgeSM )
4403     {
4404       if (!edgeSM->Contains(e)) continue;
4405     }
4406     else
4407     {
4408       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode( nNeibor, getMeshDS() );
4409       if ( !SMESH_MesherHelper::IsSubShape( s, eos._sWOL )) continue;
4410     }
4411     ( iN++ ? n2 : n1 ) = nNeibor;
4412   }
4413   if ( !n2 )
4414     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
4415   return true;
4416 }
4417
4418 //================================================================================
4419 /*!
4420  * \brief Create _Curvature
4421  */
4422 //================================================================================
4423
4424 _Curvature* _Curvature::New( double avgNormProj, double avgDist )
4425 {
4426   // double   _r; // radius
4427   // double   _k; // factor to correct node smoothed position
4428   // double   _h2lenRatio; // avgNormProj / (2*avgDist)
4429   // gp_Pnt2d _uv; // UV used in putOnOffsetSurface()
4430
4431   _Curvature* c = 0;
4432   if ( fabs( avgNormProj / avgDist ) > 1./200 )
4433   {
4434     c = _Factory::NewCurvature();
4435     c->_r = avgDist * avgDist / avgNormProj;
4436     c->_k = avgDist * avgDist / c->_r / c->_r;
4437     //c->_k = avgNormProj / c->_r;
4438     c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
4439     c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
4440
4441     c->_uv.SetCoord( 0., 0. );
4442   }
4443   return c;
4444 }
4445
4446 //================================================================================
4447 /*!
4448  * \brief Set _curvature and _2neibors->_plnNorm by 2 neighbor nodes residing the same EDGE
4449  */
4450 //================================================================================
4451
4452 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
4453                                      const SMDS_MeshNode* n2,
4454                                      const _EdgesOnShape& eos,
4455                                      SMESH_MesherHelper&  helper)
4456 {
4457   if ( eos.ShapeType() != TopAbs_EDGE )
4458     return;
4459   if ( _curvature && Is( SMOOTHED_C1 ))
4460     return;
4461
4462   gp_XYZ  pos = SMESH_TNodeXYZ( _nodes[0] );
4463   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
4464   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
4465
4466   // Set _curvature
4467
4468   double      sumLen = vec1.Modulus() + vec2.Modulus();
4469   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
4470   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
4471   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
4472   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
4473   _curvature = _Curvature::New( avgNormProj, avgLen );
4474   // if ( _curvature )
4475   //   debugMsg( _nodes[0]->GetID()
4476   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
4477   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
4478   //             << _curvature->lenDelta(0) );
4479
4480   // Set _plnNorm
4481
4482   if ( eos._sWOL.IsNull() )
4483   {
4484     TopoDS_Edge  E = TopoDS::Edge( eos._shape );
4485     // if ( SMESH_Algo::isDegenerated( E ))
4486     //   return;
4487     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
4488     gp_XYZ plnNorm = dirE ^ _normal;
4489     double proj0   = plnNorm * vec1;
4490     double proj1   = plnNorm * vec2;
4491     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
4492     {
4493       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
4494       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
4495     }
4496   }
4497 }
4498
4499 //================================================================================
4500 /*!
4501  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
4502  * this and the other _LayerEdge are inflated along a FACE or an EDGE
4503  */
4504 //================================================================================
4505
4506 gp_XYZ _LayerEdge::Copy( _LayerEdge&         other,
4507                          _EdgesOnShape&      eos,
4508                          SMESH_MesherHelper& helper )
4509 {
4510   _nodes     = other._nodes;
4511   _normal    = other._normal;
4512   _len       = 0;
4513   _lenFactor = other._lenFactor;
4514   _cosin     = other._cosin;
4515   _2neibors  = other._2neibors;
4516   _curvature = other._curvature;
4517   _2neibors  = other._2neibors;
4518   _maxLen    = Precision::Infinite();//other._maxLen;
4519   _flags     = 0;
4520   _smooFunction = 0;
4521
4522   gp_XYZ lastPos( 0,0,0 );
4523   if ( eos.SWOLType() == TopAbs_EDGE )
4524   {
4525     double u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes[0] );
4526     _pos.push_back( gp_XYZ( u, 0, 0));
4527
4528     u = helper.GetNodeU( TopoDS::Edge( eos._sWOL ), _nodes.back() );
4529     lastPos.SetX( u );
4530   }
4531   else // TopAbs_FACE
4532   {
4533     gp_XY uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes[0]);
4534     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
4535
4536     uv = helper.GetNodeUV( TopoDS::Face( eos._sWOL ), _nodes.back() );
4537     lastPos.SetX( uv.X() );
4538     lastPos.SetY( uv.Y() );
4539   }
4540   return lastPos;
4541 }
4542
4543 //================================================================================
4544 /*!
4545  * \brief Set _cosin and _lenFactor
4546  */
4547 //================================================================================
4548
4549 double _LayerEdge::SetCosin( double cosin )
4550 {
4551   _cosin = cosin;
4552   cosin = Abs( _cosin );
4553   //_lenFactor = ( cosin < 1.-1e-12 ) ?  1./sqrt(1-cosin*cosin ) : 1.0;
4554   double realLenFactor;
4555   if ( cosin < 1.-1e-12 )
4556   {
4557     _lenFactor = realLenFactor = 1./sqrt(1-cosin*cosin );
4558   }
4559   else
4560   {
4561     _lenFactor = 1;
4562     realLenFactor = Precision::Infinite();
4563   }
4564
4565   return realLenFactor;
4566 }
4567
4568 //================================================================================
4569 /*!
4570  * \brief Check if another _LayerEdge is a neighbor on EDGE
4571  */
4572 //================================================================================
4573
4574 bool _LayerEdge::IsNeiborOnEdge( const _LayerEdge* edge ) const
4575 {
4576   return (( this->_2neibors && this->_2neibors->include( edge )) ||
4577           ( edge->_2neibors && edge->_2neibors->include( this )));
4578 }
4579
4580 //================================================================================
4581 /*!
4582  * \brief Fills a vector<_Simplex > 
4583  */
4584 //================================================================================
4585
4586 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
4587                              vector<_Simplex>&    simplices,
4588                              const set<TGeomID>&  ingnoreShapes,
4589                              const _SolidData*    dataToCheckOri,
4590                              const bool           toSort)
4591 {
4592   simplices.clear();
4593   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
4594   while ( fIt->more() )
4595   {
4596     const SMDS_MeshElement* f = fIt->next();
4597     const TGeomID    shapeInd = f->getshapeId();
4598     if ( ingnoreShapes.count( shapeInd )) continue;
4599     const int nbNodes = f->NbCornerNodes();
4600     const int  srcInd = f->GetNodeIndex( node );
4601     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
4602     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
4603     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
4604     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
4605       std::swap( nPrev, nNext );
4606     simplices.push_back( _Simplex( nPrev, nNext, ( nbNodes == 3 ? 0 : nOpp )));
4607   }
4608
4609   if ( toSort )
4610     SortSimplices( simplices );
4611 }
4612
4613 //================================================================================
4614 /*!
4615  * \brief Set neighbor simplices side by side
4616  */
4617 //================================================================================
4618
4619 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
4620 {
4621   vector<_Simplex> sortedSimplices( simplices.size() );
4622   sortedSimplices[0] = simplices[0];
4623   size_t nbFound = 0;
4624   for ( size_t i = 1; i < simplices.size(); ++i )
4625   {
4626     for ( size_t j = 1; j < simplices.size(); ++j )
4627       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
4628       {
4629         sortedSimplices[i] = simplices[j];
4630         nbFound++;
4631         break;
4632       }
4633   }
4634   if ( nbFound == simplices.size() - 1 )
4635     simplices.swap( sortedSimplices );
4636 }
4637
4638 //================================================================================
4639 /*!
4640  * \brief DEBUG. Create groups containing temporary data of _LayerEdge's
4641  */
4642 //================================================================================
4643
4644 void _ViscousBuilder::makeGroupOfLE()
4645 {
4646 #ifdef _DEBUG_
4647   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
4648   {
4649     if ( _sdVec[i]._n2eMap.empty() ) continue;
4650
4651     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
4652     TNode2Edge::iterator n2e;
4653     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4654     {
4655       _LayerEdge* le = n2e->second;
4656       // for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
4657       //   dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
4658       //           << ", " << le->_nodes[iN]->GetID() <<"])");
4659       if ( le ) {
4660         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[0]->GetID()
4661                 << ", " << le->_nodes.back()->GetID() <<"]) # " << le->_flags );
4662       }
4663     }
4664     dumpFunctionEnd();
4665
4666     dumpFunction( SMESH_Comment("makeNormals") << i );
4667     for ( n2e = _sdVec[i]._n2eMap.begin(); n2e != _sdVec[i]._n2eMap.end(); ++n2e )
4668     {
4669       _LayerEdge* edge = n2e->second;
4670       SMESH_TNodeXYZ nXYZ( edge->_nodes[0] );
4671       nXYZ += edge->_normal * _sdVec[i]._stepSize;
4672       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") << edge->_nodes[0]->GetID()
4673               << ", mesh.AddNode( "<< nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
4674     }
4675     dumpFunctionEnd();
4676
4677     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
4678     dumpCmd( "faceId1 = mesh.NbElements()" );
4679     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
4680     for ( ; fExp.More(); fExp.Next() )
4681     {
4682       if ( const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current() ))
4683       {
4684         if ( sm->NbElements() == 0 ) continue;
4685         SMDS_ElemIteratorPtr fIt = sm->GetElements();
4686         while ( fIt->more())
4687         {
4688           const SMDS_MeshElement* e = fIt->next();
4689           SMESH_Comment cmd("mesh.AddFace([");
4690           for ( int j = 0; j < e->NbCornerNodes(); ++j )
4691             cmd << e->GetNode(j)->GetID() << (j+1 < e->NbCornerNodes() ? ",": "])");
4692           dumpCmd( cmd );
4693         }
4694       }
4695     }
4696     dumpCmd( "faceId2 = mesh.NbElements()" );
4697     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
4698              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
4699              << "'%s-%s' % (faceId1+1, faceId2))");
4700     dumpFunctionEnd();
4701   }
4702 #endif
4703 }
4704
4705 //================================================================================
4706 /*!
4707  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
4708  */
4709 //================================================================================
4710
4711 void _ViscousBuilder::computeGeomSize( _SolidData& data )
4712 {
4713   data._geomSize = Precision::Infinite();
4714   double intersecDist;
4715   const SMDS_MeshElement* face;
4716   SMESH_MesherHelper helper( *_mesh );
4717
4718   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
4719     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
4720                                            data._proxyMesh->GetFaces( data._solid )));
4721
4722   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4723   {
4724     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4725     if ( eos._edges.empty() )
4726       continue;
4727     // get neighbor faces, intersection with which should not be considered since
4728     // collisions are avoided by means of smoothing
4729     set< TGeomID > neighborFaces;
4730     if ( eos._hyp.ToSmooth() )
4731     {
4732       SMESH_subMeshIteratorPtr subIt =
4733         eos._subMesh->getDependsOnIterator(/*includeSelf=*/eos.ShapeType() != TopAbs_FACE );
4734       while ( subIt->more() )
4735       {
4736         SMESH_subMesh* sm = subIt->next();
4737         PShapeIteratorPtr fIt = helper.GetAncestors( sm->GetSubShape(), *_mesh, TopAbs_FACE );
4738         while ( const TopoDS_Shape* face = fIt->next() )
4739           neighborFaces.insert( getMeshDS()->ShapeToIndex( *face ));
4740       }
4741     }
4742     // find intersections
4743     double thinkness = eos._hyp.GetTotalThickness();
4744     for ( size_t i = 0; i < eos._edges.size(); ++i )
4745     {
4746       if ( eos._edges[i]->_nodes.size() < 2 ) continue;
4747       eos._edges[i]->SetMaxLen( thinkness );
4748       eos._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon, eos, &face );
4749       if ( intersecDist > 0 && face )
4750       {
4751         data._geomSize = Min( data._geomSize, intersecDist );
4752         if ( !neighborFaces.count( face->getshapeId() ))
4753           eos[i]->SetMaxLen( Min( thinkness, intersecDist / ( face->GetID() < 0 ? 3. : 2. )));
4754       }
4755     }
4756   }
4757
4758   data._maxThickness = 0;
4759   data._minThickness = 1e100;
4760   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
4761   for ( ; hyp != data._hyps.end(); ++hyp )
4762   {
4763     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
4764     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
4765   }
4766
4767   // Limit inflation step size by geometry size found by intersecting
4768   // normals of _LayerEdge's with mesh faces
4769   if ( data._stepSize > 0.3 * data._geomSize )
4770     limitStepSize( data, 0.3 * data._geomSize );
4771
4772   if ( data._stepSize > data._minThickness )
4773     limitStepSize( data, data._minThickness );
4774
4775
4776   // -------------------------------------------------------------------------
4777   // Detect _LayerEdge which can't intersect with opposite or neighbor layer,
4778   // so no need in detecting intersection at each inflation step
4779   // -------------------------------------------------------------------------
4780
4781   int nbSteps = data._maxThickness / data._stepSize;
4782   if ( nbSteps < 3 || nbSteps * data._n2eMap.size() < 100000 )
4783     return;
4784
4785   vector< const SMDS_MeshElement* > closeFaces;
4786   int nbDetected = 0;
4787
4788   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4789   {
4790     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
4791     if ( eos._edges.empty() || eos.ShapeType() != TopAbs_FACE )
4792       continue;
4793
4794     for ( size_t i = 0; i < eos.size(); ++i )
4795     {
4796       SMESH_NodeXYZ p( eos[i]->_nodes[0] );
4797       double radius = data._maxThickness + 2 * eos[i]->_maxLen;
4798       closeFaces.clear();
4799       searcher->GetElementsInSphere( p, radius, SMDSAbs_Face, closeFaces );
4800
4801       bool toIgnore = true;
4802       for ( size_t iF = 0; iF < closeFaces.size()  && toIgnore; ++iF )
4803         if ( !( toIgnore = ( closeFaces[ iF ]->getshapeId() == eos._shapeID ||
4804                              data._ignoreFaceIds.count( closeFaces[ iF ]->getshapeId() ))))
4805         {
4806           // check if a _LayerEdge will inflate in a direction opposite to a direction
4807           // toward a close face
4808           bool allBehind = true;
4809           for ( int iN = 0; iN < closeFaces[ iF ]->NbCornerNodes()  && allBehind; ++iN )
4810           {
4811             SMESH_NodeXYZ pi( closeFaces[ iF ]->GetNode( iN ));
4812             allBehind = (( pi - p ) * eos[i]->_normal < 0.1 * data._stepSize );
4813           }
4814           toIgnore = allBehind;
4815         }
4816
4817
4818       if ( toIgnore ) // no need to detect intersection
4819       {
4820         eos[i]->Set( _LayerEdge::INTERSECTED );
4821         ++nbDetected;
4822       }
4823     }
4824   }
4825
4826   debugMsg( "Nb LE to intersect " << data._n2eMap.size()-nbDetected << ", ignore " << nbDetected );
4827
4828   return;
4829 }
4830
4831 //================================================================================
4832 /*!
4833  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
4834  */
4835 //================================================================================
4836
4837 bool _ViscousBuilder::inflate(_SolidData& data)
4838 {
4839   SMESH_MesherHelper helper( *_mesh );
4840
4841   const double tgtThick = data._maxThickness;
4842
4843   if ( data._stepSize < 1. )
4844     data._epsilon = data._stepSize * 1e-7;
4845
4846   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
4847   _pyDump->Pause();
4848
4849   findCollisionEdges( data, helper );
4850
4851   limitMaxLenByCurvature( data, helper );
4852
4853   _pyDump->Resume();
4854
4855   // limit length of _LayerEdge's around MULTI_NORMAL _LayerEdge's
4856   for ( size_t i = 0; i < data._edgesOnShape.size(); ++i )
4857     if ( data._edgesOnShape[i].ShapeType() == TopAbs_VERTEX &&
4858          data._edgesOnShape[i]._edges.size() > 0 &&
4859          data._edgesOnShape[i]._edges[0]->Is( _LayerEdge::MULTI_NORMAL ))
4860     {
4861       data._edgesOnShape[i]._edges[0]->Unset( _LayerEdge::BLOCKED );
4862       data._edgesOnShape[i]._edges[0]->Block( data );
4863     }
4864
4865   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
4866
4867   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
4868   int nbSteps = 0, nbRepeats = 0;
4869   while ( avgThick < 0.99 )
4870   {
4871     // new target length
4872     double prevThick = curThick;
4873     curThick += data._stepSize;
4874     if ( curThick > tgtThick )
4875     {
4876       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
4877       nbRepeats++;
4878     }
4879
4880     double stepSize = curThick - prevThick;
4881     updateNormalsOfSmoothed( data, helper, nbSteps, stepSize ); // to ease smoothing
4882
4883     // Elongate _LayerEdge's
4884     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
4885     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4886     {
4887       _EdgesOnShape& eos = data._edgesOnShape[iS];
4888       if ( eos._edges.empty() ) continue;
4889
4890       const double shapeCurThick = Min( curThick, eos._hyp.GetTotalThickness() );
4891       for ( size_t i = 0; i < eos._edges.size(); ++i )
4892       {
4893         eos._edges[i]->SetNewLength( shapeCurThick, eos, helper );
4894       }
4895     }
4896     dumpFunctionEnd();
4897
4898     if ( !updateNormals( data, helper, nbSteps, stepSize )) // to avoid collisions
4899       return false;
4900
4901     // Improve and check quality
4902     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
4903     {
4904       if ( nbSteps > 0 )
4905       {
4906 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
4907         debugMsg("NOT INVALIDATED STEP!");
4908         return error("Smoothing failed", data._index);
4909 #endif
4910         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
4911         for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4912         {
4913           _EdgesOnShape& eos = data._edgesOnShape[iS];
4914           for ( size_t i = 0; i < eos._edges.size(); ++i )
4915             eos._edges[i]->InvalidateStep( nbSteps+1, eos );
4916         }
4917         dumpFunctionEnd();
4918       }
4919       break; // no more inflating possible
4920     }
4921     nbSteps++;
4922
4923     // Evaluate achieved thickness
4924     avgThick = 0;
4925     int nbActiveEdges = 0;
4926     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4927     {
4928       _EdgesOnShape& eos = data._edgesOnShape[iS];
4929       if ( eos._edges.empty() ) continue;
4930
4931       const double shapeTgtThick = eos._hyp.GetTotalThickness();
4932       for ( size_t i = 0; i < eos._edges.size(); ++i )
4933       {
4934         if ( eos._edges[i]->_nodes.size() > 1 )
4935           avgThick    += Min( 1., eos._edges[i]->_len / shapeTgtThick );
4936         else
4937           avgThick    += 1;
4938         nbActiveEdges += ( ! eos._edges[i]->Is( _LayerEdge::BLOCKED ));
4939       }
4940     }
4941     avgThick /= data._n2eMap.size();
4942     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
4943
4944 #ifdef BLOCK_INFLATION
4945     if ( nbActiveEdges == 0 )
4946     {
4947       debugMsg( "-- Stop inflation since all _LayerEdge's BLOCKED " );
4948       break;
4949     }
4950 #else
4951     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
4952     {
4953       debugMsg( "-- Stop inflation since "
4954                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
4955                 << tgtThick * avgThick << " ) * " << safeFactor );
4956       break;
4957     }
4958 #endif
4959
4960     // new step size
4961     limitStepSize( data, 0.25 * distToIntersection );
4962     if ( data._stepSizeNodes[0] )
4963       data._stepSize = data._stepSizeCoeff *
4964         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
4965
4966   } // while ( avgThick < 0.99 )
4967
4968   if ( nbSteps == 0 )
4969     return error("failed at the very first inflation step", data._index);
4970
4971   if ( avgThick < 0.99 )
4972   {
4973     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
4974     {
4975       data._proxyMesh->_warning.reset
4976         ( new SMESH_ComputeError (COMPERR_WARNING,
4977                                   SMESH_Comment("Thickness ") << tgtThick <<
4978                                   " of viscous layers not reached,"
4979                                   " average reached thickness is " << avgThick*tgtThick));
4980     }
4981   }
4982
4983   // Restore position of src nodes moved by inflation on _noShrinkShapes
4984   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
4985   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
4986   {
4987     _EdgesOnShape& eos = data._edgesOnShape[iS];
4988     if ( !eos._edges.empty() && eos._edges[0]->_nodes.size() == 1 )
4989       for ( size_t i = 0; i < eos._edges.size(); ++i )
4990       {
4991         restoreNoShrink( *eos._edges[ i ] );
4992       }
4993   }
4994   dumpFunctionEnd();
4995
4996   return safeFactor > 0; // == true (avoid warning: unused variable 'safeFactor')
4997 }
4998
4999 //================================================================================
5000 /*!
5001  * \brief Improve quality of layer inner surface and check intersection
5002  */
5003 //================================================================================
5004
5005 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
5006                                      const int   infStep,
5007                                      double &    distToIntersection)
5008 {
5009   if ( data._nbShapesToSmooth == 0 )
5010     return true; // no shapes needing smoothing
5011
5012   bool moved, improved;
5013   double vol;
5014   vector< _LayerEdge* >    movedEdges, badEdges;
5015   vector< _EdgesOnShape* > eosC1; // C1 continues shapes
5016   vector< bool >           isConcaveFace;
5017
5018   SMESH_MesherHelper helper(*_mesh);
5019   Handle(ShapeAnalysis_Surface) surface;
5020   TopoDS_Face F;
5021
5022   for ( int isFace = 0; isFace < 2; ++isFace ) // smooth on [ EDGEs, FACEs ]
5023   {
5024     const TopAbs_ShapeEnum shapeType = isFace ? TopAbs_FACE : TopAbs_EDGE;
5025
5026     for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5027     {
5028       _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5029       if ( !eos._toSmooth ||
5030            eos.ShapeType() != shapeType ||
5031            eos._edges.empty() )
5032         continue;
5033
5034       // already smoothed?
5035       // bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= infStep+1 );
5036       // if ( !toSmooth ) continue;
5037
5038       if ( !eos._hyp.ToSmooth() )
5039       {
5040         // smooth disabled by the user; check validy only
5041         if ( !isFace ) continue;
5042         badEdges.clear();
5043         for ( size_t i = 0; i < eos._edges.size(); ++i )
5044         {
5045           _LayerEdge* edge = eos._edges[i];
5046           for ( size_t iF = 0; iF < edge->_simplices.size(); ++iF )
5047             if ( !edge->_simplices[iF].IsForward( edge->_nodes[0], edge->_pos.back(), vol ))
5048             {
5049               // debugMsg( "-- Stop inflation. Bad simplex ("
5050               //           << " "<< edge->_nodes[0]->GetID()
5051               //           << " "<< edge->_nodes.back()->GetID()
5052               //           << " "<< edge->_simplices[iF]._nPrev->GetID()
5053               //           << " "<< edge->_simplices[iF]._nNext->GetID() << " ) ");
5054               // return false;
5055               badEdges.push_back( edge );
5056             }
5057         }
5058         if ( !badEdges.empty() )
5059         {
5060           eosC1.resize(1);
5061           eosC1[0] = &eos;
5062           int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5063           if ( nbBad > 0 )
5064             return false;
5065         }
5066         continue; // goto the next EDGE or FACE
5067       }
5068
5069       // prepare data
5070       if ( eos.SWOLType() == TopAbs_FACE )
5071       {
5072         if ( !F.IsSame( eos._sWOL )) {
5073           F = TopoDS::Face( eos._sWOL );
5074           helper.SetSubShape( F );
5075           surface = helper.GetSurface( F );
5076         }
5077       }
5078       else
5079       {
5080         F.Nullify(); surface.Nullify();
5081       }
5082       const TGeomID sInd = eos._shapeID;
5083
5084       // perform smoothing
5085
5086       if ( eos.ShapeType() == TopAbs_EDGE )
5087       {
5088         dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<infStep);
5089
5090         if ( !eos._edgeSmoother->Perform( data, surface, F, helper ))
5091         {
5092           // smooth on EDGE's (normally we should not get here)
5093           int step = 0;
5094           do {
5095             moved = false;
5096             for ( size_t i = 0; i < eos._edges.size(); ++i )
5097             {
5098               moved |= eos._edges[i]->SmoothOnEdge( surface, F, helper );
5099             }
5100             dumpCmd( SMESH_Comment("# end step ")<<step);
5101           }
5102           while ( moved && step++ < 5 );
5103         }
5104         dumpFunctionEnd();
5105       }
5106
5107       else // smooth on FACE
5108       {
5109         eosC1.clear();
5110         eosC1.push_back( & eos );
5111         eosC1.insert( eosC1.end(), eos._eosC1.begin(), eos._eosC1.end() );
5112
5113         movedEdges.clear();
5114         isConcaveFace.resize( eosC1.size() );
5115         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5116         {
5117           isConcaveFace[ iEOS ] = data._concaveFaces.count( eosC1[ iEOS ]->_shapeID  );
5118
5119           if ( eosC1[ iEOS ]->_mapper2D )
5120           {
5121             // compute node position by boundary node position in structured mesh
5122             dumpFunction(SMESH_Comment("map2dS")<<data._index<<"_Fa"<<eos._shapeID
5123                          <<"_InfStep"<<infStep);
5124
5125             eosC1[ iEOS ]->_mapper2D->ComputeNodePositions();
5126
5127             for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5128               le->_pos.back() = SMESH_NodeXYZ( le->_nodes.back() );
5129
5130             dumpFunctionEnd();
5131           }
5132           else
5133           {
5134             for ( _LayerEdge* le : eosC1[ iEOS ]->_edges )
5135               if ( le->Is( _LayerEdge::MOVED ) ||
5136                    le->Is( _LayerEdge::NEAR_BOUNDARY ))
5137                 movedEdges.push_back( le );
5138           }
5139           makeOffsetSurface( *eosC1[ iEOS ], helper );
5140         }
5141
5142         int step = 0, stepLimit = 5, nbBad = 0;
5143         while (( ++step <= stepLimit ) || improved )
5144         {
5145           int oldBadNb = nbBad;
5146           badEdges.clear();
5147
5148 #ifdef INCREMENTAL_SMOOTH
5149           // smooth moved only
5150           if ( !movedEdges.empty() )
5151             dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5152                          <<"_InfStep"<<infStep<<"_"<<step); // debug
5153           bool findBest = false; // ( step == stepLimit );
5154           for ( size_t i = 0; i < movedEdges.size(); ++i )
5155           {
5156             movedEdges[i]->Unset( _LayerEdge::SMOOTHED );
5157             if ( movedEdges[i]->Smooth( step, findBest, movedEdges ) > 0 )
5158               badEdges.push_back( movedEdges[i] );
5159           }
5160 #else
5161           // smooth all
5162           dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
5163                        <<"_InfStep"<<infStep<<"_"<<step); // debug
5164           bool findBest = ( step == stepLimit || isConcaveFace[ iEOS ]);
5165           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5166           {
5167             if ( eosC1[ iEOS ]->_mapper2D )
5168               continue;
5169             vector< _LayerEdge* > & edges = eosC1[ iEOS ]->_edges;
5170             for ( size_t i = 0; i < edges.size(); ++i )
5171             {
5172               edges[i]->Unset( _LayerEdge::SMOOTHED );
5173               if ( edges[i]->Smooth( step, findBest, false ) > 0 )
5174                 badEdges.push_back( eos._edges[i] );
5175             }
5176           }
5177 #endif
5178           nbBad = badEdges.size();
5179
5180           if ( nbBad > 0 )
5181             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5182
5183           if ( !badEdges.empty() && step >= stepLimit / 2 )
5184           {
5185             if ( badEdges[0]->Is( _LayerEdge::ON_CONCAVE_FACE ))
5186               stepLimit = 9;
5187
5188             // resolve hard smoothing situation around concave VERTEXes
5189             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5190             {
5191               vector< _EdgesOnShape* > & eosCoVe = eosC1[ iEOS ]->_eosConcaVer;
5192               for ( size_t i = 0; i < eosCoVe.size(); ++i )
5193                 eosCoVe[i]->_edges[0]->MoveNearConcaVer( eosCoVe[i], eosC1[ iEOS ],
5194                                                          step, badEdges );
5195             }
5196             // look for the best smooth of _LayerEdge's neighboring badEdges
5197             nbBad = 0;
5198             for ( size_t i = 0; i < badEdges.size(); ++i )
5199             {
5200               _LayerEdge* ledge = badEdges[i];
5201               for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
5202               {
5203                 ledge->_neibors[iN]->Unset( _LayerEdge::SMOOTHED );
5204                 nbBad += ledge->_neibors[iN]->Smooth( step, true, /*findBest=*/true );
5205               }
5206               ledge->Unset( _LayerEdge::SMOOTHED );
5207               nbBad += ledge->Smooth( step, true, /*findBest=*/true );
5208             }
5209             debugMsg(SMESH_Comment("nbBad = ") << nbBad );
5210           }
5211
5212           if ( nbBad == oldBadNb  &&
5213                nbBad > 0 &&
5214                step < stepLimit ) // smooth w/o check of validity
5215           {
5216             dumpFunctionEnd();
5217             dumpFunction(SMESH_Comment("smoothWoCheck")<<data._index<<"_Fa"<<sInd
5218                          <<"_InfStep"<<infStep<<"_"<<step); // debug
5219             for ( size_t i = 0; i < movedEdges.size(); ++i )
5220             {
5221               movedEdges[i]->SmoothWoCheck();
5222             }
5223             if ( stepLimit < 9 )
5224               stepLimit++;
5225           }
5226
5227           improved = ( nbBad < oldBadNb );
5228
5229           dumpFunctionEnd();
5230
5231           if (( step % 3 == 1 ) || ( nbBad > 0 && step >= stepLimit / 2 ))
5232             for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5233             {
5234               putOnOffsetSurface( *eosC1[ iEOS ], infStep, eosC1, step, /*moveAll=*/step == 1 );
5235             }
5236
5237         } // smoothing steps
5238
5239         // project -- to prevent intersections or to fix bad simplices
5240         for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5241         {
5242           if ( ! eosC1[ iEOS ]->_eosConcaVer.empty() || nbBad > 0 )
5243             putOnOffsetSurface( *eosC1[ iEOS ], -infStep, eosC1 );
5244         }
5245
5246         //if ( !badEdges.empty() )
5247         {
5248           badEdges.clear();
5249           for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5250           {
5251             for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5252             {
5253               if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5254
5255               _LayerEdge* edge = eosC1[ iEOS ]->_edges[i];
5256               edge->CheckNeiborsOnBoundary( & badEdges );
5257               if (( nbBad > 0 ) ||
5258                   ( edge->Is( _LayerEdge::BLOCKED ) && edge->Is( _LayerEdge::NEAR_BOUNDARY )))
5259               {
5260                 SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5261                 gp_XYZ        prevXYZ = edge->PrevCheckPos();
5262                 for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5263                   if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5264                   {
5265                     debugMsg("Bad simplex ( " << edge->_nodes[0]->GetID()
5266                              << " "<< tgtXYZ._node->GetID()
5267                              << " "<< edge->_simplices[j]._nPrev->GetID()
5268                              << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5269                     badEdges.push_back( edge );
5270                     break;
5271                   }
5272               }
5273             }
5274           }
5275
5276           // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5277           nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5278
5279           if ( nbBad > 0 )
5280             return false;
5281         }
5282
5283       } // // smooth on FACE's
5284     } // loop on shapes
5285   } // smooth on [ EDGEs, FACEs ]
5286
5287   // Check orientation of simplices of _LayerEdge's on EDGEs and VERTEXes
5288   eosC1.resize(1);
5289   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5290   {
5291     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5292     if ( eos.ShapeType() == TopAbs_FACE ||
5293          eos._edges.empty() ||
5294          !eos._sWOL.IsNull() )
5295       continue;
5296
5297     badEdges.clear();
5298     for ( size_t i = 0; i < eos._edges.size(); ++i )
5299     {
5300       _LayerEdge*      edge = eos._edges[i];
5301       if ( edge->_nodes.size() < 2 ) continue;
5302       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5303       //SMESH_TNodeXYZ prevXYZ = edge->_nodes[0];
5304       gp_XYZ        prevXYZ = edge->PrevCheckPos( &eos );
5305       //const gp_XYZ& prevXYZ = edge->PrevPos();
5306       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5307         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5308         {
5309           debugMsg("Bad simplex on bnd ( " << edge->_nodes[0]->GetID()
5310                    << " "<< tgtXYZ._node->GetID()
5311                    << " "<< edge->_simplices[j]._nPrev->GetID()
5312                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5313           badEdges.push_back( edge );
5314           break;
5315         }
5316     }
5317
5318     // try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5319     eosC1[0] = &eos;
5320     int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5321     if ( nbBad > 0 )
5322       return false;
5323   }
5324
5325
5326   // Check if the last segments of _LayerEdge intersects 2D elements;
5327   // checked elements are either temporary faces or faces on surfaces w/o the layers
5328
5329   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
5330     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
5331                                            data._proxyMesh->GetFaces( data._solid )) );
5332
5333 #ifdef BLOCK_INFLATION
5334   const bool toBlockInfaltion = true;
5335 #else
5336   const bool toBlockInfaltion = false;
5337 #endif
5338   distToIntersection = Precision::Infinite();
5339   double dist;
5340   const SMDS_MeshElement* intFace = 0;
5341   const SMDS_MeshElement* closestFace = 0;
5342   _LayerEdge* le = 0;
5343   bool is1stBlocked = true; // dbg
5344   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
5345   {
5346     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
5347     if ( eos._edges.empty() || !eos._sWOL.IsNull() )
5348       continue;
5349     for ( size_t i = 0; i < eos._edges.size(); ++i )
5350     {
5351       if ( eos._edges[i]->Is( _LayerEdge::INTERSECTED ) ||
5352            eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL ))
5353         continue;
5354       if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5355       {
5356         return false;
5357         // commented due to "Illegal hash-positionPosition" error in NETGEN
5358         // on Debian60 on viscous_layers_01/B2 case
5359         // Collision; try to deflate _LayerEdge's causing it
5360         // badEdges.clear();
5361         // badEdges.push_back( eos._edges[i] );
5362         // eosC1[0] = & eos;
5363         // int nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5364         // if ( nbBad > 0 )
5365         //   return false;
5366
5367         // badEdges.clear();
5368         // if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5369         // {
5370         //   if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5371         //   {
5372         //     const SMDS_MeshElement* srcFace =
5373         //       eof->_subMesh->GetSubMeshDS()->GetElement( f->getIdInShape() );
5374         //     SMDS_ElemIteratorPtr nIt = srcFace->nodesIterator();
5375         //     while ( nIt->more() )
5376         //     {
5377         //       const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5378         //       TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5379         //       if ( n2e != data._n2eMap.end() )
5380         //         badEdges.push_back( n2e->second );
5381         //     }
5382         //     eosC1[0] = eof;
5383         //     nbBad = invalidateBadSmooth( data, helper, badEdges, eosC1, infStep );
5384         //     if ( nbBad > 0 )
5385         //       return false;
5386         //   }
5387         // }
5388         // if ( eos._edges[i]->FindIntersection( *searcher, dist, data._epsilon, eos, &intFace ))
5389         //   return false;
5390         // else
5391         //   continue;
5392       }
5393       if ( !intFace )
5394       {
5395         SMESH_Comment msg("Invalid? normal at node "); msg << eos._edges[i]->_nodes[0]->GetID();
5396         debugMsg( msg );
5397         continue;
5398       }
5399
5400       const bool isShorterDist = ( distToIntersection > dist );
5401       if ( toBlockInfaltion || isShorterDist )
5402       {
5403         // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
5404         // lying on this _ConvexFace
5405         if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
5406           if ( convFace->_isTooCurved && convFace->_subIdToEOS.count ( eos._shapeID ))
5407             continue;
5408
5409         // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
5410         // ( avoid limiting the thickness on the case of issue 22576)
5411         if ( intFace->getshapeId() == eos._shapeID  )
5412           continue;
5413
5414         // ignore intersection with intFace of an adjacent FACE
5415         if ( dist > 0.01 * eos._edges[i]->_len )
5416         {
5417           bool toIgnore = false;
5418           if (  eos._toSmooth )
5419           {
5420             const TopoDS_Shape& S = getMeshDS()->IndexToShape( intFace->getshapeId() );
5421             if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
5422             {
5423               TopExp_Explorer sub( eos._shape,
5424                                    eos.ShapeType() == TopAbs_FACE ? TopAbs_EDGE : TopAbs_VERTEX );
5425               for ( ; !toIgnore && sub.More(); sub.Next() )
5426                 // is adjacent - has a common EDGE or VERTEX
5427                 toIgnore = ( helper.IsSubShape( sub.Current(), S ));
5428
5429               if ( toIgnore ) // check angle between normals
5430               {
5431                 gp_XYZ normal;
5432                 if ( SMESH_MeshAlgos::FaceNormal( intFace, normal, /*normalized=*/true ))
5433                   toIgnore  = ( normal * eos._edges[i]->_normal > -0.5 );
5434               }
5435             }
5436           }
5437           if ( !toIgnore ) // check if the edge is a neighbor of intFace
5438           {
5439             for ( size_t iN = 0; !toIgnore &&  iN < eos._edges[i]->_neibors.size(); ++iN )
5440             {
5441               int nInd = intFace->GetNodeIndex( eos._edges[i]->_neibors[ iN ]->_nodes.back() );
5442               toIgnore = ( nInd >= 0 );
5443             }
5444           }
5445           if ( toIgnore )
5446             continue;
5447         }
5448
5449         // intersection not ignored
5450
5451         double minDist = 0;
5452         if ( eos._edges[i]->_maxLen < 0.99 * eos._hyp.GetTotalThickness() ) // limited length
5453           minDist = eos._edges[i]->_len * theThickToIntersection;
5454
5455         if ( toBlockInfaltion && dist < minDist  )
5456         {
5457           if ( is1stBlocked ) { is1stBlocked = false; // debug
5458             dumpFunction(SMESH_Comment("blockIntersected") <<data._index<<"_InfStep"<<infStep);
5459           }
5460           eos._edges[i]->Set( _LayerEdge::INTERSECTED ); // not to intersect
5461           eos._edges[i]->Block( data );                  // not to inflate
5462
5463           //if ( _EdgesOnShape* eof = data.GetShapeEdges( intFace->getshapeId() ))
5464           {
5465             // block _LayerEdge's, on top of which intFace is
5466             if ( const _TmpMeshFace* f = dynamic_cast< const _TmpMeshFace*>( intFace ))
5467             {
5468               const SMDS_MeshElement* srcFace = f->_srcFace;
5469               SMDS_ElemIteratorPtr        nIt = srcFace->nodesIterator();
5470               while ( nIt->more() )
5471               {
5472                 const SMDS_MeshNode* srcNode = static_cast<const SMDS_MeshNode*>( nIt->next() );
5473                 TNode2Edge::iterator n2e = data._n2eMap.find( srcNode );
5474                 if ( n2e != data._n2eMap.end() )
5475                   n2e->second->Block( data );
5476               }
5477             }
5478           }
5479         }
5480
5481         if ( isShorterDist )
5482         {
5483           distToIntersection = dist;
5484           le = eos._edges[i];
5485           closestFace = intFace;
5486         }
5487
5488       } // if ( toBlockInfaltion || isShorterDist )
5489     } // loop on eos._edges
5490   } // loop on data._edgesOnShape
5491
5492   if ( !is1stBlocked )
5493   {
5494     dumpFunctionEnd();
5495   }
5496
5497   if ( closestFace && le )
5498   {
5499 #ifdef __myDEBUG
5500     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
5501     cout << "#Shortest distance: _LayerEdge nodes: tgt " << le->_nodes.back()->GetID()
5502          << " src " << le->_nodes[0]->GetID()<< ", intersection with face ("
5503          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
5504          << ") distance = " << distToIntersection<< endl;
5505 #endif
5506   }
5507
5508   return true;
5509 }
5510
5511 //================================================================================
5512 /*!
5513  * \brief try to fix bad simplices by removing the last inflation step of some _LayerEdge's
5514  *  \param [in,out] badSmooEdges - _LayerEdge's to fix
5515  *  \return int - resulting nb of bad _LayerEdge's
5516  */
5517 //================================================================================
5518
5519 int _ViscousBuilder::invalidateBadSmooth( _SolidData&               data,
5520                                           SMESH_MesherHelper&       helper,
5521                                           vector< _LayerEdge* >&    badSmooEdges,
5522                                           vector< _EdgesOnShape* >& eosC1,
5523                                           const int                 infStep )
5524 {
5525   if ( badSmooEdges.empty() || infStep == 0 ) return 0;
5526
5527   dumpFunction(SMESH_Comment("invalidateBadSmooth")<<"_S"<<eosC1[0]->_shapeID<<"_InfStep"<<infStep);
5528
5529   enum {
5530     INVALIDATED   = _LayerEdge::UNUSED_FLAG,
5531     TO_INVALIDATE = _LayerEdge::UNUSED_FLAG * 2,
5532     ADDED         = _LayerEdge::UNUSED_FLAG * 4
5533   };
5534   data.UnmarkEdges( TO_INVALIDATE & INVALIDATED & ADDED );
5535
5536   double vol;
5537   bool haveInvalidated = true;
5538   while ( haveInvalidated )
5539   {
5540     haveInvalidated = false;
5541     for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5542     {
5543       _LayerEdge*   edge = badSmooEdges[i];
5544       _EdgesOnShape* eos = data.GetShapeEdges( edge );
5545       edge->Set( ADDED );
5546       bool invalidated = false;
5547       if ( edge->Is( TO_INVALIDATE ) && edge->NbSteps() > 1 )
5548       {
5549         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5550         edge->Block( data );
5551         edge->Set( INVALIDATED );
5552         edge->Unset( TO_INVALIDATE );
5553         invalidated = true;
5554         haveInvalidated = true;
5555       }
5556
5557       // look for _LayerEdge's of bad _simplices
5558       int nbBad = 0;
5559       SMESH_TNodeXYZ tgtXYZ  = edge->_nodes.back();
5560       gp_XYZ        prevXYZ1 = edge->PrevCheckPos( eos );
5561       //const gp_XYZ& prevXYZ2 = edge->PrevPos();
5562       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5563       {
5564         if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol ))/* &&
5565             ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5566           continue;
5567
5568         bool isBad = true;
5569         _LayerEdge* ee[2] = { 0,0 };
5570         for ( size_t iN = 0; iN < edge->_neibors.size() &&   !ee[1]  ; ++iN )
5571           if ( edge->_simplices[j].Includes( edge->_neibors[iN]->_nodes.back() ))
5572             ee[ ee[0] != 0 ] = edge->_neibors[iN];
5573
5574         int maxNbSteps = Max( ee[0]->NbSteps(), ee[1]->NbSteps() );
5575         while ( maxNbSteps > edge->NbSteps() && isBad )
5576         {
5577           --maxNbSteps;
5578           for ( int iE = 0; iE < 2; ++iE )
5579           {
5580             if ( ee[ iE ]->NbSteps() > maxNbSteps &&
5581                  ee[ iE ]->NbSteps() > 1 )
5582             {
5583               _EdgesOnShape* eos = data.GetShapeEdges( ee[ iE ] );
5584               ee[ iE ]->InvalidateStep( ee[ iE ]->NbSteps(), *eos, /*restoreLength=*/true );
5585               ee[ iE ]->Block( data );
5586               ee[ iE ]->Set( INVALIDATED );
5587               haveInvalidated = true;
5588             }
5589           }
5590           if (( edge->_simplices[j].IsForward( &prevXYZ1, &tgtXYZ, vol )) /*&&
5591               ( &prevXYZ1 == &prevXYZ2 || edge->_simplices[j].IsForward( &prevXYZ2, &tgtXYZ, vol ))*/)
5592             isBad = false;
5593         }
5594         nbBad += isBad;
5595         if ( !ee[0]->Is( ADDED )) badSmooEdges.push_back( ee[0] );
5596         if ( !ee[1]->Is( ADDED )) badSmooEdges.push_back( ee[1] );
5597         ee[0]->Set( ADDED );
5598         ee[1]->Set( ADDED );
5599         if ( isBad )
5600         {
5601           ee[0]->Set( TO_INVALIDATE );
5602           ee[1]->Set( TO_INVALIDATE );
5603         }
5604       }
5605
5606       if ( !invalidated &&  nbBad > 0  &&  edge->NbSteps() > 1 )
5607       {
5608         _EdgesOnShape* eos = data.GetShapeEdges( edge );
5609         edge->InvalidateStep( edge->NbSteps(), *eos, /*restoreLength=*/true );
5610         edge->Block( data );
5611         edge->Set( INVALIDATED );
5612         edge->Unset( TO_INVALIDATE );
5613         haveInvalidated = true;
5614       }
5615     } // loop on badSmooEdges
5616   } // while ( haveInvalidated )
5617
5618   // re-smooth on analytical EDGEs
5619   for ( size_t i = 0; i < badSmooEdges.size(); ++i )
5620   {
5621     _LayerEdge* edge = badSmooEdges[i];
5622     if ( !edge->Is( INVALIDATED )) continue;
5623
5624     _EdgesOnShape* eos = data.GetShapeEdges( edge );
5625     if ( eos->ShapeType() == TopAbs_VERTEX )
5626     {
5627       PShapeIteratorPtr eIt = helper.GetAncestors( eos->_shape, *_mesh, TopAbs_EDGE );
5628       while ( const TopoDS_Shape* e = eIt->next() )
5629         if ( _EdgesOnShape* eoe = data.GetShapeEdges( *e ))
5630           if ( eoe->_edgeSmoother && eoe->_edgeSmoother->isAnalytic() )
5631           {
5632             // TopoDS_Face F; Handle(ShapeAnalysis_Surface) surface;
5633             // if ( eoe->SWOLType() == TopAbs_FACE ) {
5634             //   F       = TopoDS::Face( eoe->_sWOL );
5635             //   surface = helper.GetSurface( F );
5636             // }
5637             // eoe->_edgeSmoother->Perform( data, surface, F, helper );
5638             eoe->_edgeSmoother->_anaCurve.Nullify();
5639           }
5640     }
5641   }
5642
5643
5644   // check result of invalidation
5645
5646   int nbBad = 0;
5647   for ( size_t iEOS = 0; iEOS < eosC1.size(); ++iEOS )
5648   {
5649     for ( size_t i = 0; i < eosC1[ iEOS ]->_edges.size(); ++i )
5650     {
5651       if ( !eosC1[ iEOS ]->_sWOL.IsNull() ) continue;
5652       _LayerEdge*      edge = eosC1[ iEOS ]->_edges[i];
5653       SMESH_TNodeXYZ tgtXYZ = edge->_nodes.back();
5654       gp_XYZ        prevXYZ = edge->PrevCheckPos( eosC1[ iEOS ]);
5655       for ( size_t j = 0; j < edge->_simplices.size(); ++j )
5656         if ( !edge->_simplices[j].IsForward( &prevXYZ, &tgtXYZ, vol ))
5657         {
5658           ++nbBad;
5659           debugMsg("Bad simplex remains ( " << edge->_nodes[0]->GetID()
5660                    << " "<< tgtXYZ._node->GetID()
5661                    << " "<< edge->_simplices[j]._nPrev->GetID()
5662                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
5663         }
5664     }
5665   }
5666   dumpFunctionEnd();
5667
5668   return nbBad;
5669 }
5670
5671 //================================================================================
5672 /*!
5673  * \brief Create an offset surface
5674  */
5675 //================================================================================
5676
5677 void _ViscousBuilder::makeOffsetSurface( _EdgesOnShape& eos, SMESH_MesherHelper& helper )
5678 {
5679   if ( eos._offsetSurf.IsNull() ||
5680        eos._edgeForOffset == 0 ||
5681        eos._edgeForOffset->Is( _LayerEdge::BLOCKED ))
5682     return;
5683
5684   Handle(ShapeAnalysis_Surface) baseSurface = helper.GetSurface( TopoDS::Face( eos._shape ));
5685
5686   // find offset
5687   gp_Pnt   tgtP = SMESH_TNodeXYZ( eos._edgeForOffset->_nodes.back() );
5688   /*gp_Pnt2d uv=*/baseSurface->ValueOfUV( tgtP, Precision::Confusion() );
5689   eos._offsetValue = baseSurface->Gap();
5690
5691   eos._offsetSurf.Nullify();
5692
5693   try
5694   {
5695     BRepOffsetAPI_MakeOffsetShape offsetMaker;
5696     offsetMaker.PerformByJoin( eos._shape, -eos._offsetValue, Precision::Confusion() );
5697     if ( !offsetMaker.IsDone() ) return;
5698
5699     TopExp_Explorer fExp( offsetMaker.Shape(), TopAbs_FACE );
5700     if ( !fExp.More() ) return;
5701
5702     TopoDS_Face F = TopoDS::Face( fExp.Current() );
5703     Handle(Geom_Surface) surf = BRep_Tool::Surface( F );
5704     if ( surf.IsNull() ) return;
5705
5706     eos._offsetSurf = new ShapeAnalysis_Surface( surf );
5707   }
5708   catch ( Standard_Failure& )
5709   {
5710   }
5711 }
5712
5713 //================================================================================
5714 /*!
5715  * \brief Put nodes of a curved FACE to its offset surface
5716  */
5717 //================================================================================
5718
5719 void _ViscousBuilder::putOnOffsetSurface( _EdgesOnShape&            eos,
5720                                           int                       infStep,
5721                                           vector< _EdgesOnShape* >& eosC1,
5722                                           int                       smooStep,
5723                                           int                       moveAll )
5724 {
5725   _EdgesOnShape * eof = & eos;
5726   if ( eos.ShapeType() != TopAbs_FACE ) // eos is a boundary of C1 FACE, look for the FACE eos
5727   {
5728     eof = 0;
5729     for ( size_t i = 0; i < eosC1.size() && !eof; ++i )
5730     {
5731       if ( eosC1[i]->_offsetSurf.IsNull() ||
5732            eosC1[i]->ShapeType() != TopAbs_FACE ||
5733            eosC1[i]->_edgeForOffset == 0 ||
5734            eosC1[i]->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5735         continue;
5736       if ( SMESH_MesherHelper::IsSubShape( eos._shape, eosC1[i]->_shape ))
5737         eof = eosC1[i];
5738     }
5739   }
5740   if ( !eof ||
5741        eof->_offsetSurf.IsNull() ||
5742        eof->ShapeType() != TopAbs_FACE ||
5743        eof->_edgeForOffset == 0 ||
5744        eof->_edgeForOffset->Is( _LayerEdge::BLOCKED ))
5745     return;
5746
5747   double preci = BRep_Tool::Tolerance( TopoDS::Face( eof->_shape )), vol;
5748   bool neighborHasRiskySWOL = false;
5749   for ( size_t i = 0; i < eos._edges.size(); ++i )
5750   {
5751     _LayerEdge* edge = eos._edges[i];
5752     edge->Unset( _LayerEdge::MARKED );
5753     if ( edge->Is( _LayerEdge::BLOCKED ) || !edge->_curvature )
5754       continue;
5755     if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5756     {
5757       if ( !edge->Is( _LayerEdge::UPD_NORMAL_CONV ))
5758         continue;
5759     }
5760     else if ( moveAll == _LayerEdge::RISKY_SWOL )
5761     {
5762       if ( !edge->Is( _LayerEdge::RISKY_SWOL ) ||
5763            edge->_cosin < 0 )
5764         continue;
5765     }
5766     else if ( !moveAll && !edge->Is( _LayerEdge::MOVED ))
5767       continue;
5768
5769     int nbBlockedAround = 0;
5770     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
5771     {
5772       nbBlockedAround += edge->_neibors[iN]->Is( _LayerEdge::BLOCKED );
5773       if ( edge->_neibors[iN]->Is( _LayerEdge::RISKY_SWOL ) &&
5774            edge->_neibors[iN]->_cosin > 0 )
5775         neighborHasRiskySWOL = true;
5776     }
5777     if ( nbBlockedAround > 1 )
5778       continue;
5779
5780     gp_Pnt tgtP = SMESH_TNodeXYZ( edge->_nodes.back() );
5781     gp_Pnt2d uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, tgtP, preci );
5782     if ( eof->_offsetSurf->Gap() > edge->_len ) continue; // NextValueOfUV() bug
5783     edge->_curvature->_uv = uv;
5784     if ( eof->_offsetSurf->Gap() < 10 * preci ) continue; // same pos
5785
5786     gp_XYZ  newP = eof->_offsetSurf->Value( uv ).XYZ();
5787     gp_XYZ prevP = edge->PrevCheckPos();
5788     bool      ok = true;
5789     if ( !moveAll )
5790       for ( size_t iS = 0; iS < edge->_simplices.size() && ok; ++iS )
5791       {
5792         ok = edge->_simplices[iS].IsForward( &prevP, &newP, vol );
5793       }
5794     if ( ok )
5795     {
5796       SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( edge->_nodes.back() );
5797       n->setXYZ( newP.X(), newP.Y(), newP.Z());
5798       edge->_pos.back() = newP;
5799
5800       edge->Set( _LayerEdge::MARKED );
5801       if ( moveAll == _LayerEdge::UPD_NORMAL_CONV )
5802       {
5803         edge->_normal = ( newP - prevP ).Normalized();
5804       }
5805       // if ( edge->_len < eof->_offsetValue )
5806       //   edge->_len = eof->_offsetValue;
5807
5808       if ( !eos._sWOL.IsNull() ) // RISKY_SWOL
5809       {
5810         double change = eof->_offsetSurf->Gap() / eof->_offsetValue;
5811         if (( newP - tgtP.XYZ() ) * edge->_normal < 0 )
5812           change = 1 - change;
5813         else
5814           change = 1 + change;
5815         gp_XYZ shitfVec    = tgtP.XYZ() - SMESH_NodeXYZ( edge->_nodes[0] );
5816         gp_XYZ newShiftVec = shitfVec * change;
5817         double shift       = edge->_normal * shitfVec;
5818         double newShift    = edge->_normal * newShiftVec;
5819         newP = tgtP.XYZ() + edge->_normal * ( newShift - shift );
5820
5821         uv = eof->_offsetSurf->NextValueOfUV( edge->_curvature->_uv, newP, preci );
5822         if ( eof->_offsetSurf->Gap() < edge->_len )
5823         {
5824           edge->_curvature->_uv = uv;
5825           newP = eof->_offsetSurf->Value( uv ).XYZ();
5826         }
5827         n->setXYZ( newP.X(), newP.Y(), newP.Z());
5828         if ( !edge->UpdatePositionOnSWOL( n, /*tol=*/10 * edge->_len / ( edge->NbSteps() + 1 ),
5829                                           eos, eos.GetData().GetHelper() ))
5830         {
5831           debugMsg("UpdatePositionOnSWOL fails in putOnOffsetSurface()" );
5832         }
5833       }
5834     }
5835   }
5836
5837
5838
5839 #ifdef _DEBUG_
5840   // dumpMove() for debug
5841   size_t i = 0;
5842   for ( ; i < eos._edges.size(); ++i )
5843     if ( eos._edges[i]->Is( _LayerEdge::MARKED ))
5844       break;
5845   if ( i < eos._edges.size() )
5846   {
5847     dumpFunction(SMESH_Comment("putOnOffsetSurface_") << eos.ShapeTypeLetter() << eos._shapeID
5848                  << "_InfStep" << infStep << "_" << Abs( smooStep ));
5849     for ( ; i < eos._edges.size(); ++i )
5850     {
5851       if ( eos._edges[i]->Is( _LayerEdge::MARKED )) {
5852         dumpMove( eos._edges[i]->_nodes.back() );
5853       }
5854     }
5855     dumpFunctionEnd();
5856   }
5857 #endif
5858
5859   _ConvexFace* cnvFace;
5860   if ( moveAll != _LayerEdge::UPD_NORMAL_CONV &&
5861        eos.ShapeType() == TopAbs_FACE &&
5862        (cnvFace = eos.GetData().GetConvexFace( eos._shapeID )) &&
5863        !cnvFace->_normalsFixedOnBorders )
5864   {
5865     // put on the surface nodes built on FACE boundaries
5866     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5867     while ( smIt->more() )
5868     {
5869       SMESH_subMesh*     sm = smIt->next();
5870       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5871       if ( !subEOS->_sWOL.IsNull() ) continue;
5872       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5873
5874       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::UPD_NORMAL_CONV );
5875     }
5876     cnvFace->_normalsFixedOnBorders = true;
5877   }
5878
5879
5880   // bos #20643
5881   // negative smooStep means "final step", where we don't treat RISKY_SWOL edges
5882   // as edges based on FACE are a bit late comparing with them
5883   if ( smooStep >= 0 &&
5884        neighborHasRiskySWOL &&
5885        moveAll != _LayerEdge::RISKY_SWOL &&
5886        eos.ShapeType() == TopAbs_FACE )
5887   {
5888     // put on the surface nodes built on FACE boundaries
5889     SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
5890     while ( smIt->more() )
5891     {
5892       SMESH_subMesh*     sm = smIt->next();
5893       _EdgesOnShape* subEOS = eos.GetData().GetShapeEdges( sm->GetId() );
5894       if ( subEOS->_sWOL.IsNull() ) continue;
5895       if ( std::find( eosC1.begin(), eosC1.end(), subEOS ) != eosC1.end() ) continue;
5896
5897       putOnOffsetSurface( *subEOS, infStep, eosC1, smooStep, _LayerEdge::RISKY_SWOL );
5898     }
5899   }
5900 }
5901
5902 //================================================================================
5903 /*!
5904  * \brief Return a curve of the EDGE to be used for smoothing and arrange
5905  *        _LayerEdge's to be in a consequent order
5906  */
5907 //================================================================================
5908
5909 Handle(Geom_Curve) _Smoother1D::CurveForSmooth( const TopoDS_Edge&  E,
5910                                                 _EdgesOnShape&      eos,
5911                                                 SMESH_MesherHelper& helper)
5912 {
5913   SMESHDS_SubMesh* smDS = eos._subMesh->GetSubMeshDS();
5914
5915   TopLoc_Location loc; double f,l;
5916
5917   Handle(Geom_Line)   line;
5918   Handle(Geom_Circle) circle;
5919   bool isLine, isCirc;
5920   if ( eos._sWOL.IsNull() ) /////////////////////////////////////////// 3D case
5921   {
5922     // check if the EDGE is a line
5923     Handle(Geom_Curve) curve = BRep_Tool::Curve( E, f, l);
5924     if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
5925       curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
5926
5927     line   = Handle(Geom_Line)::DownCast( curve );
5928     circle = Handle(Geom_Circle)::DownCast( curve );
5929     isLine = (!line.IsNull());
5930     isCirc = (!circle.IsNull());
5931
5932     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5933     {
5934       isLine = SMESH_Algo::IsStraight( E );
5935
5936       if ( isLine )
5937         line = new Geom_Line( gp::OX() ); // only type does matter
5938     }
5939     if ( !isLine && !isCirc && eos._edges.size() > 2) // Check if the EDGE is close to a circle
5940     {
5941       // TODO
5942     }
5943   }
5944   else //////////////////////////////////////////////////////////////////////// 2D case
5945   {
5946     if ( !eos._isRegularSWOL ) // 23190
5947       return NULL;
5948
5949     const TopoDS_Face& F = TopoDS::Face( eos._sWOL );
5950
5951     // check if the EDGE is a line
5952     Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l );
5953     if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
5954       curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
5955
5956     Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
5957     Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
5958     isLine = (!line2d.IsNull());
5959     isCirc = (!circle2d.IsNull());
5960
5961     if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
5962     {
5963       Bnd_B2d bndBox;
5964       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
5965       while ( nIt->more() )
5966         bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
5967       gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
5968
5969       const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
5970       for ( int i = 0; i < 2 && !isLine; ++i )
5971         isLine = ( size.Coord( i+1 ) <= lineTol );
5972     }
5973     if ( !isLine && !isCirc && eos._edges.size() > 2 ) // Check if the EDGE is close to a circle
5974     {
5975       // TODO
5976     }
5977     if ( isLine )
5978     {
5979       line = new Geom_Line( gp::OX() ); // only type does matter
5980     }
5981     else if ( isCirc )
5982     {
5983       gp_Pnt2d p = circle2d->Location();
5984       gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
5985       circle = new Geom_Circle( ax, 1.); // only center position does matter
5986     }
5987   }
5988
5989   if ( isLine )
5990     return line;
5991   if ( isCirc )
5992     return circle;
5993
5994   return Handle(Geom_Curve)();
5995 }
5996
5997 //================================================================================
5998 /*!
5999  * \brief Smooth edges on EDGE
6000  */
6001 //================================================================================
6002
6003 bool _Smoother1D::Perform(_SolidData&                    data,
6004                           Handle(ShapeAnalysis_Surface)& surface,
6005                           const TopoDS_Face&             F,
6006                           SMESH_MesherHelper&            helper )
6007 {
6008   if ( _leParams.empty() || ( !isAnalytic() && _offPoints.empty() ))
6009     prepare( data );
6010
6011   findEdgesToSmooth();
6012   if ( isAnalytic() )
6013     return smoothAnalyticEdge( data, surface, F, helper );
6014   else
6015     return smoothComplexEdge ( data, surface, F, helper );
6016 }
6017
6018 //================================================================================
6019 /*!
6020  * \brief Find edges to smooth
6021  */
6022 //================================================================================
6023
6024 void _Smoother1D::findEdgesToSmooth()
6025 {
6026   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6027   for ( int iEnd = 0; iEnd < 2; ++iEnd )
6028     if ( leOnV[iEnd]->Is( _LayerEdge::NORMAL_UPDATED ))
6029       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6030
6031   _eToSmooth[0].first = _eToSmooth[0].second = 0;
6032
6033   for ( size_t i = 0; i < _eos.size(); ++i )
6034   {
6035     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6036     {
6037       if ( needSmoothing( _leOnV[0]._cosin,
6038                           _eos[i]->_len * leOnV[0]->_lenFactor, _curveLen * _leParams[i] ) ||
6039            isToSmooth( i )
6040            )
6041         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6042       else
6043         break;
6044     }
6045     _eToSmooth[0].second = i+1;
6046   }
6047
6048   _eToSmooth[1].first = _eToSmooth[1].second = _eos.size();
6049
6050   for ( int i = _eos.size() - 1; i >= _eToSmooth[0].second; --i )
6051   {
6052     if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH ))
6053     {
6054       if ( needSmoothing( _leOnV[1]._cosin,
6055                           _eos[i]->_len * leOnV[1]->_lenFactor, _curveLen * ( 1.-_leParams[i] )) ||
6056            isToSmooth( i ))
6057         _eos[i]->Set( _LayerEdge::TO_SMOOTH );
6058       else
6059         break;
6060     }
6061     _eToSmooth[1].first = i;
6062   }
6063 }
6064
6065 //================================================================================
6066 /*!
6067  * \brief Check if iE-th _LayerEdge needs smoothing
6068  */
6069 //================================================================================
6070
6071 bool _Smoother1D::isToSmooth( int iE )
6072 {
6073   SMESH_NodeXYZ pi( _eos[iE]->_nodes[0] );
6074   SMESH_NodeXYZ p0( _eos[iE]->_2neibors->srcNode(0) );
6075   SMESH_NodeXYZ p1( _eos[iE]->_2neibors->srcNode(1) );
6076   gp_XYZ       seg0 = pi - p0;
6077   gp_XYZ       seg1 = p1 - pi;
6078   gp_XYZ    tangent =  seg0 + seg1;
6079   double tangentLen = tangent.Modulus();
6080   double  segMinLen = Min( seg0.Modulus(), seg1.Modulus() );
6081   if ( tangentLen < std::numeric_limits<double>::min() )
6082     return false;
6083   tangent /= tangentLen;
6084
6085   for ( size_t i = 0; i < _eos[iE]->_neibors.size(); ++i )
6086   {
6087     _LayerEdge* ne = _eos[iE]->_neibors[i];
6088     if ( !ne->Is( _LayerEdge::TO_SMOOTH ) ||
6089          ne->_nodes.size() < 2 ||
6090          ne->_nodes[0]->GetPosition()->GetDim() != 2 )
6091       continue;
6092     gp_XYZ edgeVec = SMESH_NodeXYZ( ne->_nodes.back() ) - SMESH_NodeXYZ( ne->_nodes[0] );
6093     double    proj = edgeVec * tangent;
6094     if ( needSmoothing( 1., proj, segMinLen ))
6095       return true;
6096   }
6097   return false;
6098 }
6099
6100 //================================================================================
6101 /*!
6102  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
6103  */
6104 //================================================================================
6105
6106 bool _Smoother1D::smoothAnalyticEdge( _SolidData&                    data,
6107                                       Handle(ShapeAnalysis_Surface)& surface,
6108                                       const TopoDS_Face&             F,
6109                                       SMESH_MesherHelper&            helper)
6110 {
6111   if ( !isAnalytic() ) return false;
6112
6113   size_t iFrom = 0, iTo = _eos._edges.size();
6114
6115   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Line )))
6116   {
6117     if ( F.IsNull() ) // 3D
6118     {
6119       SMESH_TNodeXYZ pSrc0( _eos._edges[iFrom]->_2neibors->srcNode(0) );
6120       SMESH_TNodeXYZ pSrc1( _eos._edges[iTo-1]->_2neibors->srcNode(1) );
6121       //const   gp_XYZ lineDir = pSrc1 - pSrc0;
6122       //_LayerEdge* vLE0 = getLEdgeOnV( 0 );
6123       //_LayerEdge* vLE1 = getLEdgeOnV( 1 );
6124       // bool shiftOnly = ( vLE0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6125       //                    vLE0->Is( _LayerEdge::BLOCKED ) ||
6126       //                    vLE1->Is( _LayerEdge::NORMAL_UPDATED ) ||
6127       //                    vLE1->Is( _LayerEdge::BLOCKED ));
6128       for ( int iEnd = 0; iEnd < 2; ++iEnd )
6129       {
6130         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6131         if ( iFrom >= iTo ) continue;
6132         SMESH_TNodeXYZ p0( _eos[iFrom]->_2neibors->tgtNode(0) );
6133         SMESH_TNodeXYZ p1( _eos[iTo-1]->_2neibors->tgtNode(1) );
6134         double param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6135         double param1 = _leParams[ iTo ];
6136         for ( size_t i = iFrom; i < iTo; ++i )
6137         {
6138           _LayerEdge*       edge = _eos[i];
6139           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge->_nodes.back() );
6140           double           param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6141           gp_XYZ          newPos = p0 * ( 1. - param ) + p1 * param;
6142
6143           // if ( shiftOnly || edge->Is( _LayerEdge::NORMAL_UPDATED ))
6144           // {
6145           //   gp_XYZ curPos = SMESH_TNodeXYZ ( tgtNode );
6146           //   double  shift = ( lineDir * ( newPos - pSrc0 ) -
6147           //                     lineDir * ( curPos - pSrc0 ));
6148           //   newPos = curPos + lineDir * shift / lineDir.SquareModulus();
6149           // }
6150           if ( edge->Is( _LayerEdge::BLOCKED ))
6151           {
6152             SMESH_TNodeXYZ pSrc( edge->_nodes[0] );
6153             double curThick = pSrc.SquareDistance( tgtNode );
6154             double newThink = ( pSrc - newPos ).SquareModulus();
6155             if ( newThink > curThick )
6156               continue;
6157           }
6158           edge->_pos.back() = newPos;
6159           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6160           dumpMove( tgtNode );
6161         }
6162       }
6163     }
6164     else // 2D
6165     {
6166       _LayerEdge* eV0 = getLEdgeOnV( 0 );
6167       _LayerEdge* eV1 = getLEdgeOnV( 1 );
6168       gp_XY      uvV0 = eV0->LastUV( F, *data.GetShapeEdges( eV0 ));
6169       gp_XY      uvV1 = eV1->LastUV( F, *data.GetShapeEdges( eV1 ));
6170       if ( eV0->_nodes.back() == eV1->_nodes.back() ) // closed edge
6171       {
6172         int iPeriodic = helper.GetPeriodicIndex();
6173         if ( iPeriodic == 1 || iPeriodic == 2 )
6174         {
6175           uvV1.SetCoord( iPeriodic, helper.GetOtherParam( uvV1.Coord( iPeriodic )));
6176           if ( uvV0.Coord( iPeriodic ) > uvV1.Coord( iPeriodic ))
6177             std::swap( uvV0, uvV1 );
6178         }
6179       }
6180       for ( int iEnd = 0; iEnd < 2; ++iEnd )
6181       {
6182         iFrom = _eToSmooth[ iEnd ].first, iTo = _eToSmooth[ iEnd ].second;
6183         if ( iFrom >= iTo ) continue;
6184         _LayerEdge* e0 = _eos[iFrom]->_2neibors->_edges[0];
6185         _LayerEdge* e1 = _eos[iTo-1]->_2neibors->_edges[1];
6186         gp_XY      uv0 = ( e0 == eV0 ) ? uvV0 : e0->LastUV( F, _eos );
6187         gp_XY      uv1 = ( e1 == eV1 ) ? uvV1 : e1->LastUV( F, _eos );
6188         double  param0 = ( iFrom == 0 ) ? 0. : _leParams[ iFrom-1 ];
6189         double  param1 = _leParams[ iTo ];
6190         gp_XY  rangeUV = uv1 - uv0;
6191         for ( size_t i = iFrom; i < iTo; ++i )
6192         {
6193           if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6194           double param = ( _leParams[i] - param0 ) / ( param1 - param0 );
6195           gp_XY newUV = uv0 + param * rangeUV;
6196
6197           gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6198           SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6199           tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6200           dumpMove( tgtNode );
6201
6202           if ( SMDS_FacePositionPtr pos = tgtNode->GetPosition() ) // NULL if F is noShrink
6203           {
6204             pos->SetUParameter( newUV.X() );
6205             pos->SetVParameter( newUV.Y() );
6206           }
6207
6208           gp_XYZ newUV0( newUV.X(), newUV.Y(), 0 );
6209
6210           if ( !_eos[i]->Is( _LayerEdge::SMOOTHED ))
6211           {
6212             _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6213             if ( _eos[i]->_pos.size() > 2 )
6214             {
6215               // modify previous positions to make _LayerEdge less sharply bent
6216               vector<gp_XYZ>& uvVec = _eos[i]->_pos;
6217               const gp_XYZ  uvShift = newUV0 - uvVec.back();
6218               const double     len2 = ( uvVec.back() - uvVec[ 0 ] ).SquareModulus();
6219               int iPrev = uvVec.size() - 2;
6220               while ( iPrev > 0 )
6221               {
6222                 double r = ( uvVec[ iPrev ] - uvVec[0] ).SquareModulus() / len2;
6223                 uvVec[ iPrev ] += uvShift * r;
6224                 --iPrev;
6225               }
6226             }
6227           }
6228           _eos[i]->_pos.back() = newUV0;
6229         }
6230       }
6231     }
6232     return true;
6233   }
6234
6235   if ( _anaCurve->IsKind( STANDARD_TYPE( Geom_Circle )))
6236   {
6237     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( _anaCurve );
6238     gp_Pnt center3D = circle->Location();
6239
6240     if ( F.IsNull() ) // 3D
6241     {
6242       if ( getLEdgeOnV( 0 )->_nodes.back() == getLEdgeOnV( 1 )->_nodes.back() )
6243         return true; // closed EDGE - nothing to do
6244
6245       // circle is a real curve of EDGE
6246       gp_Circ circ = circle->Circ();
6247
6248       // new center is shifted along its axis
6249       const gp_Dir& axis = circ.Axis().Direction();
6250       _LayerEdge*     e0 = getLEdgeOnV(0);
6251       _LayerEdge*     e1 = getLEdgeOnV(1);
6252       SMESH_TNodeXYZ  p0 = e0->_nodes.back();
6253       SMESH_TNodeXYZ  p1 = e1->_nodes.back();
6254       double      shift1 = axis.XYZ() * ( p0 - center3D.XYZ() );
6255       double      shift2 = axis.XYZ() * ( p1 - center3D.XYZ() );
6256       gp_Pnt   newCenter = center3D.XYZ() + axis.XYZ() * 0.5 * ( shift1 + shift2 );
6257
6258       double newRadius = 0.5 * ( newCenter.Distance( p0 ) + newCenter.Distance( p1 ));
6259
6260       gp_Ax2  newAxis( newCenter, axis, gp_Vec( newCenter, p0 ));
6261       gp_Circ newCirc( newAxis, newRadius );
6262       gp_Vec  vecC1  ( newCenter, p1 );
6263
6264       double uLast = newAxis.XDirection().AngleWithRef( vecC1, newAxis.Direction() ); // -PI - +PI
6265       if ( uLast < 0 )
6266         uLast += 2 * M_PI;
6267       
6268       for ( size_t i = 0; i < _eos.size(); ++i )
6269       {
6270         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6271         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6272         double u = uLast * _leParams[i];
6273         gp_Pnt p = ElCLib::Value( u, newCirc );
6274         _eos._edges[i]->_pos.back() = p.XYZ();
6275
6276         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6277         tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6278         dumpMove( tgtNode );
6279       }
6280       return true;
6281     }
6282     else // 2D
6283     {
6284       const gp_XY center( center3D.X(), center3D.Y() );
6285
6286       _LayerEdge* e0 = getLEdgeOnV(0);
6287       _LayerEdge* eM = _eos._edges[ 0 ];
6288       _LayerEdge* e1 = getLEdgeOnV(1);
6289       gp_XY      uv0 = e0->LastUV( F, *data.GetShapeEdges( e0 ) );
6290       gp_XY      uvM = eM->LastUV( F, *data.GetShapeEdges( eM ) );
6291       gp_XY      uv1 = e1->LastUV( F, *data.GetShapeEdges( e1 ) );
6292       gp_Vec2d vec0( center, uv0 );
6293       gp_Vec2d vecM( center, uvM );
6294       gp_Vec2d vec1( center, uv1 );
6295       double uLast = vec0.Angle( vec1 ); // -PI - +PI
6296       double uMidl = vec0.Angle( vecM );
6297       if ( uLast * uMidl <= 0. )
6298         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
6299       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
6300
6301       gp_Ax2d   axis( center, vec0 );
6302       gp_Circ2d circ( axis, radius );
6303       for ( size_t i = 0; i < _eos.size(); ++i )
6304       {
6305         if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6306         //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6307         double    newU = uLast * _leParams[i];
6308         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
6309         _eos._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
6310
6311         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
6312         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos._edges[i]->_nodes.back() );
6313         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
6314         dumpMove( tgtNode );
6315
6316         if ( SMDS_FacePositionPtr pos = tgtNode->GetPosition() ) // NULL if F is noShrink
6317         {
6318           pos->SetUParameter( newUV.X() );
6319           pos->SetVParameter( newUV.Y() );
6320         }
6321         _eos[i]->Set( _LayerEdge::SMOOTHED ); // to check in refine() (IPAL54237)
6322       }
6323     }
6324     return true;
6325   }
6326
6327   return false;
6328 }
6329
6330 //================================================================================
6331 /*!
6332  * \brief smooth _LayerEdge's on a an EDGE
6333  */
6334 //================================================================================
6335
6336 bool _Smoother1D::smoothComplexEdge( _SolidData&                    /*data*/,
6337                                      Handle(ShapeAnalysis_Surface)& surface,
6338                                      const TopoDS_Face&             F,
6339                                      SMESH_MesherHelper&            /*helper*/)
6340 {
6341   if ( _offPoints.empty() )
6342     return false;
6343
6344   // ----------------------------------------------
6345   // move _offPoints along normals of _LayerEdge's
6346   // ----------------------------------------------
6347
6348   _LayerEdge* e[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6349   if ( e[0]->Is( _LayerEdge::NORMAL_UPDATED ))
6350     _leOnV[0]._normal = getNormalNormal( e[0]->_normal, _edgeDir[0] );
6351   if ( e[1]->Is( _LayerEdge::NORMAL_UPDATED )) 
6352     _leOnV[1]._normal = getNormalNormal( e[1]->_normal, _edgeDir[1] );
6353   _leOnV[0]._len = e[0]->_len;
6354   _leOnV[1]._len = e[1]->_len;
6355   for ( size_t i = 0; i < _offPoints.size(); i++ )
6356   {
6357     _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6358     _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6359     const double w0 = _offPoints[i]._2edges._wgt[0];
6360     const double w1 = _offPoints[i]._2edges._wgt[1];
6361     gp_XYZ  avgNorm = ( e0->_normal    * w0 + e1->_normal    * w1 ).Normalized();
6362     double  avgLen  = ( e0->_len       * w0 + e1->_len       * w1 );
6363     double  avgFact = ( e0->_lenFactor * w0 + e1->_lenFactor * w1 );
6364     if ( e0->Is( _LayerEdge::NORMAL_UPDATED ) ||
6365          e1->Is( _LayerEdge::NORMAL_UPDATED ))
6366       avgNorm = getNormalNormal( avgNorm, _offPoints[i]._edgeDir );
6367
6368     _offPoints[i]._xyz += avgNorm * ( avgLen - _offPoints[i]._len ) * avgFact;
6369     _offPoints[i]._len  = avgLen;
6370   }
6371
6372   double fTol = 0;
6373   if ( !surface.IsNull() ) // project _offPoints to the FACE
6374   {
6375     fTol = 100 * BRep_Tool::Tolerance( F );
6376     //const double segLen = _offPoints[0].Distance( _offPoints[1] );
6377
6378     gp_Pnt2d uv = surface->ValueOfUV( _offPoints[0]._xyz, fTol );
6379     //if ( surface->Gap() < 0.5 * segLen )
6380       _offPoints[0]._xyz = surface->Value( uv ).XYZ();
6381
6382     for ( size_t i = 1; i < _offPoints.size(); ++i )
6383     {
6384       uv = surface->NextValueOfUV( uv, _offPoints[i]._xyz, fTol );
6385       //if ( surface->Gap() < 0.5 * segLen )
6386         _offPoints[i]._xyz = surface->Value( uv ).XYZ();
6387     }
6388   }
6389
6390   // -----------------------------------------------------------------
6391   // project tgt nodes of extreme _LayerEdge's to the offset segments
6392   // -----------------------------------------------------------------
6393
6394   const int updatedOrBlocked = _LayerEdge::NORMAL_UPDATED | _LayerEdge::BLOCKED;
6395   if ( e[0]->Is( updatedOrBlocked )) _iSeg[0] = 0;
6396   if ( e[1]->Is( updatedOrBlocked )) _iSeg[1] = _offPoints.size()-2;
6397
6398   gp_Pnt pExtreme[2], pProj[2];
6399   bool isProjected[2];
6400   for ( int is2nd = 0; is2nd < 2; ++is2nd )
6401   {
6402     pExtreme[ is2nd ] = SMESH_TNodeXYZ( e[is2nd]->_nodes.back() );
6403     int  i = _iSeg[ is2nd ];
6404     int di = is2nd ? -1 : +1;
6405     bool & projected = isProjected[ is2nd ];
6406     projected = false;
6407     double uOnSeg, distMin = Precision::Infinite(), dist, distPrev = 0;
6408     int nbWorse = 0;
6409     do {
6410       gp_Vec v0p( _offPoints[i]._xyz, pExtreme[ is2nd ]    );
6411       gp_Vec v01( _offPoints[i]._xyz, _offPoints[i+1]._xyz );
6412       uOnSeg     = ( v0p * v01 ) / v01.SquareMagnitude();  // param [0,1] along v01
6413       projected  = ( Abs( uOnSeg - 0.5 ) <= 0.5 );
6414       dist       =  pExtreme[ is2nd ].SquareDistance( _offPoints[ i + ( uOnSeg > 0.5 )]._xyz );
6415       if ( dist < distMin || projected )
6416       {
6417         _iSeg[ is2nd ] = i;
6418         pProj[ is2nd ] = _offPoints[i]._xyz + ( v01 * uOnSeg ).XYZ();
6419         distMin = dist;
6420       }
6421       else if ( dist > distPrev )
6422       {
6423         if ( ++nbWorse > 3 ) // avoid projection to the middle of a closed EDGE
6424           break;
6425       }
6426       distPrev = dist;
6427       i += di;
6428     }
6429     while ( !projected &&
6430             i >= 0 && i+1 < (int)_offPoints.size() );
6431
6432     if ( !projected )
6433     {
6434       if (( is2nd && _iSeg[1] != _offPoints.size()-2 ) || ( !is2nd && _iSeg[0] != 0 ))
6435       {
6436         _iSeg[0] = 0;
6437         _iSeg[1] = _offPoints.size()-2;
6438         debugMsg( "smoothComplexEdge() failed to project nodes of extreme _LayerEdge's" );
6439         return false;
6440       }
6441     }
6442   }
6443   if ( _iSeg[0] > _iSeg[1] )
6444   {
6445     debugMsg( "smoothComplexEdge() incorrectly projected nodes of extreme _LayerEdge's" );
6446     return false;
6447   }
6448
6449   // adjust length of extreme LE (test viscous_layers_01/B7)
6450   gp_Vec vDiv0( pExtreme[0], pProj[0] );
6451   gp_Vec vDiv1( pExtreme[1], pProj[1] );
6452   double d0 = vDiv0.Magnitude();
6453   double d1 = isProjected[1] ? vDiv1.Magnitude() : 0;
6454   if ( e[0]->Is( _LayerEdge::BLOCKED )) {
6455     if ( e[0]->_normal * vDiv0.XYZ() < 0 ) e[0]->_len += d0;
6456     else                                   e[0]->_len -= d0;
6457   }
6458   if ( e[1]->Is( _LayerEdge::BLOCKED )) {
6459     if ( e[1]->_normal * vDiv1.XYZ() < 0 ) e[1]->_len += d1;
6460     else                                   e[1]->_len -= d1;
6461   }
6462
6463   // ---------------------------------------------------------------------------------
6464   // compute normalized length of the offset segments located between the projections
6465   // ---------------------------------------------------------------------------------
6466
6467   // temporary replace extreme _offPoints by pExtreme
6468   gp_XYZ opXYZ[2] = { _offPoints[ _iSeg[0]   ]._xyz,
6469                       _offPoints[ _iSeg[1]+1 ]._xyz };
6470   _offPoints[ _iSeg[0]   ]._xyz = pExtreme[0].XYZ();
6471   _offPoints[ _iSeg[1]+ 1]._xyz = pExtreme[1].XYZ();
6472
6473   size_t iSeg = 0, nbSeg = _iSeg[1] - _iSeg[0] + 1;
6474   vector< double > len( nbSeg + 1 );
6475   len[ iSeg++ ] = 0;
6476   len[ iSeg++ ] = pProj[ 0 ].Distance( _offPoints[ _iSeg[0]+1 ]._xyz );
6477   for ( size_t i = _iSeg[0]+1; i <= _iSeg[1]; ++i, ++iSeg )
6478   {
6479     len[ iSeg ] = len[ iSeg-1 ] + _offPoints[i].Distance( _offPoints[i+1] );
6480   }
6481   // if ( isProjected[ 1 ])
6482   //   len[ nbSeg ] -= pProj[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6483   // else
6484   //   len[ nbSeg ] += pExtreme[ 1 ].Distance( _offPoints[ _iSeg[1]+1 ]._xyz );
6485
6486   double fullLen = len.back() - d0 - d1;
6487   for ( iSeg = 0; iSeg < len.size(); ++iSeg )
6488     len[iSeg] = ( len[iSeg] - d0 ) / fullLen;
6489
6490   // -------------------------------------------------------------
6491   // distribute tgt nodes of _LayerEdge's between the projections
6492   // -------------------------------------------------------------
6493
6494   iSeg = 0;
6495   for ( size_t i = 0; i < _eos.size(); ++i )
6496   {
6497     if ( _eos[i]->Is( _LayerEdge::BLOCKED )) continue;
6498     //if ( !_eos[i]->Is( _LayerEdge::TO_SMOOTH )) continue;
6499     while ( iSeg+2 < len.size() && _leParams[i] > len[ iSeg+1 ] )
6500       iSeg++;
6501     double r = ( _leParams[i] - len[ iSeg ]) / ( len[ iSeg+1 ] - len[ iSeg ]);
6502     gp_XYZ p = ( _offPoints[ iSeg + _iSeg[0]     ]._xyz * ( 1 - r ) +
6503                  _offPoints[ iSeg + _iSeg[0] + 1 ]._xyz * r );
6504
6505     if ( surface.IsNull() )
6506     {
6507       _eos[i]->_pos.back() = p;
6508     }
6509     else // project a new node position to a FACE
6510     {
6511       gp_Pnt2d uv ( _eos[i]->_pos.back().X(), _eos[i]->_pos.back().Y() );
6512       gp_Pnt2d uv2( surface->NextValueOfUV( uv, p, fTol ));
6513
6514       p = surface->Value( uv2 ).XYZ();
6515       _eos[i]->_pos.back().SetCoord( uv2.X(), uv2.Y(), 0 );
6516     }
6517     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _eos[i]->_nodes.back() );
6518     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6519     dumpMove( tgtNode );
6520   }
6521
6522   _offPoints[ _iSeg[0]   ]._xyz = opXYZ[0];
6523   _offPoints[ _iSeg[1]+1 ]._xyz = opXYZ[1];
6524
6525   return true;
6526 }
6527
6528 //================================================================================
6529 /*!
6530  * \brief Prepare for smoothing
6531  */
6532 //================================================================================
6533
6534 void _Smoother1D::prepare(_SolidData& data)
6535 {
6536   const TopoDS_Edge& E = TopoDS::Edge( _eos._shape );
6537   _curveLen = SMESH_Algo::EdgeLength( E );
6538
6539   // sort _LayerEdge's by position on the EDGE
6540   data.SortOnEdge( E, _eos._edges );
6541
6542   // compute normalized param of _eos._edges on EDGE
6543   _leParams.resize( _eos._edges.size() + 1 );
6544   {
6545     double curLen;
6546     gp_Pnt pPrev = SMESH_TNodeXYZ( getLEdgeOnV( 0 )->_nodes[0] );
6547     _leParams[0] = 0;
6548     for ( size_t i = 0; i < _eos._edges.size(); ++i )
6549     {
6550       gp_Pnt p       = SMESH_TNodeXYZ( _eos._edges[i]->_nodes[0] );
6551       curLen         = p.Distance( pPrev );
6552       _leParams[i+1] = _leParams[i] + curLen;
6553       pPrev          = p;
6554     }
6555     double fullLen = _leParams.back() + pPrev.Distance( SMESH_TNodeXYZ( getLEdgeOnV(1)->_nodes[0]));
6556     for ( size_t i = 0; i < _leParams.size()-1; ++i )
6557       _leParams[i] = _leParams[i+1] / fullLen;
6558     _leParams.back() = 1.;
6559   }
6560
6561   _LayerEdge* leOnV[2] = { getLEdgeOnV(0), getLEdgeOnV(1) };
6562
6563   // get cosin to use in findEdgesToSmooth()
6564   _edgeDir[0] = getEdgeDir( E, leOnV[0]->_nodes[0], data.GetHelper() );
6565   _edgeDir[1] = getEdgeDir( E, leOnV[1]->_nodes[0], data.GetHelper() );
6566   _leOnV[0]._cosin = Abs( leOnV[0]->_cosin );
6567   _leOnV[1]._cosin = Abs( leOnV[1]->_cosin );
6568   if ( _eos._sWOL.IsNull() ) // 3D
6569     for ( int iEnd = 0; iEnd < 2; ++iEnd )
6570       _leOnV[iEnd]._cosin = Abs( _edgeDir[iEnd].Normalized() * leOnV[iEnd]->_normal );
6571
6572   if ( isAnalytic() )
6573     return;
6574
6575   // divide E to have offset segments with low deflection
6576   BRepAdaptor_Curve c3dAdaptor( E );
6577   const double curDeflect = 0.1; //0.01; // Curvature deflection == |p1p2|*sin(p1p2,p1pM)
6578   const double angDeflect = 0.1; //0.09; // Angular deflection == sin(p1pM,pMp2)
6579   GCPnts_TangentialDeflection discret(c3dAdaptor, angDeflect, curDeflect);
6580   if ( discret.NbPoints() <= 2 )
6581   {
6582     _anaCurve = new Geom_Line( gp::OX() ); // only type does matter
6583     return;
6584   }
6585
6586   const double u0 = c3dAdaptor.FirstParameter();
6587   gp_Pnt p; gp_Vec tangent;
6588   if ( discret.NbPoints() >= (int) _eos.size() + 2 )
6589   {
6590     _offPoints.resize( discret.NbPoints() );
6591     for ( size_t i = 0; i < _offPoints.size(); i++ )
6592     {
6593       double u = discret.Parameter( i+1 );
6594       c3dAdaptor.D1( u, p, tangent );
6595       _offPoints[i]._xyz     = p.XYZ();
6596       _offPoints[i]._edgeDir = tangent.XYZ();
6597       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6598     }
6599   }
6600   else
6601   {
6602     std::vector< double > params( _eos.size() + 2 );
6603
6604     params[0]     = data.GetHelper().GetNodeU( E, leOnV[0]->_nodes[0] );
6605     params.back() = data.GetHelper().GetNodeU( E, leOnV[1]->_nodes[0] );
6606     for ( size_t i = 0; i < _eos.size(); i++ )
6607       params[i+1] = data.GetHelper().GetNodeU( E, _eos[i]->_nodes[0] );
6608
6609     if ( params[1] > params[ _eos.size() ] )
6610       std::reverse( params.begin() + 1, params.end() - 1 );
6611
6612     _offPoints.resize( _eos.size() + 2 );
6613     for ( size_t i = 0; i < _offPoints.size(); i++ )
6614     {
6615       const double u = params[i];
6616       c3dAdaptor.D1( u, p, tangent );
6617       _offPoints[i]._xyz     = p.XYZ();
6618       _offPoints[i]._edgeDir = tangent.XYZ();
6619       _offPoints[i]._param = GCPnts_AbscissaPoint::Length( c3dAdaptor, u0, u ) / _curveLen;
6620     }
6621   }
6622
6623   // set _2edges
6624   _offPoints    [0]._2edges.set( &_leOnV[0], &_leOnV[0], 0.5, 0.5 );
6625   _offPoints.back()._2edges.set( &_leOnV[1], &_leOnV[1], 0.5, 0.5 );
6626   _2NearEdges tmp2edges;
6627   tmp2edges._edges[1] = _eos._edges[0];
6628   _leOnV[0]._2neibors = & tmp2edges;
6629   _leOnV[0]._nodes    = leOnV[0]->_nodes;
6630   _leOnV[1]._nodes    = leOnV[1]->_nodes;
6631   _LayerEdge* eNext, *ePrev = & _leOnV[0];
6632   for ( size_t iLE = 0, i = 1; i < _offPoints.size()-1; i++ )
6633   {
6634     // find _LayerEdge's located before and after an offset point
6635     // (_eos._edges[ iLE ] is next after ePrev)
6636     while ( iLE < _eos._edges.size() && _offPoints[i]._param > _leParams[ iLE ] )
6637       ePrev = _eos._edges[ iLE++ ];
6638     eNext = ePrev->_2neibors->_edges[1];
6639
6640     gp_Pnt p0 = SMESH_TNodeXYZ( ePrev->_nodes[0] );
6641     gp_Pnt p1 = SMESH_TNodeXYZ( eNext->_nodes[0] );
6642     double  r = p0.Distance( _offPoints[i]._xyz ) / p0.Distance( p1 );
6643     _offPoints[i]._2edges.set( ePrev, eNext, 1-r, r );
6644   }
6645
6646   // replace _LayerEdge's on VERTEX by _leOnV in _offPoints._2edges
6647   for ( size_t i = 0; i < _offPoints.size(); i++ )
6648     if ( _offPoints[i]._2edges._edges[0] == leOnV[0] )
6649       _offPoints[i]._2edges._edges[0] = & _leOnV[0];
6650     else break;
6651   for ( size_t i = _offPoints.size()-1; i > 0; i-- )
6652     if ( _offPoints[i]._2edges._edges[1] == leOnV[1] )
6653       _offPoints[i]._2edges._edges[1] = & _leOnV[1];
6654     else break;
6655
6656   // set _normal of _leOnV[0] and _leOnV[1] to be normal to the EDGE
6657
6658   int iLBO = _offPoints.size() - 2; // last but one
6659
6660   if ( leOnV[ 0 ]->Is( _LayerEdge::MULTI_NORMAL ))
6661     _leOnV[ 0 ]._normal = getNormalNormal( _eos._edges[1]->_normal, _edgeDir[0] );
6662   else
6663     _leOnV[ 0 ]._normal = getNormalNormal( leOnV[0]->_normal,       _edgeDir[0] );
6664   if ( leOnV[ 1 ]->Is( _LayerEdge::MULTI_NORMAL ))
6665     _leOnV[ 1 ]._normal = getNormalNormal( _eos._edges.back()->_normal, _edgeDir[1] );
6666   else
6667     _leOnV[ 1 ]._normal = getNormalNormal( leOnV[1]->_normal,           _edgeDir[1] );
6668   _leOnV[ 0 ]._len = 0;
6669   _leOnV[ 1 ]._len = 0;
6670   _leOnV[ 0 ]._lenFactor = _offPoints[1   ]._2edges._edges[1]->_lenFactor;
6671   _leOnV[ 1 ]._lenFactor = _offPoints[iLBO]._2edges._edges[0]->_lenFactor;
6672
6673   _iSeg[0] = 0;
6674   _iSeg[1] = _offPoints.size()-2;
6675
6676   // initialize OffPnt::_len
6677   for ( size_t i = 0; i < _offPoints.size(); ++i )
6678     _offPoints[i]._len = 0;
6679
6680   if ( _eos._edges[0]->NbSteps() > 1 ) // already inflated several times, init _xyz
6681   {
6682     _leOnV[0]._len = leOnV[0]->_len;
6683     _leOnV[1]._len = leOnV[1]->_len;
6684     for ( size_t i = 0; i < _offPoints.size(); i++ )
6685     {
6686       _LayerEdge*  e0 = _offPoints[i]._2edges._edges[0];
6687       _LayerEdge*  e1 = _offPoints[i]._2edges._edges[1];
6688       const double w0 = _offPoints[i]._2edges._wgt[0];
6689       const double w1 = _offPoints[i]._2edges._wgt[1];
6690       double  avgLen  = ( e0->_len * w0 + e1->_len * w1 );
6691       gp_XYZ  avgXYZ  = ( SMESH_TNodeXYZ( e0->_nodes.back() ) * w0 +
6692                           SMESH_TNodeXYZ( e1->_nodes.back() ) * w1 );
6693       _offPoints[i]._xyz = avgXYZ;
6694       _offPoints[i]._len = avgLen;
6695     }
6696   }
6697 }
6698
6699 //================================================================================
6700 /*!
6701  * \brief return _normal of _leOnV[is2nd] normal to the EDGE
6702  */
6703 //================================================================================
6704
6705 gp_XYZ _Smoother1D::getNormalNormal( const gp_XYZ & normal,
6706                                      const gp_XYZ&  edgeDir)
6707 {
6708   gp_XYZ cross = normal ^ edgeDir;
6709   gp_XYZ  norm = edgeDir ^ cross;
6710   double  size = norm.Modulus();
6711
6712   // if ( size == 0 ) // MULTI_NORMAL _LayerEdge
6713   //   return gp_XYZ( 1e-100, 1e-100, 1e-100 );
6714
6715   if ( size < 1e-5 ) // normal || edgeDir (almost) at inflation along EDGE (bos #20643)
6716   {
6717     const _LayerEdge* le = _eos._edges[ _eos._edges.size() / 2 ];
6718     const gp_XYZ& leNorm = le->_normal;
6719
6720     cross = leNorm ^ edgeDir;
6721     norm = edgeDir ^ cross;
6722     size = norm.Modulus();
6723   }
6724
6725   return norm / size;
6726 }
6727
6728 //================================================================================
6729 /*!
6730  * \brief Writes a script creating a mesh composed of _offPoints
6731  */
6732 //================================================================================
6733
6734 void _Smoother1D::offPointsToPython() const
6735 {
6736   const char* fname = "/tmp/offPoints.py";
6737   cout << "exec(open('"<<fname<<"','rb').read() )"<<endl;
6738   ofstream py(fname);
6739   py << "import SMESH" << endl
6740      << "from salome.smesh import smeshBuilder" << endl
6741      << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
6742      << "mesh   = smesh.Mesh( 'offPoints' )"<<endl;
6743   for ( size_t i = 0; i < _offPoints.size(); i++ )
6744   {
6745     py << "mesh.AddNode( "
6746        << _offPoints[i]._xyz.X() << ", "
6747        << _offPoints[i]._xyz.Y() << ", "
6748        << _offPoints[i]._xyz.Z() << " )" << endl;
6749   }
6750 }
6751
6752 //================================================================================
6753 /*!
6754  * \brief Sort _LayerEdge's by a parameter on a given EDGE
6755  */
6756 //================================================================================
6757
6758 void _SolidData::SortOnEdge( const TopoDS_Edge&     E,
6759                              vector< _LayerEdge* >& edges)
6760 {
6761   map< double, _LayerEdge* > u2edge;
6762   for ( size_t i = 0; i < edges.size(); ++i )
6763     u2edge.insert( u2edge.end(),
6764                    make_pair( _helper->GetNodeU( E, edges[i]->_nodes[0] ), edges[i] ));
6765
6766   ASSERT( u2edge.size() == edges.size() );
6767   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
6768   for ( size_t i = 0; i < edges.size(); ++i, ++u2e )
6769     edges[i] = u2e->second;
6770
6771   Sort2NeiborsOnEdge( edges );
6772 }
6773
6774 //================================================================================
6775 /*!
6776  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
6777  */
6778 //================================================================================
6779
6780 void _SolidData::Sort2NeiborsOnEdge( vector< _LayerEdge* >& edges )
6781 {
6782   if ( edges.size() < 2 || !edges[0]->_2neibors ) return;
6783
6784   for ( size_t i = 0; i < edges.size()-1; ++i )
6785     if ( edges[i]->_2neibors->tgtNode(1) != edges[i+1]->_nodes.back() )
6786       edges[i]->_2neibors->reverse();
6787
6788   const size_t iLast = edges.size() - 1;
6789   if ( edges.size() > 1 &&
6790        edges[iLast]->_2neibors->tgtNode(0) != edges[iLast-1]->_nodes.back() )
6791     edges[iLast]->_2neibors->reverse();
6792 }
6793
6794 //================================================================================
6795 /*!
6796  * \brief Return _EdgesOnShape* corresponding to the shape
6797  */
6798 //================================================================================
6799
6800 _EdgesOnShape* _SolidData::GetShapeEdges(const TGeomID shapeID )
6801 {
6802   if ( shapeID < (int)_edgesOnShape.size() &&
6803        _edgesOnShape[ shapeID ]._shapeID == shapeID )
6804     return _edgesOnShape[ shapeID ]._subMesh ? & _edgesOnShape[ shapeID ] : 0;
6805
6806   for ( size_t i = 0; i < _edgesOnShape.size(); ++i )
6807     if ( _edgesOnShape[i]._shapeID == shapeID )
6808       return _edgesOnShape[i]._subMesh ? & _edgesOnShape[i] : 0;
6809
6810   return 0;
6811 }
6812
6813 //================================================================================
6814 /*!
6815  * \brief Return _EdgesOnShape* corresponding to the shape
6816  */
6817 //================================================================================
6818
6819 _EdgesOnShape* _SolidData::GetShapeEdges(const TopoDS_Shape& shape )
6820 {
6821   SMESHDS_Mesh* meshDS = _proxyMesh->GetMesh()->GetMeshDS();
6822   return GetShapeEdges( meshDS->ShapeToIndex( shape ));
6823 }
6824
6825 //================================================================================
6826 /*!
6827  * \brief Prepare data of the _LayerEdge for smoothing on FACE
6828  */
6829 //================================================================================
6830
6831 void _SolidData::PrepareEdgesToSmoothOnFace( _EdgesOnShape* eos, bool substituteSrcNodes )
6832 {
6833   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
6834
6835   set< TGeomID > vertices;
6836   TopoDS_Face F;
6837   if ( eos->ShapeType() == TopAbs_FACE )
6838   {
6839     // check FACE concavity and get concave VERTEXes
6840     F = TopoDS::Face( eos->_shape );
6841     if ( isConcave( F, helper, &vertices ))
6842       _concaveFaces.insert( eos->_shapeID );
6843
6844     // set eos._eosConcaVer
6845     eos->_eosConcaVer.clear();
6846     eos->_eosConcaVer.reserve( vertices.size() );
6847     for ( set< TGeomID >::iterator v = vertices.begin(); v != vertices.end(); ++v )
6848     {
6849       _EdgesOnShape* eov = GetShapeEdges( *v );
6850       if ( eov && eov->_edges.size() == 1 )
6851       {
6852         eos->_eosConcaVer.push_back( eov );
6853         for ( size_t i = 0; i < eov->_edges[0]->_neibors.size(); ++i )
6854           eov->_edges[0]->_neibors[i]->Set( _LayerEdge::DIFFICULT );
6855       }
6856     }
6857
6858     // SetSmooLen() to _LayerEdge's on FACE
6859     // for ( size_t i = 0; i < eos->_edges.size(); ++i )
6860     // {
6861     //   eos->_edges[i]->SetSmooLen( Precision::Infinite() );
6862     // }
6863     // SMESH_subMeshIteratorPtr smIt = eos->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
6864     // while ( smIt->more() ) // loop on sub-shapes of the FACE
6865     // {
6866     //   _EdgesOnShape* eoe = GetShapeEdges( smIt->next()->GetId() );
6867     //   if ( !eoe ) continue;
6868
6869     //   vector<_LayerEdge*>& eE = eoe->_edges;
6870     //   for ( size_t iE = 0; iE < eE.size(); ++iE ) // loop on _LayerEdge's on EDGE or VERTEX
6871     //   {
6872     //     if ( eE[iE]->_cosin <= theMinSmoothCosin )
6873     //       continue;
6874
6875     //     SMDS_ElemIteratorPtr segIt = eE[iE]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
6876     //     while ( segIt->more() )
6877     //     {
6878     //       const SMDS_MeshElement* seg = segIt->next();
6879     //       if ( !eos->_subMesh->DependsOn( seg->getshapeId() ))
6880     //         continue;
6881     //       if ( seg->GetNode(0) != eE[iE]->_nodes[0] )
6882     //         continue; // not to check a seg twice
6883     //       for ( size_t iN = 0; iN < eE[iE]->_neibors.size(); ++iN )
6884     //       {
6885     //         _LayerEdge* eN = eE[iE]->_neibors[iN];
6886     //         if ( eN->_nodes[0]->getshapeId() != eos->_shapeID )
6887     //           continue;
6888     //         double dist    = SMESH_MeshAlgos::GetDistance( seg, SMESH_TNodeXYZ( eN->_nodes[0] ));
6889     //         double smooLen = getSmoothingThickness( eE[iE]->_cosin, dist );
6890     //         eN->SetSmooLen( Min( smooLen, eN->GetSmooLen() ));
6891     //         eN->Set( _LayerEdge::NEAR_BOUNDARY );
6892     //       }
6893     //     }
6894     //   }
6895     // }
6896   } // if ( eos->ShapeType() == TopAbs_FACE )
6897
6898   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6899   {
6900     eos->_edges[i]->_smooFunction = 0;
6901     eos->_edges[i]->Set( _LayerEdge::TO_SMOOTH );
6902   }
6903   bool isCurved = false;
6904   for ( size_t i = 0; i < eos->_edges.size(); ++i )
6905   {
6906     _LayerEdge* edge = eos->_edges[i];
6907
6908     // get simplices sorted
6909     _Simplex::SortSimplices( edge->_simplices );
6910
6911     // smoothing function
6912     edge->ChooseSmooFunction( vertices, _n2eMap );
6913
6914     // set _curvature
6915     double avgNormProj = 0, avgLen = 0;
6916     for ( size_t iS = 0; iS < edge->_simplices.size(); ++iS )
6917     {
6918       _Simplex& s = edge->_simplices[iS];
6919
6920       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
6921       avgNormProj += edge->_normal * vec;
6922       avgLen      += vec.Modulus();
6923       if ( substituteSrcNodes )
6924       {
6925         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
6926         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
6927       }
6928     }
6929     avgNormProj /= edge->_simplices.size();
6930     avgLen      /= edge->_simplices.size();
6931     if (( edge->_curvature = _Curvature::New( avgNormProj, avgLen )))
6932     {
6933       edge->Set( _LayerEdge::SMOOTHED_C1 );
6934       isCurved = true;
6935       SMDS_FacePositionPtr fPos = edge->_nodes[0]->GetPosition();
6936       if ( !fPos )
6937         for ( size_t iS = 0; iS < edge->_simplices.size()  &&  !fPos; ++iS )
6938           fPos = edge->_simplices[iS]._nPrev->GetPosition();
6939       if ( fPos )
6940         edge->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
6941     }
6942   }
6943
6944   // prepare for putOnOffsetSurface()
6945   if (( eos->ShapeType() == TopAbs_FACE ) &&
6946       ( isCurved || !eos->_eosConcaVer.empty() ))
6947   {
6948     eos->_offsetSurf = helper.GetSurface( TopoDS::Face( eos->_shape ));
6949     eos->_edgeForOffset = 0;
6950
6951     double maxCosin = -1;
6952     //bool hasNoShrink = false;
6953     for ( TopExp_Explorer eExp( eos->_shape, TopAbs_EDGE ); eExp.More(); eExp.Next() )
6954     {
6955       _EdgesOnShape* eoe = GetShapeEdges( eExp.Current() );
6956       if ( !eoe || eoe->_edges.empty() ) continue;
6957
6958       // if ( eos->GetData()._noShrinkShapes.count( eoe->_shapeID ))
6959       //   hasNoShrink = true;
6960
6961       vector<_LayerEdge*>& eE = eoe->_edges;
6962       _LayerEdge* e = eE[ eE.size() / 2 ];
6963       if ( !e->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > maxCosin )
6964       {
6965         eos->_edgeForOffset = e;
6966         maxCosin = e->_cosin;
6967       }
6968
6969       if ( !eoe->_sWOL.IsNull() )
6970         for ( _LayerEdge* le : eoe->_edges )
6971           if ( le->Is( _LayerEdge::RISKY_SWOL ) && e->_cosin > 0 )
6972           {
6973             // make _neibors on FACE be smoothed after le->Is( BLOCKED )
6974             for ( _LayerEdge* neibor : le->_neibors )
6975             {
6976               int shapeDim =  neibor->BaseShapeDim();
6977               if ( shapeDim == 2 )
6978                 neibor->Set( _LayerEdge::NEAR_BOUNDARY ); // on FACE
6979               else if ( shapeDim == 0 )
6980                 neibor->Set( _LayerEdge::RISKY_SWOL );    // on VERTEX
6981
6982               if ( !neibor->_curvature )
6983               {
6984                 gp_XY uv = helper.GetNodeUV( F, neibor->_nodes[0] );
6985                 neibor->_curvature = _Factory::NewCurvature();
6986                 neibor->_curvature->_r = 0;
6987                 neibor->_curvature->_k = 0;
6988                 neibor->_curvature->_h2lenRatio = 0;
6989                 neibor->_curvature->_uv = uv;
6990               }
6991             }
6992           }
6993     } // loop on EDGEs
6994
6995     // Try to initialize _Mapper2D
6996
6997     // if ( hasNoShrink )
6998     //   return;
6999
7000     SMDS_ElemIteratorPtr fIt = eos->_subMesh->GetSubMeshDS()->GetElements();
7001     if ( !fIt->more() || fIt->next()->NbCornerNodes() != 4 )
7002       return;
7003
7004     // get EDGEs of quadrangle bottom
7005     std::list< TopoDS_Edge > edges;
7006     std::list< int > nbEdgesInWire;
7007     int nbWire = SMESH_Block::GetOrderedEdges( F, edges, nbEdgesInWire );
7008     if ( nbWire != 1 || nbEdgesInWire.front() < 4 )
7009       return;
7010     const SMDS_MeshNode* node;
7011     while ( true ) // make edges start at a corner VERTEX
7012     {
7013       node = SMESH_Algo::VertexNode( helper.IthVertex( 0, edges.front() ), helper.GetMeshDS() );
7014       if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7015         break;
7016       edges.pop_front();
7017       if ( edges.empty() )
7018         return;
7019     }
7020     std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
7021     while ( true ) // make edges finish at a corner VERTEX
7022     {
7023       node = SMESH_Algo::VertexNode( helper.IthVertex( 1, *edgeIt ), helper.GetMeshDS() );
7024       ++edgeIt;
7025       if ( node && helper.IsCornerOfStructure( node, eos->_subMesh->GetSubMeshDS(), helper ))
7026       {
7027         edges.erase( edgeIt, edges.end() );
7028         break;
7029       }
7030       if ( edgeIt == edges.end() )
7031         return;
7032     }
7033
7034     // get structure of nodes
7035     TParam2ColumnMap param2ColumnMap;
7036     if ( !helper.LoadNodeColumns( param2ColumnMap, F, edges, helper.GetMeshDS() ))
7037       return;
7038
7039     eos->_mapper2D = new _Mapper2D( param2ColumnMap, eos->GetData()._n2eMap );
7040
7041   } // if eos is of curved FACE
7042
7043   return;
7044 }
7045
7046 //================================================================================
7047 /*!
7048  * \brief Add faces for smoothing
7049  */
7050 //================================================================================
7051
7052 void _SolidData::AddShapesToSmooth( const set< _EdgesOnShape* >& eosToSmooth,
7053                                     const set< _EdgesOnShape* >* edgesNoAnaSmooth )
7054 {
7055   set< _EdgesOnShape * >::const_iterator eos = eosToSmooth.begin();
7056   for ( ; eos != eosToSmooth.end(); ++eos )
7057   {
7058     if ( !*eos || (*eos)->_toSmooth ) continue;
7059
7060     (*eos)->_toSmooth = true;
7061
7062     if ( (*eos)->ShapeType() == TopAbs_FACE )
7063     {
7064       PrepareEdgesToSmoothOnFace( *eos, /*substituteSrcNodes=*/false );
7065       (*eos)->_toSmooth = true;
7066     }
7067   }
7068
7069   // avoid _Smoother1D::smoothAnalyticEdge() of edgesNoAnaSmooth
7070   if ( edgesNoAnaSmooth )
7071     for ( eos = edgesNoAnaSmooth->begin(); eos != edgesNoAnaSmooth->end(); ++eos )
7072     {
7073       if ( (*eos)->_edgeSmoother )
7074         (*eos)->_edgeSmoother->_anaCurve.Nullify();
7075     }
7076 }
7077
7078 //================================================================================
7079 /*!
7080  * \brief Limit _LayerEdge::_maxLen according to local curvature
7081  */
7082 //================================================================================
7083
7084 void _ViscousBuilder::limitMaxLenByCurvature( _SolidData& data, SMESH_MesherHelper& /*helper*/ )
7085 {
7086   // find intersection of neighbor _LayerEdge's to limit _maxLen
7087   // according to local curvature (IPAL52648)
7088
7089   // This method must be called after findCollisionEdges() where _LayerEdge's
7090   // get _lenFactor initialized in the case of eos._hyp.IsOffsetMethod()
7091
7092   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7093   {
7094     _EdgesOnShape& eosI = data._edgesOnShape[iS];
7095     if ( eosI._edges.empty() ) continue;
7096     if ( !eosI._hyp.ToSmooth() )
7097     {
7098       for ( size_t i = 0; i < eosI._edges.size(); ++i )
7099       {
7100         _LayerEdge* eI = eosI._edges[i];
7101         for ( size_t iN = 0; iN < eI->_neibors.size(); ++iN )
7102         {
7103           _LayerEdge* eN = eI->_neibors[iN];
7104           if ( eI->_nodes[0]->GetID() < eN->_nodes[0]->GetID() ) // treat this pair once
7105           {
7106             _EdgesOnShape* eosN = data.GetShapeEdges( eN );
7107             limitMaxLenByCurvature( eI, eN, eosI, *eosN, eosI._hyp.ToSmooth() );
7108           }
7109         }
7110       }
7111     }
7112     else if ( eosI.ShapeType() == TopAbs_EDGE )
7113     {
7114       const TopoDS_Edge& E = TopoDS::Edge( eosI._shape );
7115       if ( SMESH_Algo::IsStraight( E, /*degenResult=*/true )) continue;
7116
7117       _LayerEdge* e0 = eosI._edges[0];
7118       for ( size_t i = 1; i < eosI._edges.size(); ++i )
7119       {
7120         _LayerEdge* eI = eosI._edges[i];
7121         limitMaxLenByCurvature( eI, e0, eosI, eosI, eosI._hyp.ToSmooth() );
7122         e0 = eI;
7123       }
7124     }
7125   }
7126 }
7127
7128 //================================================================================
7129 /*!
7130  * \brief Limit _LayerEdge::_maxLen according to local curvature
7131  */
7132 //================================================================================
7133
7134 void _ViscousBuilder::limitMaxLenByCurvature( _LayerEdge*    e1,
7135                                               _LayerEdge*    e2,
7136                                               _EdgesOnShape& /*eos1*/,
7137                                               _EdgesOnShape& /*eos2*/,
7138                                               const bool     /*isSmoothable*/ )
7139 {
7140   if (( e1->_nodes[0]->GetPosition()->GetDim() !=
7141         e2->_nodes[0]->GetPosition()->GetDim() ) &&
7142       ( e1->_cosin < 0.75 ))
7143     return; // angle > 90 deg at e1
7144
7145   gp_XYZ plnNorm = e1->_normal ^ e2->_normal;
7146   double norSize = plnNorm.SquareModulus();
7147   if ( norSize < std::numeric_limits<double>::min() )
7148     return; // parallel normals
7149
7150   // find closest points of skew _LayerEdge's
7151   SMESH_TNodeXYZ src1( e1->_nodes[0] ), src2( e2->_nodes[0] );
7152   gp_XYZ dir12 = src2 - src1;
7153   gp_XYZ perp1 = e1->_normal ^ plnNorm;
7154   gp_XYZ perp2 = e2->_normal ^ plnNorm;
7155   double  dot1 = perp2 * e1->_normal;
7156   double  dot2 = perp1 * e2->_normal;
7157   double    u1 =   ( perp2 * dir12 ) / dot1;
7158   double    u2 = - ( perp1 * dir12 ) / dot2;
7159   if ( u1 > 0 && u2 > 0 )
7160   {
7161     double ovl = ( u1 * e1->_normal * dir12 -
7162                    u2 * e2->_normal * dir12 ) / dir12.SquareModulus();
7163     if ( ovl > theSmoothThickToElemSizeRatio )
7164     {
7165       const double coef = 0.75;
7166       e1->SetMaxLen( Min( e1->_maxLen, coef * u1 / e1->_lenFactor ));
7167       e2->SetMaxLen( Min( e2->_maxLen, coef * u2 / e2->_lenFactor ));
7168     }
7169   }
7170 }
7171
7172 //================================================================================
7173 /*!
7174  * \brief Fill data._collisionEdges
7175  */
7176 //================================================================================
7177
7178 void _ViscousBuilder::findCollisionEdges( _SolidData& data, SMESH_MesherHelper& helper )
7179 {
7180   data._collisionEdges.clear();
7181
7182   // set the full thickness of the layers to LEs
7183   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7184   {
7185     _EdgesOnShape& eos = data._edgesOnShape[iS];
7186     if ( eos._edges.empty() ) continue;
7187     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7188     if ( !eos._sWOL.IsNull() ) continue; // PAL23566
7189
7190     for ( size_t i = 0; i < eos._edges.size(); ++i )
7191     {
7192       if ( eos._edges[i]->Is( _LayerEdge::BLOCKED )) continue;
7193       double maxLen = eos._edges[i]->_maxLen;
7194       eos._edges[i]->_maxLen = Precision::Infinite(); // avoid blocking
7195       eos._edges[i]->SetNewLength( 1.5 * maxLen, eos, helper );
7196       eos._edges[i]->_maxLen = maxLen;
7197     }
7198   }
7199
7200   // make temporary quadrangles got by extrusion of
7201   // mesh edges along _LayerEdge._normal's
7202
7203   vector< const SMDS_MeshElement* > tmpFaces;
7204
7205   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7206   {
7207     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7208     if ( eos.ShapeType() != TopAbs_EDGE )
7209       continue;
7210     if ( eos._edges.empty() )
7211     {
7212       _LayerEdge* edge[2] = { 0, 0 }; // LE of 2 VERTEX'es
7213       SMESH_subMeshIteratorPtr smIt = eos._subMesh->getDependsOnIterator(/*includeSelf=*/false);
7214       while ( smIt->more() )
7215         if ( _EdgesOnShape* eov = data.GetShapeEdges( smIt->next()->GetId() ))
7216           if ( eov->_edges.size() == 1 )
7217             edge[ bool( edge[0]) ] = eov->_edges[0];
7218
7219       if ( edge[1] )
7220       {
7221         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge[0], edge[1], --_tmpFaceID );
7222         tmpFaces.push_back( f );
7223       }
7224     }
7225     for ( size_t i = 0; i < eos._edges.size(); ++i )
7226     {
7227       _LayerEdge* edge = eos._edges[i];
7228       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
7229       {
7230         const SMDS_MeshNode* src2 = edge->_2neibors->srcNode(j);
7231         if ( src2->GetPosition()->GetDim() > 0 &&
7232              src2->GetID() < edge->_nodes[0]->GetID() )
7233           continue; // avoid using same segment twice
7234
7235         // a _LayerEdge containing tgt2
7236         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
7237
7238         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
7239         tmpFaces.push_back( f );
7240       }
7241     }
7242   }
7243
7244   // Find _LayerEdge's intersecting tmpFaces.
7245
7246   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
7247                                                             tmpFaces.end()));
7248   SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
7249     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
7250
7251   double dist1, dist2, segLen, eps = 0.5;
7252   _CollisionEdges collEdges;
7253   vector< const SMDS_MeshElement* > suspectFaces;
7254   const double angle45 = Cos( 45. * M_PI / 180. );
7255
7256   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7257   {
7258     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7259     if ( eos.ShapeType() == TopAbs_FACE || !eos._sWOL.IsNull() )
7260       continue;
7261     // find sub-shapes whose VL can influence VL on eos
7262     set< TGeomID > neighborShapes;
7263     PShapeIteratorPtr fIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_FACE );
7264     while ( const TopoDS_Shape* face = fIt->next() )
7265     {
7266       TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
7267       if ( _EdgesOnShape* eof = data.GetShapeEdges( faceID ))
7268       {
7269         SMESH_subMeshIteratorPtr subIt = eof->_subMesh->getDependsOnIterator(/*includeSelf=*/false);
7270         while ( subIt->more() )
7271           neighborShapes.insert( subIt->next()->GetId() );
7272       }
7273     }
7274     if ( eos.ShapeType() == TopAbs_VERTEX )
7275     {
7276       PShapeIteratorPtr eIt = helper.GetAncestors( eos._shape, *_mesh, TopAbs_EDGE );
7277       while ( const TopoDS_Shape* edge = eIt->next() )
7278         neighborShapes.erase( getMeshDS()->ShapeToIndex( *edge ));
7279     }
7280     // find intersecting _LayerEdge's
7281     for ( size_t i = 0; i < eos._edges.size(); ++i )
7282     {
7283       if ( eos._edges[i]->Is( _LayerEdge::MULTI_NORMAL )) continue;
7284       _LayerEdge*   edge = eos._edges[i];
7285       gp_Ax1 lastSegment = edge->LastSegment( segLen, eos );
7286       segLen *= 1.2;
7287
7288       gp_Vec eSegDir0, eSegDir1;
7289       if ( edge->IsOnEdge() )
7290       {
7291         SMESH_TNodeXYZ eP( edge->_nodes[0] );
7292         eSegDir0 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(0) ) - eP;
7293         eSegDir1 = SMESH_TNodeXYZ( edge->_2neibors->srcNode(1) ) - eP;
7294       }
7295       suspectFaces.clear();
7296       searcher->GetElementsInSphere( SMESH_TNodeXYZ( edge->_nodes.back()), edge->_len * 2,
7297                                      SMDSAbs_Face, suspectFaces );
7298       collEdges._intEdges.clear();
7299       for ( size_t j = 0 ; j < suspectFaces.size(); ++j )
7300       {
7301         const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) suspectFaces[j];
7302         if ( f->_le1 == edge || f->_le2 == edge ) continue;
7303         if ( !neighborShapes.count( f->_le1->_nodes[0]->getshapeId() )) continue;
7304         if ( !neighborShapes.count( f->_le2->_nodes[0]->getshapeId() )) continue;
7305         if ( edge->IsOnEdge() ) {
7306           if ( edge->_2neibors->include( f->_le1 ) ||
7307                edge->_2neibors->include( f->_le2 )) continue;
7308         }
7309         else {
7310           if (( f->_le1->IsOnEdge() && f->_le1->_2neibors->include( edge )) ||
7311               ( f->_le2->IsOnEdge() && f->_le2->_2neibors->include( edge )))  continue;
7312         }
7313         dist1 = dist2 = Precision::Infinite();
7314         if ( !edge->SegTriaInter( lastSegment, f->n(0), f->n(1), f->n(2), dist1, eps ))
7315           dist1 = Precision::Infinite();
7316         if ( !edge->SegTriaInter( lastSegment, f->n(3), f->n(2), f->n(0), dist2, eps ))
7317           dist2 = Precision::Infinite();
7318         if (( dist1 > segLen ) && ( dist2 > segLen ))
7319           continue;
7320
7321         if ( edge->IsOnEdge() )
7322         {
7323           // skip perpendicular EDGEs
7324           gp_Vec fSegDir  = SMESH_TNodeXYZ( f->n(0) ) - SMESH_TNodeXYZ( f->n(3) );
7325           bool isParallel = ( isLessAngle( eSegDir0, fSegDir, angle45 ) ||
7326                               isLessAngle( eSegDir1, fSegDir, angle45 ) ||
7327                               isLessAngle( eSegDir0, fSegDir.Reversed(), angle45 ) ||
7328                               isLessAngle( eSegDir1, fSegDir.Reversed(), angle45 ));
7329           if ( !isParallel )
7330             continue;
7331         }
7332
7333         // either limit inflation of edges or remember them for updating _normal
7334         // double dot = edge->_normal * f->GetDir();
7335         // if ( dot > 0.1 )
7336         {
7337           collEdges._intEdges.push_back( f->_le1 );
7338           collEdges._intEdges.push_back( f->_le2 );
7339         }
7340         // else
7341         // {
7342         //   double shortLen = 0.75 * ( Min( dist1, dist2 ) / edge->_lenFactor );
7343         //   edge->SetMaxLen( Min( shortLen, edge->_maxLen ));
7344         // }
7345       }
7346
7347       if ( !collEdges._intEdges.empty() )
7348       {
7349         collEdges._edge = edge;
7350         data._collisionEdges.push_back( collEdges );
7351       }
7352     }
7353   }
7354
7355   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
7356     delete tmpFaces[i];
7357
7358   // restore the zero thickness
7359   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7360   {
7361     _EdgesOnShape& eos = data._edgesOnShape[iS];
7362     if ( eos._edges.empty() ) continue;
7363     if ( eos.ShapeType() != TopAbs_EDGE && eos.ShapeType() != TopAbs_VERTEX ) continue;
7364
7365     for ( size_t i = 0; i < eos._edges.size(); ++i )
7366     {
7367       eos._edges[i]->InvalidateStep( 1, eos );
7368       eos._edges[i]->_len = 0;
7369     }
7370   }
7371 }
7372
7373 //================================================================================
7374 /*!
7375  * \brief Find _LayerEdge's located on boundary of a convex FACE whose normal
7376  *        will be updated at each inflation step
7377  */
7378 //================================================================================
7379
7380 void _ViscousBuilder::findEdgesToUpdateNormalNearConvexFace( _ConvexFace &       convFace,
7381                                                              _SolidData&         data,
7382                                                              SMESH_MesherHelper& helper )
7383 {
7384   const TGeomID convFaceID = getMeshDS()->ShapeToIndex( convFace._face );
7385   const double       preci = BRep_Tool::Tolerance( convFace._face );
7386   Handle(ShapeAnalysis_Surface) surface = helper.GetSurface( convFace._face );
7387
7388   bool edgesToUpdateFound = false;
7389
7390   map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7391   for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7392   {
7393     _EdgesOnShape& eos = * id2eos->second;
7394     if ( !eos._sWOL.IsNull() ) continue;
7395     if ( !eos._hyp.ToSmooth() ) continue;
7396     for ( size_t i = 0; i < eos._edges.size(); ++i )
7397     {
7398       _LayerEdge* ledge = eos._edges[ i ];
7399       if ( ledge->Is( _LayerEdge::UPD_NORMAL_CONV )) continue; // already checked
7400       if ( ledge->Is( _LayerEdge::MULTI_NORMAL )) continue; // not inflatable
7401
7402       gp_XYZ tgtPos = ( SMESH_NodeXYZ( ledge->_nodes[0] ) +
7403                         ledge->_normal * ledge->_lenFactor * ledge->_maxLen );
7404
7405       // the normal must be updated if distance from tgtPos to surface is less than
7406       // target thickness
7407
7408       // find an initial UV for search of a projection of tgtPos to surface
7409       const SMDS_MeshNode* nodeInFace = 0;
7410       SMDS_ElemIteratorPtr fIt = ledge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7411       while ( fIt->more() && !nodeInFace )
7412       {
7413         const SMDS_MeshElement* f = fIt->next();
7414         if ( convFaceID != f->getshapeId() ) continue;
7415
7416         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
7417         while ( nIt->more() && !nodeInFace )
7418         {
7419           const SMDS_MeshElement* n = nIt->next();
7420           if ( n->getshapeId() == convFaceID )
7421             nodeInFace = static_cast< const SMDS_MeshNode* >( n );
7422         }
7423       }
7424       if ( !nodeInFace )
7425         continue;
7426       gp_XY uv = helper.GetNodeUV( convFace._face, nodeInFace );
7427
7428       // projection
7429       surface->NextValueOfUV( uv, tgtPos, preci );
7430       double  dist = surface->Gap();
7431       if ( dist < 0.95 * ledge->_maxLen )
7432       {
7433         ledge->Set( _LayerEdge::UPD_NORMAL_CONV );
7434         if ( !ledge->_curvature ) ledge->_curvature = _Factory::NewCurvature();
7435         ledge->_curvature->_uv.SetCoord( uv.X(), uv.Y() );
7436         edgesToUpdateFound = true;
7437       }
7438     }
7439   }
7440
7441   if ( !convFace._isTooCurved && edgesToUpdateFound )
7442   {
7443     data._convexFaces.insert( make_pair( convFaceID, convFace )).first->second;
7444   }
7445 }
7446
7447 //================================================================================
7448 /*!
7449  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
7450  * _LayerEdge's on neighbor EDGE's
7451  */
7452 //================================================================================
7453
7454 bool _ViscousBuilder::updateNormals( _SolidData&         data,
7455                                      SMESH_MesherHelper& helper,
7456                                      int                 stepNb,
7457                                      double              /*stepSize*/)
7458 {
7459   updateNormalsOfC1Vertices( data );
7460
7461   if ( stepNb > 0 && !updateNormalsOfConvexFaces( data, helper, stepNb ))
7462     return false;
7463
7464   // map to store new _normal and _cosin for each intersected edge
7465   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >           edge2newEdge;
7466   map< _LayerEdge*, _LayerEdge, _LayerEdgeCmp >::iterator e2neIt;
7467   _LayerEdge zeroEdge;
7468   zeroEdge._normal.SetCoord( 0,0,0 );
7469   zeroEdge._maxLen = Precision::Infinite();
7470   zeroEdge._nodes.resize(1); // to init _TmpMeshFaceOnEdge
7471
7472   set< _EdgesOnShape* > shapesToSmooth, edgesNoAnaSmooth;
7473
7474   double segLen, dist1, dist2, dist;
7475   vector< pair< _LayerEdge*, double > > intEdgesDist;
7476   _TmpMeshFaceOnEdge quad( &zeroEdge, &zeroEdge, 0 );
7477
7478   for ( int iter = 0; iter < 5; ++iter )
7479   {
7480     edge2newEdge.clear();
7481
7482     for ( size_t iE = 0; iE < data._collisionEdges.size(); ++iE )
7483     {
7484       _CollisionEdges& ce = data._collisionEdges[iE];
7485       _LayerEdge*   edge1 = ce._edge;
7486       if ( !edge1 /*|| edge1->Is( _LayerEdge::BLOCKED )*/) continue;
7487       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7488       if ( !eos1 ) continue;
7489
7490       // detect intersections
7491       gp_Ax1 lastSeg = edge1->LastSegment( segLen, *eos1 );
7492       double testLen = 1.5 * edge1->_maxLen * edge1->_lenFactor;
7493       double     eps = 0.5;
7494       intEdgesDist.clear();
7495       double minIntDist = Precision::Infinite();
7496       for ( size_t i = 0; i < ce._intEdges.size(); i += 2 )
7497       {
7498         if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7499              ce._intEdges[i  ]->Is( _LayerEdge::BLOCKED ) &&
7500              ce._intEdges[i+1]->Is( _LayerEdge::BLOCKED ))
7501           continue;
7502         double dot  = edge1->_normal * quad.GetDir( ce._intEdges[i], ce._intEdges[i+1] );
7503         double fact = ( 1.1 + dot * dot );
7504         SMESH_TNodeXYZ pSrc0( ce.nSrc(i) ), pSrc1( ce.nSrc(i+1) );
7505         SMESH_TNodeXYZ pTgt0( ce.nTgt(i) ), pTgt1( ce.nTgt(i+1) );
7506         gp_XYZ pLast0 = pSrc0 + ( pTgt0 - pSrc0 ) * fact;
7507         gp_XYZ pLast1 = pSrc1 + ( pTgt1 - pSrc1 ) * fact;
7508         dist1 = dist2 = Precision::Infinite();
7509         if ( !edge1->SegTriaInter( lastSeg, pSrc0, pLast0, pSrc1,  dist1, eps ) &&
7510              !edge1->SegTriaInter( lastSeg, pSrc1, pLast1, pLast0, dist2, eps ))
7511           continue;
7512         dist = dist1;
7513         if ( dist > testLen || dist <= 0 )
7514         {
7515           dist = dist2;
7516           if ( dist > testLen || dist <= 0 )
7517             continue;
7518         }
7519         // choose a closest edge
7520         gp_Pnt intP( lastSeg.Location().XYZ() + lastSeg.Direction().XYZ() * ( dist + segLen ));
7521         double d1 = intP.SquareDistance( pSrc0 );
7522         double d2 = intP.SquareDistance( pSrc1 );
7523         int iClose = i + ( d2 < d1 );
7524         _LayerEdge* edge2 = ce._intEdges[iClose];
7525         edge2->Unset( _LayerEdge::MARKED );
7526
7527         // choose a closest edge among neighbors
7528         gp_Pnt srcP( SMESH_TNodeXYZ( edge1->_nodes[0] ));
7529         d1 = srcP.SquareDistance( SMESH_TNodeXYZ( edge2->_nodes[0] ));
7530         for ( size_t j = 0; j < intEdgesDist.size(); ++j )
7531         {
7532           _LayerEdge * edgeJ = intEdgesDist[j].first;
7533           if ( edge2->IsNeiborOnEdge( edgeJ ))
7534           {
7535             d2 = srcP.SquareDistance( SMESH_TNodeXYZ( edgeJ->_nodes[0] ));
7536             ( d1 < d2 ? edgeJ : edge2 )->Set( _LayerEdge::MARKED );
7537           }
7538         }
7539         intEdgesDist.push_back( make_pair( edge2, dist ));
7540         // if ( Abs( d2 - d1 ) / Max( d2, d1 ) < 0.5 )
7541         // {
7542         //   iClose = i + !( d2 < d1 );
7543         //   intEdges.push_back( ce._intEdges[iClose] );
7544         //   ce._intEdges[iClose]->Unset( _LayerEdge::MARKED );
7545         // }
7546         minIntDist = Min( edge1->_len * edge1->_lenFactor - segLen + dist, minIntDist );
7547       }
7548
7549       //ce._edge = 0;
7550
7551       // compute new _normals
7552       for ( size_t i = 0; i < intEdgesDist.size(); ++i )
7553       {
7554         _LayerEdge* edge2   = intEdgesDist[i].first;
7555         double      distWgt = edge1->_len / intEdgesDist[i].second;
7556         // if ( edge1->Is( _LayerEdge::BLOCKED ) &&
7557         //      edge2->Is( _LayerEdge::BLOCKED )) continue;        
7558         if ( edge2->Is( _LayerEdge::MARKED )) continue;
7559         edge2->Set( _LayerEdge::MARKED );
7560
7561         // get a new normal
7562         gp_XYZ dir1 = edge1->_normal, dir2 = edge2->_normal;
7563
7564         double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
7565         double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7566         double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
7567         // double cos1 = Abs( edge1->_cosin ),        cos2 = Abs( edge2->_cosin );
7568         // double sgn1 = 0.1 * ( 1 + edge1->_cosin ), sgn2 = 0.1 * ( 1 + edge2->_cosin );
7569         // double wgt1 = ( cos1 + sgn1 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7570         // double wgt2 = ( cos2 + sgn2 ) / ( cos1 + cos2 + sgn1 + sgn2 );
7571         gp_XYZ newNormal = wgt1 * dir1 + wgt2 * dir2;
7572         newNormal.Normalize();
7573
7574         // get new cosin
7575         double newCos;
7576         double sgn1 = edge1->_cosin / cos1, sgn2 = edge2->_cosin / cos2;
7577         if ( cos1 < theMinSmoothCosin )
7578         {
7579           newCos = cos2 * sgn1;
7580         }
7581         else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
7582         {
7583           newCos = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
7584         }
7585         else
7586         {
7587           newCos = edge1->_cosin;
7588         }
7589
7590         e2neIt = edge2newEdge.insert( make_pair( edge1, zeroEdge )).first;
7591         e2neIt->second._normal += distWgt * newNormal;
7592         e2neIt->second._cosin   = newCos;
7593         e2neIt->second.SetMaxLen( 0.7 * minIntDist / edge1->_lenFactor );
7594         if ( iter > 0 && sgn1 * sgn2 < 0 && edge1->_cosin < 0 )
7595           e2neIt->second._normal += dir2;
7596
7597         e2neIt = edge2newEdge.insert( make_pair( edge2, zeroEdge )).first;
7598         e2neIt->second._normal += distWgt * newNormal;
7599         if ( Precision::IsInfinite( zeroEdge._maxLen ))
7600         {
7601           e2neIt->second._cosin  = edge2->_cosin;
7602           e2neIt->second.SetMaxLen( 1.3 * minIntDist / edge1->_lenFactor );
7603         }
7604         if ( iter > 0 && sgn1 * sgn2 < 0 && edge2->_cosin < 0 )
7605           e2neIt->second._normal += dir1;
7606       }
7607     }
7608
7609     if ( edge2newEdge.empty() )
7610       break; //return true;
7611
7612     dumpFunction(SMESH_Comment("updateNormals")<< data._index << "_" << stepNb << "_it" << iter);
7613
7614     // Update data of edges depending on a new _normal
7615
7616     data.UnmarkEdges();
7617     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7618     {
7619       _LayerEdge*    edge = e2neIt->first;
7620       _LayerEdge& newEdge = e2neIt->second;
7621       _EdgesOnShape*  eos = data.GetShapeEdges( edge );
7622       if ( edge->Is( _LayerEdge::BLOCKED ) && newEdge._maxLen > edge->_len )
7623         continue;
7624
7625       // Check if a new _normal is OK:
7626       newEdge._normal.Normalize();
7627       if ( !isNewNormalOk( data, *edge, newEdge._normal ))
7628       {
7629         if ( newEdge._maxLen < edge->_len && iter > 0 ) // limit _maxLen
7630         {
7631           edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7632           edge->SetMaxLen( newEdge._maxLen );
7633           edge->SetNewLength( newEdge._maxLen, *eos, helper );
7634         }
7635         continue; // the new _normal is bad
7636       }
7637       // the new _normal is OK
7638
7639       // find shapes that need smoothing due to change of _normal
7640       if ( edge->_cosin   < theMinSmoothCosin &&
7641            newEdge._cosin > theMinSmoothCosin )
7642       {
7643         if ( eos->_sWOL.IsNull() )
7644         {
7645           SMDS_ElemIteratorPtr fIt = edge->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
7646           while ( fIt->more() )
7647             shapesToSmooth.insert( data.GetShapeEdges( fIt->next()->getshapeId() ));
7648         }
7649         else // edge inflates along a FACE
7650         {
7651           TopoDS_Shape V = helper.GetSubShapeByNode( edge->_nodes[0], getMeshDS() );
7652           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE, &eos->_sWOL );
7653           while ( const TopoDS_Shape* E = eIt->next() )
7654           {
7655             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ),
7656                                          eos->_hyp.Get1stLayerThickness() );
7657             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
7658             if ( angle < M_PI / 2 )
7659               shapesToSmooth.insert( data.GetShapeEdges( *E ));
7660           }
7661         }
7662       }
7663
7664       double len = edge->_len;
7665       edge->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7666       edge->SetNormal( newEdge._normal );
7667       edge->SetCosin( newEdge._cosin );
7668       edge->SetNewLength( len, *eos, helper );
7669       edge->Set( _LayerEdge::MARKED );
7670       edge->Set( _LayerEdge::NORMAL_UPDATED );
7671       edgesNoAnaSmooth.insert( eos );
7672     }
7673
7674     // Update normals and other dependent data of not intersecting _LayerEdge's
7675     // neighboring the intersecting ones
7676
7677     for ( e2neIt = edge2newEdge.begin(); e2neIt != edge2newEdge.end(); ++e2neIt )
7678     {
7679       _LayerEdge*   edge1 = e2neIt->first;
7680       _EdgesOnShape* eos1 = data.GetShapeEdges( edge1 );
7681       if ( !edge1->Is( _LayerEdge::MARKED ))
7682         continue;
7683
7684       if ( edge1->IsOnEdge() )
7685       {
7686         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
7687         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
7688         edge1->SetDataByNeighbors( n1, n2, *eos1, helper );
7689       }
7690
7691       if ( !edge1->_2neibors || !eos1->_sWOL.IsNull() )
7692         continue;
7693       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
7694       {
7695         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
7696         if ( neighbor->Is( _LayerEdge::MARKED ) /*edge2newEdge.count ( neighbor )*/)
7697           continue; // j-th neighbor is also intersected
7698         _LayerEdge* prevEdge = edge1;
7699         const int nbSteps = 10;
7700         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
7701         {
7702           if ( neighbor->Is( _LayerEdge::BLOCKED ) ||
7703                neighbor->Is( _LayerEdge::MARKED ))
7704             break;
7705           _EdgesOnShape* eos = data.GetShapeEdges( neighbor );
7706           if ( !eos ) continue;
7707           _LayerEdge* nextEdge = neighbor;
7708           if ( neighbor->_2neibors )
7709           {
7710             int iNext = 0;
7711             nextEdge = neighbor->_2neibors->_edges[iNext];
7712             if ( nextEdge == prevEdge )
7713               nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
7714           }
7715           double r = double(step-1)/nbSteps/(iter+1);
7716           if ( !nextEdge->_2neibors )
7717             r = Min( r, 0.5 );
7718
7719           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
7720           newNorm.Normalize();
7721           if ( !isNewNormalOk( data, *neighbor, newNorm ))
7722             break;
7723
7724           double len = neighbor->_len;
7725           neighbor->InvalidateStep( stepNb + 1, *eos, /*restoreLength=*/true  );
7726           neighbor->SetNormal( newNorm );
7727           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
7728           if ( neighbor->_2neibors )
7729             neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], *eos, helper );
7730           neighbor->SetNewLength( len, *eos, helper );
7731           neighbor->Set( _LayerEdge::MARKED );
7732           neighbor->Set( _LayerEdge::NORMAL_UPDATED );
7733           edgesNoAnaSmooth.insert( eos );
7734
7735           if ( !neighbor->_2neibors )
7736             break; // neighbor is on VERTEX
7737
7738           // goto the next neighbor
7739           prevEdge = neighbor;
7740           neighbor = nextEdge;
7741         }
7742       }
7743     }
7744     dumpFunctionEnd();
7745   } // iterations
7746
7747   data.AddShapesToSmooth( shapesToSmooth, &edgesNoAnaSmooth );
7748
7749   return true;
7750 }
7751
7752 //================================================================================
7753 /*!
7754  * \brief Check if a new normal is OK
7755  */
7756 //================================================================================
7757
7758 bool _ViscousBuilder::isNewNormalOk( _SolidData&   data,
7759                                      _LayerEdge&   edge,
7760                                      const gp_XYZ& newNormal)
7761 {
7762   // check a min angle between the newNormal and surrounding faces
7763   vector<_Simplex> simplices;
7764   SMESH_TNodeXYZ n0( edge._nodes[0] ), n1, n2;
7765   _Simplex::GetSimplices( n0._node, simplices, data._ignoreFaceIds, &data );
7766   double newMinDot = 1, curMinDot = 1;
7767   for ( size_t i = 0; i < simplices.size(); ++i )
7768   {
7769     n1.Set( simplices[i]._nPrev );
7770     n2.Set( simplices[i]._nNext );
7771     gp_XYZ normFace = ( n1 - n0 ) ^ ( n2 - n0 );
7772     double normLen2 = normFace.SquareModulus();
7773     if ( normLen2 < std::numeric_limits<double>::min() )
7774       continue;
7775     normFace /= Sqrt( normLen2 );
7776     newMinDot = Min( newNormal    * normFace, newMinDot );
7777     curMinDot = Min( edge._normal * normFace, curMinDot );
7778   }
7779   bool ok = true;
7780   if ( newMinDot < 0.5 )
7781   {
7782     ok = ( newMinDot >= curMinDot * 0.9 );
7783     //return ( newMinDot >= ( curMinDot * ( 0.8 + 0.1 * edge.NbSteps() )));
7784     // double initMinDot2 = 1. - edge._cosin * edge._cosin;
7785     // return ( newMinDot * newMinDot ) >= ( 0.8 * initMinDot2 );
7786   }
7787
7788   return ok;
7789 }
7790
7791 //================================================================================
7792 /*!
7793  * \brief Modify normals of _LayerEdge's on FACE to reflex smoothing
7794  */
7795 //================================================================================
7796
7797 bool _ViscousBuilder::updateNormalsOfSmoothed( _SolidData&         data,
7798                                                SMESH_MesherHelper& /*helper*/,
7799                                                const int           nbSteps,
7800                                                const double        stepSize )
7801 {
7802   if ( data._nbShapesToSmooth == 0 || nbSteps == 0 )
7803     return true; // no shapes needing smoothing
7804
7805   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7806   {
7807     _EdgesOnShape& eos = data._edgesOnShape[ iS ];
7808     if ( //!eos._toSmooth ||  _eosC1 have _toSmooth == false
7809          !eos._hyp.ToSmooth() ||
7810          eos.ShapeType() != TopAbs_FACE ||
7811          eos._edges.empty() )
7812       continue;
7813
7814     bool toSmooth = ( eos._edges[ 0 ]->NbSteps() >= nbSteps+1 );
7815     if ( !toSmooth ) continue;
7816
7817     for ( size_t i = 0; i < eos._edges.size(); ++i )
7818     {
7819       _LayerEdge* edge = eos._edges[i];
7820       if ( !edge->Is( _LayerEdge::SMOOTHED ))
7821         continue;
7822       if ( edge->Is( _LayerEdge::DIFFICULT ) && nbSteps != 1 )
7823         continue;
7824
7825       const gp_XYZ& pPrev = edge->PrevPos();
7826       const gp_XYZ& pLast = edge->_pos.back();
7827       gp_XYZ      stepVec = pLast - pPrev;
7828       double realStepSize = stepVec.Modulus();
7829       if ( realStepSize < numeric_limits<double>::min() )
7830         continue;
7831
7832       edge->_lenFactor = realStepSize / stepSize;
7833       edge->_normal    = stepVec / realStepSize;
7834       edge->Set( _LayerEdge::NORMAL_UPDATED );
7835     }
7836   }
7837
7838   return true;
7839 }
7840
7841 //================================================================================
7842 /*!
7843  * \brief Modify normals of _LayerEdge's on C1 VERTEXes
7844  */
7845 //================================================================================
7846
7847 void _ViscousBuilder::updateNormalsOfC1Vertices( _SolidData& data )
7848 {
7849   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
7850   {
7851     _EdgesOnShape& eov = data._edgesOnShape[ iS ];
7852     if ( eov._eosC1.empty() ||
7853          eov.ShapeType() != TopAbs_VERTEX ||
7854          eov._edges.empty() )
7855       continue;
7856
7857     gp_XYZ newNorm   = eov._edges[0]->_normal;
7858     double curThick  = eov._edges[0]->_len * eov._edges[0]->_lenFactor;
7859     bool normChanged = false;
7860
7861     for ( size_t i = 0; i < eov._eosC1.size(); ++i )
7862     {
7863       _EdgesOnShape*   eoe = eov._eosC1[i];
7864       const TopoDS_Edge& e = TopoDS::Edge( eoe->_shape );
7865       const double    eLen = SMESH_Algo::EdgeLength( e );
7866       TopoDS_Shape    oppV = SMESH_MesherHelper::IthVertex( 0, e );
7867       if ( oppV.IsSame( eov._shape ))
7868         oppV = SMESH_MesherHelper::IthVertex( 1, e );
7869       _EdgesOnShape* eovOpp = data.GetShapeEdges( oppV );
7870       if ( !eovOpp || eovOpp->_edges.empty() ) continue;
7871       if ( eov._edges[0]->Is( _LayerEdge::BLOCKED )) continue;
7872
7873       double curThickOpp = eovOpp->_edges[0]->_len * eovOpp->_edges[0]->_lenFactor;
7874       if ( curThickOpp + curThick < eLen )
7875         continue;
7876
7877       double wgt = 2. * curThick / eLen;
7878       newNorm += wgt * eovOpp->_edges[0]->_normal;
7879       normChanged = true;
7880     }
7881     if ( normChanged )
7882     {
7883       eov._edges[0]->SetNormal( newNorm.Normalized() );
7884       eov._edges[0]->Set( _LayerEdge::NORMAL_UPDATED );
7885     }
7886   }
7887 }
7888
7889 //================================================================================
7890 /*!
7891  * \brief Modify normals of _LayerEdge's on _ConvexFace's
7892  */
7893 //================================================================================
7894
7895 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
7896                                                   SMESH_MesherHelper& helper,
7897                                                   int                 stepNb )
7898 {
7899   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
7900   bool isOK;
7901
7902   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
7903   for ( ; id2face != data._convexFaces.end(); ++id2face )
7904   {
7905     _ConvexFace & convFace = (*id2face).second;
7906     convFace._normalsFixedOnBorders = false; // to update at each inflation step
7907
7908     if ( convFace._normalsFixed )
7909       continue; // already fixed
7910     if ( convFace.CheckPrisms() )
7911       continue; // nothing to fix
7912
7913     convFace._normalsFixed = true;
7914
7915     BRepAdaptor_Surface surface ( convFace._face, false );
7916     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
7917
7918     // check if the convex FACE is of spherical shape
7919
7920     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
7921     Bnd_B3d nodesBox;
7922     gp_Pnt  center;
7923
7924     map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.begin();
7925     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7926     {
7927       _EdgesOnShape& eos = *(id2eos->second);
7928       if ( eos.ShapeType() == TopAbs_VERTEX )
7929       {
7930         _LayerEdge* ledge = eos._edges[ 0 ];
7931         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
7932           centersBox.Add( center );
7933       }
7934       for ( size_t i = 0; i < eos._edges.size(); ++i )
7935         nodesBox.Add( SMESH_TNodeXYZ( eos._edges[ i ]->_nodes[0] ));
7936     }
7937     if ( centersBox.IsVoid() )
7938     {
7939       debugMsg( "Error: centersBox.IsVoid()" );
7940       return false;
7941     }
7942     const bool isSpherical =
7943       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
7944
7945     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
7946     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
7947
7948     if ( isSpherical )
7949     {
7950       // set _LayerEdge::_normal as average of all normals
7951
7952       // WARNING: different density of nodes on EDGEs is not taken into account that
7953       // can lead to an improper new normal
7954
7955       gp_XYZ avgNormal( 0,0,0 );
7956       nbEdges = 0;
7957       id2eos = convFace._subIdToEOS.begin();
7958       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
7959       {
7960         _EdgesOnShape& eos = *(id2eos->second);
7961         // set data of _CentralCurveOnEdge
7962         if ( eos.ShapeType() == TopAbs_EDGE )
7963         {
7964           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
7965           ceCurve.SetShapes( TopoDS::Edge( eos._shape ), convFace, data, helper );
7966           if ( !eos._sWOL.IsNull() )
7967             ceCurve._adjFace.Nullify();
7968           else
7969             ceCurve._ledges.insert( ceCurve._ledges.end(),
7970                                     eos._edges.begin(), eos._edges.end());
7971         }
7972         // summarize normals
7973         for ( size_t i = 0; i < eos._edges.size(); ++i )
7974           avgNormal += eos._edges[ i ]->_normal;
7975       }
7976       double normSize = avgNormal.SquareModulus();
7977       if ( normSize < 1e-200 )
7978       {
7979         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
7980         return false;
7981       }
7982       avgNormal /= Sqrt( normSize );
7983
7984       // compute new _LayerEdge::_cosin on EDGEs
7985       double avgCosin = 0;
7986       int     nbCosin = 0;
7987       gp_Vec inFaceDir;
7988       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
7989       {
7990         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
7991         if ( ceCurve._adjFace.IsNull() )
7992           continue;
7993         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
7994         {
7995           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
7996           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
7997           if ( isOK )
7998           {
7999             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
8000             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
8001             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
8002             nbCosin++;
8003           }
8004         }
8005       }
8006       if ( nbCosin > 0 )
8007         avgCosin /= nbCosin;
8008
8009       // set _LayerEdge::_normal = avgNormal
8010       id2eos = convFace._subIdToEOS.begin();
8011       for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8012       {
8013         _EdgesOnShape& eos = *(id2eos->second);
8014         if ( eos.ShapeType() != TopAbs_EDGE )
8015           for ( size_t i = 0; i < eos._edges.size(); ++i )
8016             eos._edges[ i ]->_cosin = avgCosin;
8017
8018         for ( size_t i = 0; i < eos._edges.size(); ++i )
8019         {
8020           eos._edges[ i ]->SetNormal( avgNormal );
8021           eos._edges[ i ]->Set( _LayerEdge::NORMAL_UPDATED );
8022         }
8023       }
8024     }
8025     else // if ( isSpherical )
8026     {
8027       // We suppose that centers of curvature at all points of the FACE
8028       // lie on some curve, let's call it "central curve". For all _LayerEdge's
8029       // having a common center of curvature we define the same new normal
8030       // as a sum of normals of _LayerEdge's on EDGEs among them.
8031
8032       // get all centers of curvature for each EDGE
8033
8034       helper.SetSubShape( convFace._face );
8035       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
8036
8037       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
8038       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
8039       {
8040         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
8041
8042         // set adjacent FACE
8043         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
8044
8045         // get _LayerEdge's of the EDGE
8046         TGeomID edgeID = meshDS->ShapeToIndex( edge );
8047         _EdgesOnShape* eos = data.GetShapeEdges( edgeID );
8048         if ( !eos || eos->_edges.empty() )
8049         {
8050           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
8051           for ( int iV = 0; iV < 2; ++iV )
8052           {
8053             TopoDS_Vertex v = helper.IthVertex( iV, edge );
8054             TGeomID     vID = meshDS->ShapeToIndex( v );
8055             eos = data.GetShapeEdges( vID );
8056             vertexLEdges[ iV ] = eos->_edges[ 0 ];
8057           }
8058           edgeLEdge    = &vertexLEdges[0];
8059           edgeLEdgeEnd = edgeLEdge + 2;
8060
8061           centerCurves[ iE ]._adjFace.Nullify();
8062         }
8063         else
8064         {
8065           if ( ! eos->_toSmooth )
8066             data.SortOnEdge( edge, eos->_edges );
8067           edgeLEdge    = &eos->_edges[ 0 ];
8068           edgeLEdgeEnd = edgeLEdge + eos->_edges.size();
8069           vertexLEdges[0] = eos->_edges.front()->_2neibors->_edges[0];
8070           vertexLEdges[1] = eos->_edges.back() ->_2neibors->_edges[1];
8071
8072           if ( ! eos->_sWOL.IsNull() )
8073             centerCurves[ iE ]._adjFace.Nullify();
8074         }
8075
8076         // Get curvature centers
8077
8078         centersBox.Clear();
8079
8080         if ( edgeLEdge[0]->IsOnEdge() &&
8081              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
8082         { // 1st VERTEX
8083           centerCurves[ iE ].Append( center, vertexLEdges[0] );
8084           centersBox.Add( center );
8085         }
8086         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
8087           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
8088           { // EDGE or VERTEXes
8089             centerCurves[ iE ].Append( center, *edgeLEdge );
8090             centersBox.Add( center );
8091           }
8092         if ( edgeLEdge[-1]->IsOnEdge() &&
8093              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
8094         { // 2nd VERTEX
8095           centerCurves[ iE ].Append( center, vertexLEdges[1] );
8096           centersBox.Add( center );
8097         }
8098         centerCurves[ iE ]._isDegenerated =
8099           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
8100
8101       } // loop on EDGES of convFace._face to set up data of centerCurves
8102
8103       // Compute new normals for _LayerEdge's on EDGEs
8104
8105       double avgCosin = 0;
8106       int     nbCosin = 0;
8107       gp_Vec inFaceDir;
8108       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
8109       {
8110         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
8111         if ( ceCurve._isDegenerated )
8112           continue;
8113         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
8114         vector< gp_XYZ > &   newNormals = ceCurve._normals;
8115         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
8116         {
8117           isOK = false;
8118           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
8119           {
8120             if ( iE1 != iE2 )
8121               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
8122           }
8123           if ( isOK && !ceCurve._adjFace.IsNull() )
8124           {
8125             // compute new _LayerEdge::_cosin
8126             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
8127             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
8128             if ( isOK )
8129             {
8130               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
8131               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
8132               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
8133               nbCosin++;
8134             }
8135           }
8136         }
8137       }
8138       // set new normals to _LayerEdge's of NOT degenerated central curves
8139       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8140       {
8141         if ( centerCurves[ iE ]._isDegenerated )
8142           continue;
8143         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8144         {
8145           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( centerCurves[ iE ]._normals[ iLE ]);
8146           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8147         }
8148       }
8149       // set new normals to _LayerEdge's of     degenerated central curves
8150       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8151       {
8152         if ( !centerCurves[ iE ]._isDegenerated ||
8153              centerCurves[ iE ]._ledges.size() < 3 )
8154           continue;
8155         // new normal is an average of new normals at VERTEXes that
8156         // was computed on non-degenerated _CentralCurveOnEdge's
8157         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
8158                            centerCurves[ iE ]._ledges.back ()->_normal );
8159         double sz = newNorm.Modulus();
8160         if ( sz < 1e-200 )
8161           continue;
8162         newNorm /= sz;
8163         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
8164                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
8165         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
8166         {
8167           centerCurves[ iE ]._ledges[ iLE ]->SetNormal( newNorm );
8168           centerCurves[ iE ]._ledges[ iLE ]->_cosin   = newCosin;
8169           centerCurves[ iE ]._ledges[ iLE ]->Set( _LayerEdge::NORMAL_UPDATED );
8170         }
8171       }
8172
8173       // Find new normals for _LayerEdge's based on FACE
8174
8175       if ( nbCosin > 0 )
8176         avgCosin /= nbCosin;
8177       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
8178       map< TGeomID, _EdgesOnShape* >::iterator id2eos = convFace._subIdToEOS.find( faceID );
8179       if ( id2eos != convFace._subIdToEOS.end() )
8180       {
8181         int iE = 0;
8182         gp_XYZ newNorm;
8183         _EdgesOnShape& eos = * ( id2eos->second );
8184         for ( size_t i = 0; i < eos._edges.size(); ++i )
8185         {
8186           _LayerEdge* ledge = eos._edges[ i ];
8187           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
8188             continue;
8189           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
8190           {
8191             iE = iE % centerCurves.size();
8192             if ( centerCurves[ iE ]._isDegenerated )
8193               continue;
8194             newNorm.SetCoord( 0,0,0 );
8195             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
8196             {
8197               ledge->SetNormal( newNorm );
8198               ledge->_cosin  = avgCosin;
8199               ledge->Set( _LayerEdge::NORMAL_UPDATED );
8200               break;
8201             }
8202           }
8203         }
8204       }
8205
8206     } // not a quasi-spherical FACE
8207
8208     // Update _LayerEdge's data according to a new normal
8209
8210     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
8211                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
8212
8213     id2eos = convFace._subIdToEOS.begin();
8214     for ( ; id2eos != convFace._subIdToEOS.end(); ++id2eos )
8215     {
8216       _EdgesOnShape& eos = * ( id2eos->second );
8217       for ( size_t i = 0; i < eos._edges.size(); ++i )
8218       {
8219         _LayerEdge* & ledge = eos._edges[ i ];
8220         double len = ledge->_len;
8221         ledge->InvalidateStep( stepNb + 1, eos, /*restoreLength=*/true );
8222         ledge->SetCosin( ledge->_cosin );
8223         ledge->SetNewLength( len, eos, helper );
8224       }
8225       if ( eos.ShapeType() != TopAbs_FACE )
8226         for ( size_t i = 0; i < eos._edges.size(); ++i )
8227         {
8228           _LayerEdge* ledge = eos._edges[ i ];
8229           for ( size_t iN = 0; iN < ledge->_neibors.size(); ++iN )
8230           {
8231             _LayerEdge* neibor = ledge->_neibors[iN];
8232             if ( neibor->_nodes[0]->GetPosition()->GetDim() == 2 )
8233             {
8234               neibor->Set( _LayerEdge::NEAR_BOUNDARY );
8235               neibor->Set( _LayerEdge::MOVED );
8236               neibor->SetSmooLen( neibor->_len );
8237             }
8238           }
8239         }
8240     } // loop on sub-shapes of convFace._face
8241
8242     // Find FACEs adjacent to convFace._face that got necessity to smooth
8243     // as a result of normals modification
8244
8245     set< _EdgesOnShape* > adjFacesToSmooth;
8246     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
8247     {
8248       if ( centerCurves[ iE ]._adjFace.IsNull() ||
8249            centerCurves[ iE ]._adjFaceToSmooth )
8250         continue;
8251       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
8252       {
8253         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
8254         {
8255           adjFacesToSmooth.insert( data.GetShapeEdges( centerCurves[ iE ]._adjFace ));
8256           break;
8257         }
8258       }
8259     }
8260     data.AddShapesToSmooth( adjFacesToSmooth );
8261
8262     dumpFunctionEnd();
8263
8264
8265   } // loop on data._convexFaces
8266
8267   return true;
8268 }
8269
8270 //================================================================================
8271 /*!
8272  * \brief Return max curvature of a FACE
8273  */
8274 //================================================================================
8275
8276 double _ConvexFace::GetMaxCurvature( _SolidData&         data,
8277                                      _EdgesOnShape&      eof,
8278                                      BRepLProp_SLProps&  surfProp,
8279                                      SMESH_MesherHelper& helper)
8280 {
8281   double maxCurvature = 0;
8282
8283   TopoDS_Face F = TopoDS::Face( eof._shape );
8284
8285   const int           nbTestPnt = 5;
8286   const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8287   SMESH_subMeshIteratorPtr smIt = eof._subMesh->getDependsOnIterator(/*includeSelf=*/true);
8288   while ( smIt->more() )
8289   {
8290     SMESH_subMesh* sm = smIt->next();
8291     const TGeomID subID = sm->GetId();
8292
8293     // find _LayerEdge's of a sub-shape
8294     _EdgesOnShape* eos;
8295     if (( eos = data.GetShapeEdges( subID )))
8296       this->_subIdToEOS.insert( make_pair( subID, eos ));
8297     else
8298       continue;
8299
8300     // check concavity and curvature and limit data._stepSize
8301     const double minCurvature =
8302       1. / ( eos->_hyp.GetTotalThickness() * ( 1 + theThickToIntersection ));
8303     size_t iStep = Max( 1, eos->_edges.size() / nbTestPnt );
8304     for ( size_t i = 0; i < eos->_edges.size(); i += iStep )
8305     {
8306       gp_XY uv = helper.GetNodeUV( F, eos->_edges[ i ]->_nodes[0] );
8307       surfProp.SetParameters( uv.X(), uv.Y() );
8308       if ( surfProp.IsCurvatureDefined() )
8309       {
8310         double curvature = Max( surfProp.MaxCurvature() * oriFactor,
8311                                 surfProp.MinCurvature() * oriFactor );
8312         maxCurvature = Max( maxCurvature, curvature );
8313
8314         if ( curvature > minCurvature )
8315           this->_isTooCurved = true;
8316       }
8317     }
8318   } // loop on sub-shapes of the FACE
8319
8320   return maxCurvature;
8321 }
8322
8323 //================================================================================
8324 /*!
8325  * \brief Finds a center of curvature of a surface at a _LayerEdge
8326  */
8327 //================================================================================
8328
8329 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
8330                                         BRepLProp_SLProps&  surfProp,
8331                                         SMESH_MesherHelper& helper,
8332                                         gp_Pnt &            center ) const
8333 {
8334   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
8335   surfProp.SetParameters( uv.X(), uv.Y() );
8336   if ( !surfProp.IsCurvatureDefined() )
8337     return false;
8338
8339   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
8340   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
8341   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
8342   if ( surfCurvatureMin > surfCurvatureMax )
8343     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
8344   else
8345     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
8346
8347   return true;
8348 }
8349
8350 //================================================================================
8351 /*!
8352  * \brief Check that prisms are not distorted
8353  */
8354 //================================================================================
8355
8356 bool _ConvexFace::CheckPrisms() const
8357 {
8358   double vol = 0;
8359   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
8360   {
8361     const _LayerEdge* edge = _simplexTestEdges[i];
8362     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
8363     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
8364       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], tgtXYZ, vol ))
8365       {
8366         debugMsg( "Bad simplex of _simplexTestEdges ("
8367                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
8368                   << " "<< edge->_simplices[j]._nPrev->GetID()
8369                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
8370         return false;
8371       }
8372   }
8373   return true;
8374 }
8375
8376 //================================================================================
8377 /*!
8378  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
8379  *        stored in this _CentralCurveOnEdge.
8380  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
8381  *  \param [in,out] newNormal - current normal at this point, to be redefined
8382  *  \return bool - true if succeeded.
8383  */
8384 //================================================================================
8385
8386 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
8387 {
8388   if ( this->_isDegenerated )
8389     return false;
8390
8391   // find two centers the given one lies between
8392
8393   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
8394   {
8395     double sl2 = 1.001 * _segLength2[ i ];
8396
8397     double d1 = center.SquareDistance( _curvaCenters[ i ]);
8398     if ( d1 > sl2 )
8399       continue;
8400     
8401     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
8402     if ( d2 > sl2 || d2 + d1 < 1e-100 )
8403       continue;
8404
8405     d1 = Sqrt( d1 );
8406     d2 = Sqrt( d2 );
8407     double r = d1 / ( d1 + d2 );
8408     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
8409                    (      r ) * _ledges[ i+1 ]->_normal );
8410     norm.Normalize();
8411
8412     newNormal += norm;
8413     double sz = newNormal.Modulus();
8414     if ( sz < 1e-200 )
8415       break;
8416     newNormal /= sz;
8417     return true;
8418   }
8419   return false;
8420 }
8421
8422 //================================================================================
8423 /*!
8424  * \brief Set shape members
8425  */
8426 //================================================================================
8427
8428 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
8429                                      const _ConvexFace&  convFace,
8430                                      _SolidData&         data,
8431                                      SMESH_MesherHelper& helper)
8432 {
8433   _edge = edge;
8434
8435   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
8436   while ( const TopoDS_Shape* F = fIt->next())
8437     if ( !convFace._face.IsSame( *F ))
8438     {
8439       _adjFace = TopoDS::Face( *F );
8440       _adjFaceToSmooth = false;
8441       // _adjFace already in a smoothing queue ?
8442       if ( _EdgesOnShape* eos = data.GetShapeEdges( _adjFace ))
8443         _adjFaceToSmooth = eos->_toSmooth;
8444       break;
8445     }
8446 }
8447
8448 //================================================================================
8449 /*!
8450  * \brief Looks for intersection of it's last segment with faces
8451  *  \param distance - returns shortest distance from the last node to intersection
8452  */
8453 //================================================================================
8454
8455 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
8456                                    double &                 distance,
8457                                    const double&            epsilon,
8458                                    _EdgesOnShape&           eos,
8459                                    const SMDS_MeshElement** intFace)
8460 {
8461   vector< const SMDS_MeshElement* > suspectFaces;
8462   double segLen;
8463   gp_Ax1 lastSegment = LastSegment( segLen, eos );
8464   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
8465
8466   bool segmentIntersected = false;
8467   distance = Precision::Infinite();
8468   int iFace = -1; // intersected face
8469   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
8470   {
8471     const SMDS_MeshElement* face = suspectFaces[j];
8472     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
8473          face->GetNodeIndex( _nodes[0]     ) >= 0 )
8474       continue; // face sharing _LayerEdge node
8475     const int nbNodes = face->NbCornerNodes();
8476     bool intFound = false;
8477     double dist;
8478     SMDS_MeshElement::iterator nIt = face->begin_nodes();
8479     if ( nbNodes == 3 )
8480     {
8481       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
8482     }
8483     else
8484     {
8485       const SMDS_MeshNode* tria[3];
8486       tria[0] = *nIt++;
8487       tria[1] = *nIt++;
8488       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
8489       {
8490         tria[2] = *nIt++;
8491         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
8492         tria[1] = tria[2];
8493       }
8494     }
8495     if ( intFound )
8496     {
8497       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
8498         segmentIntersected = true;
8499       if ( distance > dist )
8500         distance = dist, iFace = j;
8501     }
8502   }
8503   if ( intFace ) *intFace = ( iFace != -1 ) ? suspectFaces[iFace] : 0;
8504
8505   distance -= segLen;
8506
8507   if ( segmentIntersected )
8508   {
8509 #ifdef __myDEBUG
8510     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
8511     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * ( distance+segLen ));
8512     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
8513          << ", intersection with face ("
8514          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
8515          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
8516          << ") distance = " << distance << endl;
8517 #endif
8518   }
8519
8520   return segmentIntersected;
8521 }
8522
8523 //================================================================================
8524 /*!
8525  * \brief Returns a point used to check orientation of _simplices
8526  */
8527 //================================================================================
8528
8529 gp_XYZ _LayerEdge::PrevCheckPos( _EdgesOnShape* eos ) const
8530 {
8531   size_t i = Is( NORMAL_UPDATED ) && IsOnFace() ? _pos.size()-2 : 0;
8532
8533   if ( !eos || eos->_sWOL.IsNull() )
8534     return _pos[ i ];
8535
8536   if ( eos->SWOLType() == TopAbs_EDGE )
8537   {
8538     return BRepAdaptor_Curve( TopoDS::Edge( eos->_sWOL )).Value( _pos[i].X() ).XYZ();
8539   }
8540   //else //  TopAbs_FACE
8541
8542   return BRepAdaptor_Surface( TopoDS::Face( eos->_sWOL )).Value(_pos[i].X(), _pos[i].Y() ).XYZ();
8543 }
8544
8545 //================================================================================
8546 /*!
8547  * \brief Returns size and direction of the last segment
8548  */
8549 //================================================================================
8550
8551 gp_Ax1 _LayerEdge::LastSegment(double& segLen, _EdgesOnShape& eos) const
8552 {
8553   // find two non-coincident positions
8554   gp_XYZ orig = _pos.back();
8555   gp_XYZ vec;
8556   int iPrev = _pos.size() - 2;
8557   //const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
8558   const double tol = ( _len > 0 ) ? ( 1e-6 * _len ) : 1e-100;
8559   while ( iPrev >= 0 )
8560   {
8561     vec = orig - _pos[iPrev];
8562     if ( vec.SquareModulus() > tol*tol )
8563       break;
8564     else
8565       iPrev--;
8566   }
8567
8568   // make gp_Ax1
8569   gp_Ax1 segDir;
8570   if ( iPrev < 0 )
8571   {
8572     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
8573     segDir.SetDirection( _normal );
8574     segLen = 0;
8575   }
8576   else
8577   {
8578     gp_Pnt pPrev = _pos[ iPrev ];
8579     if ( !eos._sWOL.IsNull() )
8580     {
8581       TopLoc_Location loc;
8582       if ( eos.SWOLType() == TopAbs_EDGE )
8583       {
8584         double f,l;
8585         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
8586         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
8587       }
8588       else
8589       {
8590         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( eos._sWOL ), loc );
8591         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
8592       }
8593       vec = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
8594     }
8595     segDir.SetLocation( pPrev );
8596     segDir.SetDirection( vec );
8597     segLen = vec.Modulus();
8598   }
8599
8600   return segDir;
8601 }
8602
8603 //================================================================================
8604 /*!
8605  * \brief Return the last (or \a which) position of the target node on a FACE. 
8606  *  \param [in] F - the FACE this _LayerEdge is inflated along
8607  *  \param [in] which - index of position
8608  *  \return gp_XY - result UV
8609  */
8610 //================================================================================
8611
8612 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F, _EdgesOnShape& eos, int which ) const
8613 {
8614   if ( F.IsSame( eos._sWOL )) // F is my FACE
8615     return gp_XY( _pos.back().X(), _pos.back().Y() );
8616
8617   if ( eos.SWOLType() != TopAbs_EDGE ) // wrong call
8618     return gp_XY( 1e100, 1e100 );
8619
8620   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
8621   double f, l, u = _pos[ which < 0 ? _pos.size()-1 : which ].X();
8622   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(eos._sWOL), F, f,l);
8623   if ( !C2d.IsNull() && f <= u && u <= l )
8624     return C2d->Value( u ).XY();
8625
8626   return gp_XY( 1e100, 1e100 );
8627 }
8628
8629 //================================================================================
8630 /*!
8631  * \brief Test intersection of the last segment with a given triangle
8632  *   using Moller-Trumbore algorithm
8633  * Intersection is detected if distance to intersection is less than _LayerEdge._len
8634  */
8635 //================================================================================
8636
8637 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
8638                                const gp_XYZ& vert0,
8639                                const gp_XYZ& vert1,
8640                                const gp_XYZ& vert2,
8641                                double&       t,
8642                                const double& EPSILON) const
8643 {
8644   const gp_Pnt& orig = lastSegment.Location();
8645   const gp_Dir& dir  = lastSegment.Direction();
8646
8647   /* calculate distance from vert0 to ray origin */
8648   //gp_XYZ tvec = orig.XYZ() - vert0;
8649
8650   //if ( tvec * dir > EPSILON )
8651     // intersected face is at back side of the temporary face this _LayerEdge belongs to
8652     //return false;
8653
8654   gp_XYZ edge1 = vert1 - vert0;
8655   gp_XYZ edge2 = vert2 - vert0;
8656
8657   /* begin calculating determinant - also used to calculate U parameter */
8658   gp_XYZ pvec = dir.XYZ() ^ edge2;
8659
8660   /* if determinant is near zero, ray lies in plane of triangle */
8661   double det = edge1 * pvec;
8662
8663   const double ANGL_EPSILON = 1e-12;
8664   if ( det > -ANGL_EPSILON && det < ANGL_EPSILON )
8665     return false;
8666
8667   /* calculate distance from vert0 to ray origin */
8668   gp_XYZ tvec = orig.XYZ() - vert0;
8669
8670   /* calculate U parameter and test bounds */
8671   double u = ( tvec * pvec ) / det;
8672   //if (u < 0.0 || u > 1.0)
8673   if ( u < -EPSILON || u > 1.0 + EPSILON )
8674     return false;
8675
8676   /* prepare to test V parameter */
8677   gp_XYZ qvec = tvec ^ edge1;
8678
8679   /* calculate V parameter and test bounds */
8680   double v = (dir.XYZ() * qvec) / det;
8681   //if ( v < 0.0 || u + v > 1.0 )
8682   if ( v < -EPSILON || u + v > 1.0 + EPSILON )
8683     return false;
8684
8685   /* calculate t, ray intersects triangle */
8686   t = (edge2 * qvec) / det;
8687
8688   //return true;
8689   return t > 0.;
8690 }
8691
8692 //================================================================================
8693 /*!
8694  * \brief _LayerEdge, located at a concave VERTEX of a FACE, moves target nodes of
8695  *        neighbor _LayerEdge's by it's own inflation vector.
8696  *  \param [in] eov - EOS of the VERTEX
8697  *  \param [in] eos - EOS of the FACE
8698  *  \param [in] step - inflation step
8699  *  \param [in,out] badSmooEdges - tangled _LayerEdge's
8700  */
8701 //================================================================================
8702
8703 void _LayerEdge::MoveNearConcaVer( const _EdgesOnShape*    eov,
8704                                    const _EdgesOnShape*    eos,
8705                                    const int               step,
8706                                    vector< _LayerEdge* > & badSmooEdges )
8707 {
8708   // check if any of _neibors is in badSmooEdges
8709   if ( std::find_first_of( _neibors.begin(), _neibors.end(),
8710                            badSmooEdges.begin(), badSmooEdges.end() ) == _neibors.end() )
8711     return;
8712
8713   // get all edges to move
8714
8715   set< _LayerEdge* > edges;
8716
8717   // find a distance between _LayerEdge on VERTEX and its neighbors
8718   gp_XYZ  curPosV = SMESH_TNodeXYZ( _nodes.back() );
8719   double dist2 = 0;
8720   for ( size_t i = 0; i < _neibors.size(); ++i )
8721   {
8722     _LayerEdge* nEdge = _neibors[i];
8723     if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID )
8724     {
8725       edges.insert( nEdge );
8726       dist2 = Max( dist2, ( curPosV - nEdge->_pos.back() ).SquareModulus() );
8727     }
8728   }
8729   // add _LayerEdge's close to curPosV
8730   size_t nbE;
8731   do {
8732     nbE = edges.size();
8733     for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8734     {
8735       _LayerEdge* edgeF = *e;
8736       for ( size_t i = 0; i < edgeF->_neibors.size(); ++i )
8737       {
8738         _LayerEdge* nEdge = edgeF->_neibors[i];
8739         if ( nEdge->_nodes[0]->getshapeId() == eos->_shapeID &&
8740              dist2 > ( curPosV - nEdge->_pos.back() ).SquareModulus() )
8741           edges.insert( nEdge );
8742       }
8743     }
8744   }
8745   while ( nbE < edges.size() );
8746
8747   // move the target node of the got edges
8748
8749   gp_XYZ prevPosV = PrevPos();
8750   if ( eov->SWOLType() == TopAbs_EDGE )
8751   {
8752     BRepAdaptor_Curve curve ( TopoDS::Edge( eov->_sWOL ));
8753     prevPosV = curve.Value( prevPosV.X() ).XYZ();
8754   }
8755   else if ( eov->SWOLType() == TopAbs_FACE )
8756   {
8757     BRepAdaptor_Surface surface( TopoDS::Face( eov->_sWOL ));
8758     prevPosV = surface.Value( prevPosV.X(), prevPosV.Y() ).XYZ();
8759   }
8760
8761   SMDS_FacePositionPtr fPos;
8762   //double r = 1. - Min( 0.9, step / 10. );
8763   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8764   {
8765     _LayerEdge*       edgeF = *e;
8766     const gp_XYZ     prevVF = edgeF->PrevPos() - prevPosV;
8767     const gp_XYZ    newPosF = curPosV + prevVF;
8768     SMDS_MeshNode* tgtNodeF = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8769     tgtNodeF->setXYZ( newPosF.X(), newPosF.Y(), newPosF.Z() );
8770     edgeF->_pos.back() = newPosF;
8771     dumpMoveComm( tgtNodeF, "MoveNearConcaVer" ); // debug
8772
8773     // set _curvature to make edgeF updated by putOnOffsetSurface()
8774     if ( !edgeF->_curvature )
8775       if (( fPos = edgeF->_nodes[0]->GetPosition() ))
8776       {
8777         edgeF->_curvature = _Factory::NewCurvature();
8778         edgeF->_curvature->_r = 0;
8779         edgeF->_curvature->_k = 0;
8780         edgeF->_curvature->_h2lenRatio = 0;
8781         edgeF->_curvature->_uv.SetCoord( fPos->GetUParameter(), fPos->GetVParameter() );
8782       }
8783   }
8784   // gp_XYZ inflationVec( SMESH_TNodeXYZ( _nodes.back() ) -
8785   //                      SMESH_TNodeXYZ( _nodes[0]    ));
8786   // for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8787   // {
8788   //   _LayerEdge*      edgeF = *e;
8789   //   gp_XYZ          newPos = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8790   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8791   //   tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8792   //   edgeF->_pos.back() = newPosF;
8793   //   dumpMoveComm( tgtNode, "MoveNearConcaVer" ); // debug
8794   // }
8795
8796   // smooth _LayerEdge's around moved nodes
8797   //size_t nbBadBefore = badSmooEdges.size();
8798   for ( set< _LayerEdge* >::iterator e = edges.begin(); e != edges.end(); ++e )
8799   {
8800     _LayerEdge* edgeF = *e;
8801     for ( size_t j = 0; j < edgeF->_neibors.size(); ++j )
8802       if ( edgeF->_neibors[j]->_nodes[0]->getshapeId() == eos->_shapeID )
8803         //&& !edges.count( edgeF->_neibors[j] ))
8804       {
8805         _LayerEdge* edgeFN = edgeF->_neibors[j];
8806         edgeFN->Unset( SMOOTHED );
8807         int nbBad = edgeFN->Smooth( step, /*isConcaFace=*/true, /*findBest=*/true );
8808         // if ( nbBad > 0 )
8809         // {
8810         //   gp_XYZ         newPos = SMESH_TNodeXYZ( edgeFN->_nodes[0] ) + inflationVec;
8811         //   const gp_XYZ& prevPos = edgeFN->_pos[ edgeFN->_pos.size()-2 ];
8812         //   int        nbBadAfter = edgeFN->_simplices.size();
8813         //   double vol;
8814         //   for ( size_t iS = 0; iS < edgeFN->_simplices.size(); ++iS )
8815         //   {
8816         //     nbBadAfter -= edgeFN->_simplices[iS].IsForward( &prevPos, &newPos, vol );
8817         //   }
8818         //   if ( nbBadAfter <= nbBad )
8819         //   {
8820         //     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeFN->_nodes.back() );
8821         //     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8822         //     edgeF->_pos.back() = newPosF;
8823         //     dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8824         //     nbBad = nbBadAfter;
8825         //   }
8826         // }
8827         if ( nbBad > 0 )
8828           badSmooEdges.push_back( edgeFN );
8829       }
8830   }
8831     // move a bit not smoothed around moved nodes
8832   //   for ( size_t i = nbBadBefore; i < badSmooEdges.size(); ++i )
8833   //   {
8834   //   _LayerEdge*      edgeF = badSmooEdges[i];
8835   //   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edgeF->_nodes.back() );
8836   //   gp_XYZ         newPos1 = SMESH_TNodeXYZ( edgeF->_nodes[0] ) + inflationVec;
8837   //   gp_XYZ         newPos2 = 0.5 * ( newPos1 + SMESH_TNodeXYZ( tgtNode ));
8838   //   tgtNode->setXYZ( newPos2.X(), newPos2.Y(), newPos2.Z() );
8839   //   edgeF->_pos.back() = newPosF;
8840   //   dumpMoveComm( tgtNode, "MoveNearConcaVer 2" ); // debug
8841   // }
8842 }
8843
8844 //================================================================================
8845 /*!
8846  * \brief Perform smooth of _LayerEdge's based on EDGE's
8847  *  \retval bool - true if node has been moved
8848  */
8849 //================================================================================
8850
8851 bool _LayerEdge::SmoothOnEdge(Handle(ShapeAnalysis_Surface)& surface,
8852                               const TopoDS_Face&             F,
8853                               SMESH_MesherHelper&            helper)
8854 {
8855   ASSERT( IsOnEdge() );
8856
8857   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
8858   SMESH_TNodeXYZ oldPos( tgtNode );
8859   double dist01, distNewOld;
8860   
8861   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
8862   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
8863   dist01 = p0.Distance( _2neibors->tgtNode(1) );
8864
8865   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
8866   double lenDelta = 0;
8867   if ( _curvature )
8868   {
8869     //lenDelta = _curvature->lenDelta( _len );
8870     lenDelta = _curvature->lenDeltaByDist( dist01 );
8871     newPos.ChangeCoord() += _normal * lenDelta;
8872   }
8873
8874   distNewOld = newPos.Distance( oldPos );
8875
8876   if ( F.IsNull() )
8877   {
8878     if ( _2neibors->_plnNorm )
8879     {
8880       // put newPos on the plane defined by source node and _plnNorm
8881       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
8882       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
8883       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
8884     }
8885     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8886     _pos.back() = newPos.XYZ();
8887   }
8888   else
8889   {
8890     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8891     gp_XY uv( Precision::Infinite(), 0 );
8892     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
8893     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
8894
8895     newPos = surface->Value( uv );
8896     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
8897   }
8898
8899   // commented for IPAL0052478
8900   // if ( _curvature && lenDelta < 0 )
8901   // {
8902   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
8903   //   _len -= prevPos.Distance( oldPos );
8904   //   _len += prevPos.Distance( newPos );
8905   // }
8906   bool moved = distNewOld > dist01/50;
8907   //if ( moved )
8908   dumpMove( tgtNode ); // debug
8909
8910   return moved;
8911 }
8912
8913 //================================================================================
8914 /*!
8915  * \brief Perform 3D smooth of nodes inflated from FACE. No check of validity
8916  */
8917 //================================================================================
8918
8919 void _LayerEdge::SmoothWoCheck()
8920 {
8921   if ( Is( DIFFICULT ))
8922     return;
8923
8924   bool moved = Is( SMOOTHED );
8925   for ( size_t i = 0; i < _neibors.size()  &&  !moved; ++i )
8926     moved = _neibors[i]->Is( SMOOTHED );
8927   if ( !moved )
8928     return;
8929
8930   gp_XYZ newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
8931
8932   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
8933   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
8934   _pos.back() = newPos;
8935
8936   dumpMoveComm( n, SMESH_Comment("No check - ") << _funNames[ smooFunID() ]);
8937 }
8938
8939 //================================================================================
8940 /*!
8941  * \brief Checks validity of _neibors on EDGEs and VERTEXes
8942  */
8943 //================================================================================
8944
8945 int _LayerEdge::CheckNeiborsOnBoundary( vector< _LayerEdge* >* badNeibors, bool * needSmooth )
8946 {
8947   if ( ! Is( NEAR_BOUNDARY ))
8948     return 0;
8949
8950   int nbBad = 0;
8951   double vol;
8952   for ( size_t iN = 0; iN < _neibors.size(); ++iN )
8953   {
8954     _LayerEdge* eN = _neibors[iN];
8955     if ( eN->_nodes[0]->getshapeId() == _nodes[0]->getshapeId() )
8956       continue;
8957     if ( needSmooth )
8958       *needSmooth |= ( eN->Is( _LayerEdge::BLOCKED ) ||
8959                        eN->Is( _LayerEdge::NORMAL_UPDATED ) ||
8960                        eN->_pos.size() != _pos.size() );
8961
8962     SMESH_TNodeXYZ curPosN ( eN->_nodes.back() );
8963     SMESH_TNodeXYZ prevPosN( eN->_nodes[0] );
8964     for ( size_t i = 0; i < eN->_simplices.size(); ++i )
8965       if ( eN->_nodes.size() > 1 &&
8966            eN->_simplices[i].Includes( _nodes.back() ) &&
8967            !eN->_simplices[i].IsForward( &prevPosN, &curPosN, vol ))
8968       {
8969         ++nbBad;
8970         if ( badNeibors )
8971         {
8972           badNeibors->push_back( eN );
8973           debugMsg("Bad boundary simplex ( "
8974                    << " "<< eN->_nodes[0]->GetID()
8975                    << " "<< eN->_nodes.back()->GetID()
8976                    << " "<< eN->_simplices[i]._nPrev->GetID()
8977                    << " "<< eN->_simplices[i]._nNext->GetID() << " )" );
8978         }
8979         else
8980         {
8981           break;
8982         }
8983       }
8984   }
8985   return nbBad;
8986 }
8987
8988 //================================================================================
8989 /*!
8990  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
8991  *  \retval int - nb of bad simplices around this _LayerEdge
8992  */
8993 //================================================================================
8994
8995 int _LayerEdge::Smooth(const int step, bool findBest, vector< _LayerEdge* >& toSmooth )
8996 {
8997   if ( !Is( MOVED ) || Is( SMOOTHED ) || Is( BLOCKED ))
8998     return 0; // shape of simplices not changed
8999   if ( _simplices.size() < 2 )
9000     return 0; // _LayerEdge inflated along EDGE or FACE
9001
9002   if ( Is( DIFFICULT )) // || Is( ON_CONCAVE_FACE )
9003     findBest = true;
9004
9005   const gp_XYZ& curPos  = _pos.back();
9006   const gp_XYZ& prevPos = _pos[0]; //PrevPos();
9007
9008   // quality metrics (orientation) of tetras around _tgtNode
9009   int nbOkBefore = 0;
9010   double vol, minVolBefore = 1e100;
9011   for ( size_t i = 0; i < _simplices.size(); ++i )
9012   {
9013     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9014     minVolBefore = Min( minVolBefore, vol );
9015   }
9016   int nbBad = _simplices.size() - nbOkBefore;
9017
9018   bool bndNeedSmooth = false;
9019   if ( nbBad == 0 )
9020     nbBad = CheckNeiborsOnBoundary( 0, & bndNeedSmooth );
9021   if ( nbBad > 0 )
9022     Set( DISTORTED );
9023
9024   // evaluate min angle
9025   if ( nbBad == 0 && !findBest && !bndNeedSmooth )
9026   {
9027     size_t nbGoodAngles = _simplices.size();
9028     double angle;
9029     for ( size_t i = 0; i < _simplices.size(); ++i )
9030     {
9031       if ( !_simplices[i].IsMinAngleOK( curPos, angle ) && angle > _minAngle )
9032         --nbGoodAngles;
9033     }
9034     if ( nbGoodAngles == _simplices.size() )
9035     {
9036       Unset( MOVED );
9037       return 0;
9038     }
9039   }
9040   if ( Is( ON_CONCAVE_FACE ))
9041     findBest = true;
9042
9043   if ( step % 2 == 0 )
9044     findBest = false;
9045
9046   if ( Is( ON_CONCAVE_FACE ) && !findBest ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9047   {
9048     if ( _smooFunction == _funs[ FUN_LAPLACIAN ] )
9049       _smooFunction = _funs[ FUN_CENTROIDAL ];
9050     else
9051       _smooFunction = _funs[ FUN_LAPLACIAN ];
9052   }
9053
9054   // compute new position for the last _pos using different _funs
9055   gp_XYZ newPos;
9056   bool moved = false;
9057   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9058   {
9059     if ( iFun < 0 )
9060       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9061     else if ( _funs[ iFun ] == _smooFunction )
9062       continue; // _smooFunction again
9063     else if ( step > 1 )
9064       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9065     else
9066       break; // let "easy" functions improve elements around distorted ones
9067
9068     if ( _curvature )
9069     {
9070       double delta  = _curvature->lenDelta( _len );
9071       if ( delta > 0 )
9072         newPos += _normal * delta;
9073       else
9074       {
9075         double segLen = _normal * ( newPos - prevPos );
9076         if ( segLen + delta > 0 )
9077           newPos += _normal * delta;
9078       }
9079       // double segLenChange = _normal * ( curPos - newPos );
9080       // newPos += 0.5 * _normal * segLenChange;
9081     }
9082
9083     int nbOkAfter = 0;
9084     double minVolAfter = 1e100;
9085     for ( size_t i = 0; i < _simplices.size(); ++i )
9086     {
9087       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9088       minVolAfter = Min( minVolAfter, vol );
9089     }
9090     // get worse?
9091     if ( nbOkAfter < nbOkBefore )
9092       continue;
9093
9094     if (( findBest ) &&
9095         ( nbOkAfter == nbOkBefore ) &&
9096         ( minVolAfter <= minVolBefore ))
9097       continue;
9098
9099     nbBad        = _simplices.size() - nbOkAfter;
9100     minVolBefore = minVolAfter;
9101     nbOkBefore   = nbOkAfter;
9102     moved        = true;
9103
9104     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9105     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9106     _pos.back() = newPos;
9107
9108     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9109                   << (nbBad ? " --BAD" : ""));
9110
9111     if ( iFun > -1 )
9112     {
9113       continue; // look for a better function
9114     }
9115
9116     if ( !findBest )
9117       break;
9118
9119   } // loop on smoothing functions
9120
9121   if ( moved ) // notify _neibors
9122   {
9123     Set( SMOOTHED );
9124     for ( size_t i = 0; i < _neibors.size(); ++i )
9125       if ( !_neibors[i]->Is( MOVED ))
9126       {
9127         _neibors[i]->Set( MOVED );
9128         toSmooth.push_back( _neibors[i] );
9129       }
9130   }
9131
9132   return nbBad;
9133 }
9134
9135 //================================================================================
9136 /*!
9137  * \brief Perform 'smart' 3D smooth of nodes inflated from FACE
9138  *  \retval int - nb of bad simplices around this _LayerEdge
9139  */
9140 //================================================================================
9141
9142 int _LayerEdge::Smooth(const int step, const bool isConcaveFace, bool findBest )
9143 {
9144   if ( !_smooFunction )
9145     return 0; // _LayerEdge inflated along EDGE or FACE
9146   if ( Is( BLOCKED ))
9147     return 0; // not inflated
9148
9149   const gp_XYZ& curPos  = _pos.back();
9150   const gp_XYZ& prevPos = _pos[0]; //PrevCheckPos();
9151
9152   // quality metrics (orientation) of tetras around _tgtNode
9153   int nbOkBefore = 0;
9154   double vol, minVolBefore = 1e100;
9155   for ( size_t i = 0; i < _simplices.size(); ++i )
9156   {
9157     nbOkBefore += _simplices[i].IsForward( &prevPos, &curPos, vol );
9158     minVolBefore = Min( minVolBefore, vol );
9159   }
9160   int nbBad = _simplices.size() - nbOkBefore;
9161
9162   if ( isConcaveFace ) // alternate FUN_CENTROIDAL and FUN_LAPLACIAN
9163   {
9164     if      ( _smooFunction == _funs[ FUN_CENTROIDAL ] && step % 2 )
9165       _smooFunction = _funs[ FUN_LAPLACIAN ];
9166     else if ( _smooFunction == _funs[ FUN_LAPLACIAN ] && !( step % 2 ))
9167       _smooFunction = _funs[ FUN_CENTROIDAL ];
9168   }
9169
9170   // compute new position for the last _pos using different _funs
9171   gp_XYZ newPos;
9172   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
9173   {
9174     if ( iFun < 0 )
9175       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
9176     else if ( _funs[ iFun ] == _smooFunction )
9177       continue; // _smooFunction again
9178     else if ( step > 1 )
9179       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
9180     else
9181       break; // let "easy" functions improve elements around distorted ones
9182
9183     if ( _curvature )
9184     {
9185       double delta  = _curvature->lenDelta( _len );
9186       if ( delta > 0 )
9187         newPos += _normal * delta;
9188       else
9189       {
9190         double segLen = _normal * ( newPos - prevPos );
9191         if ( segLen + delta > 0 )
9192           newPos += _normal * delta;
9193       }
9194       // double segLenChange = _normal * ( curPos - newPos );
9195       // newPos += 0.5 * _normal * segLenChange;
9196     }
9197
9198     int nbOkAfter = 0;
9199     double minVolAfter = 1e100;
9200     for ( size_t i = 0; i < _simplices.size(); ++i )
9201     {
9202       nbOkAfter += _simplices[i].IsForward( &prevPos, &newPos, vol );
9203       minVolAfter = Min( minVolAfter, vol );
9204     }
9205     // get worse?
9206     if ( nbOkAfter < nbOkBefore )
9207       continue;
9208     if (( isConcaveFace || findBest ) &&
9209         ( nbOkAfter == nbOkBefore ) &&
9210         ( minVolAfter <= minVolBefore )
9211         )
9212       continue;
9213
9214     nbBad        = _simplices.size() - nbOkAfter;
9215     minVolBefore = minVolAfter;
9216     nbOkBefore   = nbOkAfter;
9217
9218     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
9219     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
9220     _pos.back() = newPos;
9221
9222     dumpMoveComm( n, SMESH_Comment( _funNames[ iFun < 0 ? smooFunID() : iFun ] )
9223                   << ( nbBad ? "--BAD" : ""));
9224
9225     // commented for IPAL0052478
9226     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
9227     // _len += prevPos.Distance(newPos);
9228
9229     if ( iFun > -1 ) // findBest || the chosen _fun makes worse
9230     {
9231       //_smooFunction = _funs[ iFun ];
9232       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
9233       // << "\t nbBad: " << _simplices.size() - nbOkAfter
9234       // << " minVol: " << minVolAfter
9235       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
9236       // << endl;
9237       continue; // look for a better function
9238     }
9239
9240     if ( !findBest )
9241       break;
9242
9243   } // loop on smoothing functions
9244
9245   return nbBad;
9246 }
9247
9248 //================================================================================
9249 /*!
9250  * \brief Chooses a smoothing technique giving a position most close to an initial one.
9251  *        For a correct result, _simplices must contain nodes lying on geometry.
9252  */
9253 //================================================================================
9254
9255 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
9256                                      const TNode2Edge&     /*n2eMap*/)
9257 {
9258   if ( _smooFunction ) return;
9259
9260   // use smoothNefPolygon() near concaveVertices
9261   if ( !concaveVertices.empty() )
9262   {
9263     _smooFunction = _funs[ FUN_CENTROIDAL ];
9264
9265     Set( ON_CONCAVE_FACE );
9266
9267     for ( size_t i = 0; i < _simplices.size(); ++i )
9268     {
9269       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
9270       {
9271         _smooFunction = _funs[ FUN_NEFPOLY ];
9272
9273         // set FUN_CENTROIDAL to neighbor edges
9274         for ( i = 0; i < _neibors.size(); ++i )
9275         {
9276           if ( _neibors[i]->_nodes[0]->GetPosition()->GetDim() == 2 )
9277           {
9278             _neibors[i]->_smooFunction = _funs[ FUN_CENTROIDAL ];
9279           }
9280         }
9281         return;
9282       }
9283     }
9284
9285     // // this choice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
9286     // // where the nodes are smoothed too far along a sphere thus creating
9287     // // inverted _simplices
9288     // double dist[theNbSmooFuns];
9289     // //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
9290     // double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
9291
9292     // double minDist = Precision::Infinite();
9293     // gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
9294     // for ( int i = 0; i < FUN_NEFPOLY; ++i )
9295     // {
9296     //   gp_Pnt newP = (this->*_funs[i])();
9297     //   dist[i] = p.SquareDistance( newP );
9298     //   if ( dist[i]*coef[i] < minDist )
9299     //   {
9300     //     _smooFunction = _funs[i];
9301     //     minDist = dist[i]*coef[i];
9302     //   }
9303     // }
9304   }
9305   else
9306   {
9307     _smooFunction = _funs[ FUN_LAPLACIAN ];
9308   }
9309   // int minDim = 3;
9310   // for ( size_t i = 0; i < _simplices.size(); ++i )
9311   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
9312   // if ( minDim == 0 )
9313   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
9314   // else if ( minDim == 1 )
9315   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
9316
9317
9318   // int iMin;
9319   // for ( int i = 0; i < FUN_NB; ++i )
9320   // {
9321   //   //cout << dist[i] << " ";
9322   //   if ( _smooFunction == _funs[i] ) {
9323   //     iMin = i;
9324   //     //debugMsg( fNames[i] );
9325   //     break;
9326   //   }
9327   // }
9328   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
9329 }
9330
9331 //================================================================================
9332 /*!
9333  * \brief Returns a name of _SmooFunction
9334  */
9335 //================================================================================
9336
9337 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
9338 {
9339   if ( !fun )
9340     fun = _smooFunction;
9341   for ( int i = 0; i < theNbSmooFuns; ++i )
9342     if ( fun == _funs[i] )
9343       return i;
9344
9345   return theNbSmooFuns;
9346 }
9347
9348 //================================================================================
9349 /*!
9350  * \brief Computes a new node position using Laplacian smoothing
9351  */
9352 //================================================================================
9353
9354 gp_XYZ _LayerEdge::smoothLaplacian()
9355 {
9356   gp_XYZ newPos (0,0,0);
9357   for ( size_t i = 0; i < _simplices.size(); ++i )
9358     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9359   newPos /= _simplices.size();
9360
9361   return newPos;
9362 }
9363
9364 //================================================================================
9365 /*!
9366  * \brief Computes a new node position using angular-based smoothing
9367  */
9368 //================================================================================
9369
9370 gp_XYZ _LayerEdge::smoothAngular()
9371 {
9372   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1 );
9373   vector< double > edgeSize; edgeSize.reserve( _simplices.size()     );
9374   vector< gp_XYZ > points;   points.  reserve( _simplices.size() + 1 );
9375
9376   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9377   gp_XYZ pN( 0,0,0 );
9378   for ( size_t i = 0; i < _simplices.size(); ++i )
9379   {
9380     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9381     edgeDir.push_back( p - pPrev );
9382     edgeSize.push_back( edgeDir.back().Magnitude() );
9383     if ( edgeSize.back() < numeric_limits<double>::min() )
9384     {
9385       edgeDir.pop_back();
9386       edgeSize.pop_back();
9387     }
9388     else
9389     {
9390       edgeDir.back() /= edgeSize.back();
9391       points.push_back( p );
9392       pN += p;
9393     }
9394     pPrev = p;
9395   }
9396   edgeDir.push_back ( edgeDir[0] );
9397   edgeSize.push_back( edgeSize[0] );
9398   pN /= points.size();
9399
9400   gp_XYZ newPos(0,0,0);
9401   double sumSize = 0;
9402   for ( size_t i = 0; i < points.size(); ++i )
9403   {
9404     gp_Vec toN    = pN - points[i];
9405     double toNLen = toN.Magnitude();
9406     if ( toNLen < numeric_limits<double>::min() )
9407     {
9408       newPos += pN;
9409       continue;
9410     }
9411     gp_Vec bisec    = edgeDir[i] + edgeDir[i+1];
9412     double bisecLen = bisec.SquareMagnitude();
9413     if ( bisecLen < numeric_limits<double>::min() )
9414     {
9415       gp_Vec norm = edgeDir[i] ^ toN;
9416       bisec = norm ^ edgeDir[i];
9417       bisecLen = bisec.SquareMagnitude();
9418     }
9419     bisecLen = Sqrt( bisecLen );
9420     bisec /= bisecLen;
9421
9422 #if 1
9423     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
9424     sumSize += bisecLen;
9425 #else
9426     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
9427     sumSize += ( edgeSize[i] + edgeSize[i+1] );
9428 #endif
9429     newPos += pNew;
9430   }
9431   newPos /= sumSize;
9432
9433   // project newPos to an average plane
9434
9435   gp_XYZ norm(0,0,0); // plane normal
9436   points.push_back( points[0] );
9437   for ( size_t i = 1; i < points.size(); ++i )
9438   {
9439     gp_XYZ vec1 = points[ i-1 ] - pN;
9440     gp_XYZ vec2 = points[ i   ] - pN;
9441     gp_XYZ cross = vec1 ^ vec2;
9442     try {
9443       cross.Normalize();
9444       if ( cross * norm < numeric_limits<double>::min() )
9445         norm += cross.Reversed();
9446       else
9447         norm += cross;
9448     }
9449     catch (Standard_Failure&) { // if |cross| == 0.
9450     }
9451   }
9452   gp_XYZ vec = newPos - pN;
9453   double r   = ( norm * vec ) / norm.SquareModulus();  // param [0,1] on norm
9454   newPos     = newPos - r * norm;
9455
9456   return newPos;
9457 }
9458
9459 //================================================================================
9460 /*!
9461  * \brief Computes a new node position using weighted node positions
9462  */
9463 //================================================================================
9464
9465 gp_XYZ _LayerEdge::smoothLengthWeighted()
9466 {
9467   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
9468   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
9469
9470   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
9471   for ( size_t i = 0; i < _simplices.size(); ++i )
9472   {
9473     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9474     edgeSize.push_back( ( p - pPrev ).Modulus() );
9475     if ( edgeSize.back() < numeric_limits<double>::min() )
9476     {
9477       edgeSize.pop_back();
9478     }
9479     else
9480     {
9481       points.push_back( p );
9482     }
9483     pPrev = p;
9484   }
9485   edgeSize.push_back( edgeSize[0] );
9486
9487   gp_XYZ newPos(0,0,0);
9488   double sumSize = 0;
9489   for ( size_t i = 0; i < points.size(); ++i )
9490   {
9491     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
9492     sumSize += edgeSize[i] + edgeSize[i+1];
9493   }
9494   newPos /= sumSize;
9495   return newPos;
9496 }
9497
9498 //================================================================================
9499 /*!
9500  * \brief Computes a new node position using angular-based smoothing
9501  */
9502 //================================================================================
9503
9504 gp_XYZ _LayerEdge::smoothCentroidal()
9505 {
9506   gp_XYZ newPos(0,0,0);
9507   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
9508   double sumSize = 0;
9509   for ( size_t i = 0; i < _simplices.size(); ++i )
9510   {
9511     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
9512     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
9513     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
9514     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
9515
9516     sumSize += size;
9517     newPos += gc * size;
9518   }
9519   newPos /= sumSize;
9520
9521   return newPos;
9522 }
9523
9524 //================================================================================
9525 /*!
9526  * \brief Computes a new node position located inside a Nef polygon
9527  */
9528 //================================================================================
9529
9530 gp_XYZ _LayerEdge::smoothNefPolygon()
9531 #ifdef OLD_NEF_POLYGON
9532 {
9533   gp_XYZ newPos(0,0,0);
9534
9535   // get a plane to search a solution on
9536
9537   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9538   size_t i;
9539   const double tol = numeric_limits<double>::min();
9540   gp_XYZ center(0,0,0);
9541   for ( i = 0; i < _simplices.size(); ++i )
9542   {
9543     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
9544                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
9545     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9546   }
9547   vecs.back() = vecs[0];
9548   center /= _simplices.size();
9549
9550   gp_XYZ zAxis(0,0,0);
9551   for ( i = 0; i < _simplices.size(); ++i )
9552     zAxis += vecs[i] ^ vecs[i+1];
9553
9554   gp_XYZ yAxis;
9555   for ( i = 0; i < _simplices.size(); ++i )
9556   {
9557     yAxis = vecs[i];
9558     if ( yAxis.SquareModulus() > tol )
9559       break;
9560   }
9561   gp_XYZ xAxis = yAxis ^ zAxis;
9562   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9563   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9564   //                             p0.Distance( _simplices[2]._nPrev ));
9565   // gp_XYZ center = smoothLaplacian();
9566   // gp_XYZ xAxis, yAxis, zAxis;
9567   // for ( i = 0; i < _simplices.size(); ++i )
9568   // {
9569   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9570   //   if ( xAxis.SquareModulus() > tol*tol )
9571   //     break;
9572   // }
9573   // for ( i = 1; i < _simplices.size(); ++i )
9574   // {
9575   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9576   //   zAxis = xAxis ^ yAxis;
9577   //   if ( zAxis.SquareModulus() > tol*tol )
9578   //     break;
9579   // }
9580   // if ( i == _simplices.size() ) return newPos;
9581
9582   yAxis = zAxis ^ xAxis;
9583   xAxis /= xAxis.Modulus();
9584   yAxis /= yAxis.Modulus();
9585
9586   // get half-planes of _simplices
9587
9588   vector< _halfPlane > halfPlns( _simplices.size() );
9589   int nbHP = 0;
9590   for ( size_t i = 0; i < _simplices.size(); ++i )
9591   {
9592     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9593     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
9594     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9595     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9596     gp_XY  vec12 = p2 - p1;
9597     double dist12 = vec12.Modulus();
9598     if ( dist12 < tol )
9599       continue;
9600     vec12 /= dist12;
9601     halfPlns[ nbHP ]._pos = p1;
9602     halfPlns[ nbHP ]._dir = vec12;
9603     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9604     ++nbHP;
9605   }
9606
9607   // intersect boundaries of half-planes, define state of intersection points
9608   // in relation to all half-planes and calculate internal point of a 2D polygon
9609
9610   double sumLen = 0;
9611   gp_XY newPos2D (0,0);
9612
9613   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9614   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9615   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9616
9617   vector< vector< TIntPntState > > allIntPnts( nbHP );
9618   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9619   {
9620     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9621     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9622
9623     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9624     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9625
9626     int nbNotOut = 0;
9627     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9628
9629     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9630     {
9631       if ( iHP1 == iHP2 ) continue;
9632
9633       TIntPntState & ips1 = intPnts1[ iHP2 ];
9634       if ( ips1.second == UNDEF )
9635       {
9636         // find an intersection point of boundaries of iHP1 and iHP2
9637
9638         if ( iHP2 == iPrev ) // intersection with neighbors is known
9639           ips1.first = halfPlns[ iHP1 ]._pos;
9640         else if ( iHP2 == iNext )
9641           ips1.first = halfPlns[ iHP2 ]._pos;
9642         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9643           ips1.second = NO_INT;
9644
9645         // classify the found intersection point
9646         if ( ips1.second != NO_INT )
9647         {
9648           ips1.second = NOT_OUT;
9649           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9650             if ( i != iHP1 && i != iHP2 &&
9651                  halfPlns[ i ].IsOut( ips1.first, tol ))
9652               ips1.second = IS_OUT;
9653         }
9654         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9655         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9656         TIntPntState & ips2 = intPnts2[ iHP1 ];
9657         ips2 = ips1;
9658       }
9659       if ( ips1.second == NOT_OUT )
9660       {
9661         ++nbNotOut;
9662         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9663       }
9664     }
9665
9666     // find a NOT_OUT segment of boundary which is located between
9667     // two NOT_OUT int points
9668
9669     if ( nbNotOut < 2 )
9670       continue; // no such a segment
9671
9672     if ( nbNotOut > 2 )
9673     {
9674       // sort points along the boundary
9675       map< double, TIntPntState* > ipsByParam;
9676       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9677       {
9678         TIntPntState & ips1 = intPnts1[ iHP2 ];
9679         if ( ips1.second != NO_INT )
9680         {
9681           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9682           double param = op * halfPlns[ iHP1 ]._dir;
9683           ipsByParam.insert( make_pair( param, & ips1 ));
9684         }
9685       }
9686       // look for two neighboring NOT_OUT points
9687       nbNotOut = 0;
9688       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9689       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9690       {
9691         TIntPntState & ips1 = *(u2ips->second);
9692         if ( ips1.second == NOT_OUT )
9693           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9694         else if ( nbNotOut >= 2 )
9695           break;
9696         else
9697           nbNotOut = 0;
9698       }
9699     }
9700
9701     if ( nbNotOut >= 2 )
9702     {
9703       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9704       sumLen += len;
9705
9706       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9707     }
9708   }
9709
9710   if ( sumLen > 0 )
9711   {
9712     newPos2D /= sumLen;
9713     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9714   }
9715   else
9716   {
9717     newPos = center;
9718   }
9719
9720   return newPos;
9721 }
9722 #else // OLD_NEF_POLYGON
9723 { ////////////////////////////////// NEW
9724   gp_XYZ newPos(0,0,0);
9725
9726   // get a plane to search a solution on
9727
9728   size_t i;
9729   gp_XYZ center(0,0,0);
9730   for ( i = 0; i < _simplices.size(); ++i )
9731     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
9732   center /= _simplices.size();
9733
9734   vector< gp_XYZ > vecs( _simplices.size() + 1 );
9735   for ( i = 0; i < _simplices.size(); ++i )
9736     vecs[i] = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9737   vecs.back() = vecs[0];
9738
9739   const double tol = numeric_limits<double>::min();
9740   gp_XYZ zAxis(0,0,0);
9741   for ( i = 0; i < _simplices.size(); ++i )
9742   {
9743     gp_XYZ cross = vecs[i] ^ vecs[i+1];
9744     try {
9745       cross.Normalize();
9746       if ( cross * zAxis < tol )
9747         zAxis += cross.Reversed();
9748       else
9749         zAxis += cross;
9750     }
9751     catch (Standard_Failure) { // if |cross| == 0.
9752     }
9753   }
9754
9755   gp_XYZ yAxis;
9756   for ( i = 0; i < _simplices.size(); ++i )
9757   {
9758     yAxis = vecs[i];
9759     if ( yAxis.SquareModulus() > tol )
9760       break;
9761   }
9762   gp_XYZ xAxis = yAxis ^ zAxis;
9763   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
9764   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
9765   //                             p0.Distance( _simplices[2]._nPrev ));
9766   // gp_XYZ center = smoothLaplacian();
9767   // gp_XYZ xAxis, yAxis, zAxis;
9768   // for ( i = 0; i < _simplices.size(); ++i )
9769   // {
9770   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9771   //   if ( xAxis.SquareModulus() > tol*tol )
9772   //     break;
9773   // }
9774   // for ( i = 1; i < _simplices.size(); ++i )
9775   // {
9776   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
9777   //   zAxis = xAxis ^ yAxis;
9778   //   if ( zAxis.SquareModulus() > tol*tol )
9779   //     break;
9780   // }
9781   // if ( i == _simplices.size() ) return newPos;
9782
9783   yAxis = zAxis ^ xAxis;
9784   xAxis /= xAxis.Modulus();
9785   yAxis /= yAxis.Modulus();
9786
9787   // get half-planes of _simplices
9788
9789   vector< _halfPlane > halfPlns( _simplices.size() );
9790   int nbHP = 0;
9791   for ( size_t i = 0; i < _simplices.size(); ++i )
9792   {
9793     const gp_XYZ& OP1 = vecs[ i   ];
9794     const gp_XYZ& OP2 = vecs[ i+1 ];
9795     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
9796     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
9797     gp_XY  vec12 = p2 - p1;
9798     double dist12 = vec12.Modulus();
9799     if ( dist12 < tol )
9800       continue;
9801     vec12 /= dist12;
9802     halfPlns[ nbHP ]._pos = p1;
9803     halfPlns[ nbHP ]._dir = vec12;
9804     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
9805     ++nbHP;
9806   }
9807
9808   // intersect boundaries of half-planes, define state of intersection points
9809   // in relation to all half-planes and calculate internal point of a 2D polygon
9810
9811   double sumLen = 0;
9812   gp_XY newPos2D (0,0);
9813
9814   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
9815   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
9816   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
9817
9818   vector< vector< TIntPntState > > allIntPnts( nbHP );
9819   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
9820   {
9821     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
9822     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
9823
9824     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
9825     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
9826
9827     int nbNotOut = 0;
9828     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
9829
9830     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9831     {
9832       if ( iHP1 == iHP2 ) continue;
9833
9834       TIntPntState & ips1 = intPnts1[ iHP2 ];
9835       if ( ips1.second == UNDEF )
9836       {
9837         // find an intersection point of boundaries of iHP1 and iHP2
9838
9839         if ( iHP2 == iPrev ) // intersection with neighbors is known
9840           ips1.first = halfPlns[ iHP1 ]._pos;
9841         else if ( iHP2 == iNext )
9842           ips1.first = halfPlns[ iHP2 ]._pos;
9843         else if ( !halfPlns[ iHP1 ].FindIntersection( halfPlns[ iHP2 ], ips1.first ))
9844           ips1.second = NO_INT;
9845
9846         // classify the found intersection point
9847         if ( ips1.second != NO_INT )
9848         {
9849           ips1.second = NOT_OUT;
9850           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
9851             if ( i != iHP1 && i != iHP2 &&
9852                  halfPlns[ i ].IsOut( ips1.first, tol ))
9853               ips1.second = IS_OUT;
9854         }
9855         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
9856         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
9857         TIntPntState & ips2 = intPnts2[ iHP1 ];
9858         ips2 = ips1;
9859       }
9860       if ( ips1.second == NOT_OUT )
9861       {
9862         ++nbNotOut;
9863         segEnds[ bool(segEnds[0]) ] = & ips1.first;
9864       }
9865     }
9866
9867     // find a NOT_OUT segment of boundary which is located between
9868     // two NOT_OUT int points
9869
9870     if ( nbNotOut < 2 )
9871       continue; // no such a segment
9872
9873     if ( nbNotOut > 2 )
9874     {
9875       // sort points along the boundary
9876       map< double, TIntPntState* > ipsByParam;
9877       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
9878       {
9879         TIntPntState & ips1 = intPnts1[ iHP2 ];
9880         if ( ips1.second != NO_INT )
9881         {
9882           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
9883           double param = op * halfPlns[ iHP1 ]._dir;
9884           ipsByParam.insert( make_pair( param, & ips1 ));
9885         }
9886       }
9887       // look for two neighboring NOT_OUT points
9888       nbNotOut = 0;
9889       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
9890       for ( ; u2ips != ipsByParam.end(); ++u2ips )
9891       {
9892         TIntPntState & ips1 = *(u2ips->second);
9893         if ( ips1.second == NOT_OUT )
9894           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
9895         else if ( nbNotOut >= 2 )
9896           break;
9897         else
9898           nbNotOut = 0;
9899       }
9900     }
9901
9902     if ( nbNotOut >= 2 )
9903     {
9904       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
9905       sumLen += len;
9906
9907       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
9908     }
9909   }
9910
9911   if ( sumLen > 0 )
9912   {
9913     newPos2D /= sumLen;
9914     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
9915   }
9916   else
9917   {
9918     newPos = center;
9919   }
9920
9921   return newPos;
9922 }
9923 #endif // OLD_NEF_POLYGON
9924
9925 //================================================================================
9926 /*!
9927  * \brief Add a new segment to _LayerEdge during inflation
9928  */
9929 //================================================================================
9930
9931 void _LayerEdge::SetNewLength( double len, _EdgesOnShape& eos, SMESH_MesherHelper& helper )
9932 {
9933   if ( Is( BLOCKED ))
9934     return;
9935
9936   if ( len > _maxLen )
9937   {
9938     len = _maxLen;
9939     Block( eos.GetData() );
9940   }
9941   const double lenDelta = len - _len;
9942   // if ( lenDelta < 0 )
9943   //   return;
9944   if ( lenDelta < len * 1e-3  )
9945   {
9946     Block( eos.GetData() );
9947     return;
9948   }
9949
9950   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
9951   gp_XYZ oldXYZ = SMESH_TNodeXYZ( n );
9952   gp_XYZ newXYZ;
9953   if ( eos._hyp.IsOffsetMethod() )
9954   {
9955     newXYZ = oldXYZ;
9956     gp_Vec faceNorm;
9957     SMDS_ElemIteratorPtr faceIt = _nodes[0]->GetInverseElementIterator( SMDSAbs_Face );
9958     while ( faceIt->more() )
9959     {
9960       const SMDS_MeshElement* face = faceIt->next();
9961       if ( !eos.GetNormal( face, faceNorm ))
9962         continue;
9963
9964       // translate plane of a face
9965       gp_XYZ baryCenter = oldXYZ + faceNorm.XYZ() * lenDelta;
9966
9967       // find point of intersection of the face plane located at baryCenter
9968       // and _normal located at newXYZ
9969       double d   = -( faceNorm.XYZ() * baryCenter ); // d of plane equation ax+by+cz+d=0
9970       double dot =  ( faceNorm.XYZ() * _normal );
9971       if ( dot < std::numeric_limits<double>::min() )
9972         dot = lenDelta * 1e-3;
9973       double step = -( faceNorm.XYZ() * newXYZ + d ) / dot;
9974       newXYZ += step * _normal;
9975     }
9976     _lenFactor = _normal * ( newXYZ - oldXYZ ) / lenDelta; // _lenFactor is used in InvalidateStep()
9977   }
9978   else
9979   {
9980     newXYZ = oldXYZ + _normal * lenDelta * _lenFactor;
9981   }
9982
9983   n->setXYZ( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
9984   _pos.push_back( newXYZ );
9985
9986   if ( !eos._sWOL.IsNull() )
9987     if ( !UpdatePositionOnSWOL( n, 2*lenDelta, eos, helper ))
9988     {
9989       n->setXYZ( oldXYZ.X(), oldXYZ.Y(), oldXYZ.Z() );
9990       _pos.pop_back();
9991       Block( eos.GetData() );
9992       return;
9993     }
9994
9995   _len = len;
9996
9997   // notify _neibors
9998   if ( eos.ShapeType() != TopAbs_FACE )
9999   {
10000     for ( size_t i = 0; i < _neibors.size(); ++i )
10001       //if (  _len > _neibors[i]->GetSmooLen() )
10002       _neibors[i]->Set( MOVED );
10003
10004     Set( MOVED );
10005   }
10006   dumpMove( n ); //debug
10007 }
10008
10009
10010 //================================================================================
10011 /*!
10012  * \brief Update last position on SWOL by projecting node on SWOL
10013 */
10014 //================================================================================
10015
10016 bool _LayerEdge::UpdatePositionOnSWOL( SMDS_MeshNode*      n,
10017                                        double              tol,
10018                                        _EdgesOnShape&      eos,
10019                                        SMESH_MesherHelper& helper )
10020 {
10021   double distXYZ[4];
10022   bool uvOK = false;
10023   if ( eos.SWOLType() == TopAbs_EDGE )
10024   {
10025     double u = Precision::Infinite(); // to force projection w/o distance check
10026     uvOK = helper.CheckNodeU( TopoDS::Edge( eos._sWOL ), n, u, tol, /*force=*/true, distXYZ );
10027     _pos.back().SetCoord( u, 0, 0 );
10028     if ( _nodes.size() > 1 && uvOK )
10029     {
10030       SMDS_EdgePositionPtr pos = n->GetPosition();
10031       pos->SetUParameter( u );
10032     }
10033   }
10034   else //  TopAbs_FACE
10035   {
10036     gp_XY uv( Precision::Infinite(), 0 );
10037     uvOK = helper.CheckNodeUV( TopoDS::Face( eos._sWOL ), n, uv, tol, /*force=*/true, distXYZ );
10038     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
10039     if ( _nodes.size() > 1 && uvOK )
10040     {
10041       SMDS_FacePositionPtr pos = n->GetPosition();
10042       pos->SetUParameter( uv.X() );
10043       pos->SetVParameter( uv.Y() );
10044     }
10045   }
10046   if ( uvOK )
10047   {
10048     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
10049   }
10050   return uvOK;
10051 }
10052
10053 //================================================================================
10054 /*!
10055  * \brief Set BLOCKED flag and propagate limited _maxLen to _neibors
10056  */
10057 //================================================================================
10058
10059 void _LayerEdge::Block( _SolidData& data )
10060 {
10061   //if ( Is( BLOCKED )) return;
10062   Set( BLOCKED );
10063
10064   SMESH_Comment msg( "#BLOCK shape=");
10065   msg << data.GetShapeEdges( this )->_shapeID
10066       << ", nodes " << _nodes[0]->GetID() << ", " << _nodes.back()->GetID();
10067   dumpCmd( msg + " -- BEGIN");
10068
10069   SetMaxLen( _len );
10070   std::queue<_LayerEdge*> queue;
10071   queue.push( this );
10072
10073   gp_Pnt pSrc, pTgt, pSrcN, pTgtN;
10074   while ( !queue.empty() )
10075   {
10076     _LayerEdge* edge = queue.front(); queue.pop();
10077     pSrc = SMESH_TNodeXYZ( edge->_nodes[0] );
10078     pTgt = SMESH_TNodeXYZ( edge->_nodes.back() );
10079     for ( size_t iN = 0; iN < edge->_neibors.size(); ++iN )
10080     {
10081       _LayerEdge* neibor = edge->_neibors[iN];
10082       if ( neibor->_maxLen < edge->_maxLen * 1.01 )
10083         continue;
10084       pSrcN = SMESH_TNodeXYZ( neibor->_nodes[0] );
10085       pTgtN = SMESH_TNodeXYZ( neibor->_nodes.back() );
10086       double minDist = pSrc.SquareDistance( pSrcN );
10087       minDist   = Min( pTgt.SquareDistance( pTgtN ), minDist );
10088       minDist   = Min( pSrc.SquareDistance( pTgtN ), minDist );
10089       minDist   = Min( pTgt.SquareDistance( pSrcN ), minDist );
10090       double newMaxLen = edge->_maxLen + 0.5 * Sqrt( minDist );
10091       //if ( edge->_nodes[0]->getshapeId() == neibor->_nodes[0]->getshapeId() ) viscous_layers_00/A3
10092       {
10093         //newMaxLen *= edge->_lenFactor / neibor->_lenFactor;
10094         // newMaxLen *= Min( edge->_lenFactor / neibor->_lenFactor,
10095         //                   neibor->_lenFactor / edge->_lenFactor );
10096       }
10097       if ( neibor->_maxLen > newMaxLen )
10098       {
10099         neibor->SetMaxLen( newMaxLen );
10100         if ( neibor->_maxLen < neibor->_len )
10101         {
10102           _EdgesOnShape* eos = data.GetShapeEdges( neibor );
10103           int       lastStep = neibor->Is( BLOCKED ) ? 1 : 0;
10104           while ( neibor->_len > neibor->_maxLen &&
10105                   neibor->NbSteps() > lastStep )
10106             neibor->InvalidateStep( neibor->NbSteps(), *eos, /*restoreLength=*/true );
10107           neibor->SetNewLength( neibor->_maxLen, *eos, data.GetHelper() );
10108           //neibor->Block( data );
10109         }
10110         queue.push( neibor );
10111       }
10112     }
10113   }
10114   dumpCmd( msg + " -- END");
10115 }
10116
10117 //================================================================================
10118 /*!
10119  * \brief Remove last inflation step
10120  */
10121 //================================================================================
10122
10123 void _LayerEdge::InvalidateStep( size_t curStep, const _EdgesOnShape& eos, bool restoreLength )
10124 {
10125   if ( _pos.size() > curStep && _nodes.size() > 1 )
10126   {
10127     _pos.resize( curStep );
10128
10129     gp_Pnt      nXYZ = _pos.back();
10130     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
10131     SMESH_TNodeXYZ curXYZ( n );
10132     if ( !eos._sWOL.IsNull() )
10133     {
10134       TopLoc_Location loc;
10135       if ( eos.SWOLType() == TopAbs_EDGE )
10136       {
10137         SMDS_EdgePositionPtr pos = n->GetPosition();
10138         pos->SetUParameter( nXYZ.X() );
10139         double f,l;
10140         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( eos._sWOL ), loc, f,l);
10141         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
10142       }
10143       else
10144       {
10145         SMDS_FacePositionPtr pos = n->GetPosition();
10146         pos->SetUParameter( nXYZ.X() );
10147         pos->SetVParameter( nXYZ.Y() );
10148         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(eos._sWOL), loc );
10149         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
10150       }
10151     }
10152     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
10153     dumpMove( n );
10154
10155     if ( restoreLength )
10156     {
10157       if ( NbSteps() == 0 )
10158         _len = 0.;
10159       else if ( IsOnFace() && Is( MOVED ))
10160         _len = ( nXYZ.XYZ() - SMESH_NodeXYZ( _nodes[0] )) * _normal;
10161       else
10162         _len -= ( nXYZ.XYZ() - curXYZ ).Modulus() / _lenFactor;
10163     }
10164   }
10165   return;
10166 }
10167
10168 //================================================================================
10169 /*!
10170  * \brief Return index of a _pos distant from _normal
10171  */
10172 //================================================================================
10173
10174 int _LayerEdge::GetSmoothedPos( const double tol )
10175 {
10176   int iSmoothed = 0;
10177   for ( size_t i = 1; i < _pos.size() && !iSmoothed; ++i )
10178   {
10179     double normDist = ( _pos[i] - _pos[0] ).Crossed( _normal ).SquareModulus();
10180     if ( normDist > tol * tol )
10181       iSmoothed = i;
10182   }
10183   return iSmoothed;
10184 }
10185
10186 //================================================================================
10187 /*!
10188  * \brief Smooth a path formed by _pos of a _LayerEdge smoothed on FACE
10189  */
10190 //================================================================================
10191
10192 void _LayerEdge::SmoothPos( const vector< double >& segLen, const double tol )
10193 {
10194   if ( /*Is( NORMAL_UPDATED ) ||*/ _pos.size() <= 2 )
10195     return;
10196
10197   // find the 1st smoothed _pos
10198   int iSmoothed = GetSmoothedPos( tol );
10199   if ( !iSmoothed ) return;
10200
10201   gp_XYZ normal = _normal;
10202   if ( Is( NORMAL_UPDATED ))
10203   {
10204     double minDot = 1;
10205     for ( size_t i = 0; i < _neibors.size(); ++i )
10206     {
10207       if ( _neibors[i]->IsOnFace() )
10208       {
10209         double dot = _normal * _neibors[i]->_normal;
10210         if ( dot < minDot )
10211         {
10212           normal = _neibors[i]->_normal;
10213           minDot = dot;
10214         }
10215       }
10216     }
10217     if ( minDot == 1. )
10218       for ( size_t i = 1; i < _pos.size(); ++i )
10219       {
10220         normal = _pos[i] - _pos[0];
10221         double size = normal.Modulus();
10222         if ( size > RealSmall() )
10223         {
10224           normal /= size;
10225           break;
10226         }
10227       }
10228   }
10229   const double r = 0.2;
10230   for ( int iter = 0; iter < 50; ++iter )
10231   {
10232     double minDot = 1;
10233     for ( size_t i = Max( 1, iSmoothed-1-iter ); i < _pos.size()-1; ++i )
10234     {
10235       gp_XYZ midPos = 0.5 * ( _pos[i-1] + _pos[i+1] );
10236       gp_XYZ newPos = ( 1-r ) * midPos + r * _pos[i];
10237       _pos[i] = newPos;
10238       double midLen = 0.5 * ( segLen[i-1] + segLen[i+1] );
10239       double newLen = ( 1-r ) * midLen + r * segLen[i];
10240       const_cast< double& >( segLen[i] ) = newLen;
10241       // check angle between normal and (_pos[i+1], _pos[i] )
10242       gp_XYZ posDir = _pos[i+1] - _pos[i];
10243       double size   = posDir.SquareModulus();
10244       if ( size > RealSmall() )
10245         minDot = Min( minDot, ( normal * posDir ) * ( normal * posDir ) / size );
10246     }
10247     if ( minDot > 0.5 * 0.5 )
10248       break;
10249   }
10250   return;
10251 }
10252
10253 //================================================================================
10254 /*!
10255  * \brief Print flags
10256  */
10257 //================================================================================
10258
10259 std::string _LayerEdge::DumpFlags() const
10260 {
10261   SMESH_Comment dump;
10262   for ( int flag = 1; flag < 0x1000000; flag *= 2 )
10263     if ( _flags & flag )
10264     {
10265       EFlags f = (EFlags) flag;
10266       switch ( f ) {
10267       case TO_SMOOTH:       dump << "TO_SMOOTH";       break;
10268       case MOVED:           dump << "MOVED";           break;
10269       case SMOOTHED:        dump << "SMOOTHED";        break;
10270       case DIFFICULT:       dump << "DIFFICULT";       break;
10271       case ON_CONCAVE_FACE: dump << "ON_CONCAVE_FACE"; break;
10272       case BLOCKED:         dump << "BLOCKED";         break;
10273       case INTERSECTED:     dump << "INTERSECTED";     break;
10274       case NORMAL_UPDATED:  dump << "NORMAL_UPDATED";  break;
10275       case UPD_NORMAL_CONV: dump << "UPD_NORMAL_CONV"; break;
10276       case MARKED:          dump << "MARKED";          break;
10277       case MULTI_NORMAL:    dump << "MULTI_NORMAL";    break;
10278       case NEAR_BOUNDARY:   dump << "NEAR_BOUNDARY";   break;
10279       case SMOOTHED_C1:     dump << "SMOOTHED_C1";     break;
10280       case DISTORTED:       dump << "DISTORTED";       break;
10281       case RISKY_SWOL:      dump << "RISKY_SWOL";      break;
10282       case SHRUNK:          dump << "SHRUNK";          break;
10283       case UNUSED_FLAG:     dump << "UNUSED_FLAG";     break;
10284       }
10285       dump << " ";
10286     }
10287   cout << dump << endl;
10288   return dump;
10289 }
10290
10291
10292 //================================================================================
10293 /*!
10294  * \brief Create layers of prisms
10295  */
10296 //================================================================================
10297
10298 bool _ViscousBuilder::refine(_SolidData& data)
10299 {
10300   SMESH_MesherHelper& helper = data.GetHelper();
10301   helper.SetElementsOnShape(false);
10302
10303   Handle(Geom_Curve) curve;
10304   Handle(ShapeAnalysis_Surface) surface;
10305   TopoDS_Edge geomEdge;
10306   TopoDS_Face geomFace;
10307   TopLoc_Location loc;
10308   double f,l, u = 0;
10309   gp_XY uv;
10310   vector< gp_XYZ > pos3D;
10311   bool isOnEdge, isTooConvexFace = false;
10312   TGeomID prevBaseId = -1;
10313   TNode2Edge* n2eMap = 0;
10314   TNode2Edge::iterator n2e;
10315
10316   // Create intermediate nodes on each _LayerEdge
10317
10318   for ( size_t iS = 0; iS < data._edgesOnShape.size(); ++iS )
10319   {
10320     _EdgesOnShape& eos = data._edgesOnShape[iS];
10321     if ( eos._edges.empty() ) continue;
10322
10323     if ( eos._edges[0]->_nodes.size() < 2 )
10324       continue; // on _noShrinkShapes
10325
10326     // get data of a shrink shape
10327     isOnEdge = false;
10328     geomEdge.Nullify(); geomFace.Nullify();
10329     curve.Nullify(); surface.Nullify();
10330     if ( !eos._sWOL.IsNull() )
10331     {
10332       isOnEdge = ( eos.SWOLType() == TopAbs_EDGE );
10333       if ( isOnEdge )
10334       {
10335         geomEdge = TopoDS::Edge( eos._sWOL );
10336         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
10337       }
10338       else
10339       {
10340         geomFace = TopoDS::Face( eos._sWOL );
10341         surface  = helper.GetSurface( geomFace );
10342       }
10343     }
10344     else if ( eos.ShapeType() == TopAbs_FACE && eos._toSmooth )
10345     {
10346       geomFace = TopoDS::Face( eos._shape );
10347       surface  = helper.GetSurface( geomFace );
10348       // propagate _toSmooth back to _eosC1, which was unset in findShapesToSmooth()
10349       for ( size_t i = 0; i < eos._eosC1.size(); ++i )
10350         eos._eosC1[ i ]->_toSmooth = true;
10351
10352       isTooConvexFace = false;
10353       if ( _ConvexFace* cf = data.GetConvexFace( eos._shapeID ))
10354         isTooConvexFace = cf->_isTooCurved;
10355     }
10356
10357     vector< double > segLen;
10358     for ( size_t i = 0; i < eos._edges.size(); ++i )
10359     {
10360       _LayerEdge& edge = *eos._edges[i];
10361       if ( edge._pos.size() < 2 )
10362         continue;
10363
10364       // get accumulated length of segments
10365       segLen.resize( edge._pos.size() );
10366       segLen[0] = 0.0;
10367       if ( eos._sWOL.IsNull() )
10368       {
10369         bool useNormal = true;
10370         bool    usePos = false;
10371         bool  smoothed = false;
10372         double   preci = 0.1 * edge._len;
10373         if ( eos._toSmooth && edge._pos.size() > 2 )
10374         {
10375           smoothed = edge.GetSmoothedPos( preci );
10376         }
10377         if ( smoothed )
10378         {
10379           if ( !surface.IsNull() && !isTooConvexFace ) // edge smoothed on FACE
10380           {
10381             useNormal = usePos = false;
10382             gp_Pnt2d uv = helper.GetNodeUV( geomFace, edge._nodes[0] );
10383             for ( size_t j = 1; j < edge._pos.size() && !useNormal; ++j )
10384             {
10385               uv = surface->NextValueOfUV( uv, edge._pos[j], preci );
10386               if ( surface->Gap() < 2. * edge._len )
10387                 segLen[j] = surface->Gap();
10388               else
10389                 useNormal = true;
10390             }
10391           }
10392         }
10393         else if ( !edge.Is( _LayerEdge::NORMAL_UPDATED ))
10394         {
10395 #ifndef __NODES_AT_POS
10396           useNormal = usePos = false;
10397           edge._pos[1] = edge._pos.back();
10398           edge._pos.resize( 2 );
10399           segLen.resize( 2 );
10400           segLen[ 1 ] = edge._len;
10401 #endif
10402         }
10403         if ( useNormal && edge.Is( _LayerEdge::NORMAL_UPDATED ))
10404         {
10405           useNormal = usePos = false;
10406           _LayerEdge tmpEdge; // get original _normal
10407           tmpEdge._nodes.push_back( edge._nodes[0] );
10408           if ( !setEdgeData( tmpEdge, eos, helper, data ))
10409             usePos = true;
10410           else
10411             for ( size_t j = 1; j < edge._pos.size(); ++j )
10412               segLen[j] = ( edge._pos[j] - edge._pos[0] ) * tmpEdge._normal;
10413         }
10414         if ( useNormal )
10415         {
10416           for ( size_t j = 1; j < edge._pos.size(); ++j )
10417             segLen[j] = ( edge._pos[j] - edge._pos[0] ) * edge._normal;
10418         }
10419         if ( usePos )
10420         {
10421           for ( size_t j = 1; j < edge._pos.size(); ++j )
10422             segLen[j] = segLen[j-1] + ( edge._pos[j-1] - edge._pos[j] ).Modulus();
10423         }
10424         else
10425         {
10426           bool swapped = ( edge._pos.size() > 2 );
10427           while ( swapped )
10428           {
10429             swapped = false;
10430             for ( size_t j = 1; j < edge._pos.size()-1; ++j )
10431               if ( segLen[j] > segLen.back() )
10432               {
10433                 segLen.erase( segLen.begin() + j );
10434                 edge._pos.erase( edge._pos.begin() + j );
10435                 --j;
10436               }
10437               else if ( segLen[j] < segLen[j-1] )
10438               {
10439                 std::swap( segLen[j], segLen[j-1] );
10440                 std::swap( edge._pos[j], edge._pos[j-1] );
10441                 swapped = true;
10442               }
10443           }
10444         }
10445         // smooth a path formed by edge._pos
10446 #ifndef __NODES_AT_POS
10447         if (( smoothed ) /*&&
10448             ( eos.ShapeType() == TopAbs_FACE || edge.Is( _LayerEdge::SMOOTHED_C1 ))*/)
10449           edge.SmoothPos( segLen, preci );
10450 #endif
10451       }
10452       else if ( eos._isRegularSWOL ) // usual SWOL
10453       {
10454         if ( edge.Is( _LayerEdge::SMOOTHED ))
10455         {
10456           SMESH_NodeXYZ p0( edge._nodes[0] );
10457           for ( size_t j = 1; j < edge._pos.size(); ++j )
10458           {
10459             gp_XYZ pj = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10460             segLen[j] = ( pj - p0 ) * edge._normal;
10461           }
10462         }
10463         else
10464         {
10465           for ( size_t j = 1; j < edge._pos.size(); ++j )
10466             segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
10467         }
10468       }
10469       else // SWOL is surface with singularities or irregularly parametrized curve
10470       {
10471         pos3D.resize( edge._pos.size() );
10472
10473         if ( !surface.IsNull() )
10474           for ( size_t j = 0; j < edge._pos.size(); ++j )
10475             pos3D[j] = surface->Value( edge._pos[j].X(), edge._pos[j].Y() ).XYZ();
10476         else if ( !curve.IsNull() )
10477           for ( size_t j = 0; j < edge._pos.size(); ++j )
10478             pos3D[j] = curve->Value( edge._pos[j].X() ).XYZ();
10479
10480         for ( size_t j = 1; j < edge._pos.size(); ++j )
10481           segLen[j] = segLen[j-1] + ( pos3D[j-1] - pos3D[j] ).Modulus();
10482       }
10483
10484       // allocate memory for new nodes if it is not yet refined
10485       const SMDS_MeshNode* tgtNode = edge._nodes.back();
10486       if ( edge._nodes.size() == 2 )
10487       {
10488 #ifdef __NODES_AT_POS
10489         int nbNodes = edge._pos.size();
10490 #else
10491         int nbNodes = eos._hyp.GetNumberLayers() + 1;
10492 #endif
10493         edge._nodes.resize( nbNodes, 0 );
10494         edge._nodes[1] = 0;
10495         edge._nodes.back() = tgtNode;
10496       }
10497       // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
10498       const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
10499       if ( baseShapeId != prevBaseId )
10500       {
10501         map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
10502         n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : s2ne->second;
10503         prevBaseId = baseShapeId;
10504       }
10505       _LayerEdge* edgeOnSameNode = 0;
10506       bool        useExistingPos = false;
10507       if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
10508       {
10509         edgeOnSameNode = n2e->second;
10510         useExistingPos = ( edgeOnSameNode->_len < edge._len ||
10511                            segLen[0] == segLen.back() ); // too short inflation step (bos #20643)
10512         const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
10513         SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
10514         if ( isOnEdge )
10515         {
10516           SMDS_EdgePositionPtr epos = lastPos;
10517           epos->SetUParameter( otherTgtPos.X() );
10518         }
10519         else
10520         {
10521           SMDS_FacePositionPtr fpos = lastPos;
10522           fpos->SetUParameter( otherTgtPos.X() );
10523           fpos->SetVParameter( otherTgtPos.Y() );
10524         }
10525       }
10526
10527       // create intermediate nodes
10528       const double      h0 = eos._hyp.Get1stLayerThickness( segLen.back() );
10529       const double zeroLen = std::numeric_limits<double>::min();
10530       double hSum = 0, hi = h0/eos._hyp.GetStretchFactor();
10531       size_t iSeg = 1;
10532       for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
10533       {
10534         // compute an intermediate position
10535         hi *= eos._hyp.GetStretchFactor();
10536         hSum += hi;
10537         while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1 )
10538           ++iSeg;
10539         int iPrevSeg = iSeg-1;
10540         while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
10541           --iPrevSeg;
10542         double   r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
10543         gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
10544 #ifdef __NODES_AT_POS
10545         pos = edge._pos[ iStep ];
10546 #endif
10547         SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
10548         if ( !eos._sWOL.IsNull() )
10549         {
10550           // compute XYZ by parameters <pos>
10551           if ( isOnEdge )
10552           {
10553             u = pos.X();
10554             if ( !node )
10555               pos = curve->Value( u ).Transformed(loc);
10556           }
10557           else if ( eos._isRegularSWOL )
10558           {
10559             uv.SetCoord( pos.X(), pos.Y() );
10560             if ( !node )
10561               pos = surface->Value( pos.X(), pos.Y() );
10562           }
10563           else
10564           {
10565             uv.SetCoord( pos.X(), pos.Y() );
10566             gp_Pnt p = r * pos3D[ iPrevSeg ] + (1-r) * pos3D[ iSeg ];
10567             uv = surface->NextValueOfUV( uv, p, BRep_Tool::Tolerance( geomFace )).XY();
10568             if ( !node )
10569               pos = surface->Value( uv );
10570           }
10571         }
10572         // create or update the node
10573         if ( !node )
10574         {
10575           node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
10576           if ( !eos._sWOL.IsNull() )
10577           {
10578             if ( isOnEdge )
10579               getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
10580             else
10581               getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
10582           }
10583           else
10584           {
10585             getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
10586           }
10587         }
10588         else
10589         {
10590           if ( !eos._sWOL.IsNull() )
10591           {
10592             // make average pos from new and current parameters
10593             if ( isOnEdge )
10594             {
10595               //u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
10596               if ( useExistingPos )
10597                 u = helper.GetNodeU( geomEdge, node );
10598               pos = curve->Value( u ).Transformed(loc);
10599
10600               SMDS_EdgePositionPtr epos = node->GetPosition();
10601               epos->SetUParameter( u );
10602             }
10603             else
10604             {
10605               //uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
10606               if ( useExistingPos )
10607                 uv = helper.GetNodeUV( geomFace, node );
10608               pos = surface->Value( uv );
10609
10610               SMDS_FacePositionPtr fpos = node->GetPosition();
10611               fpos->SetUParameter( uv.X() );
10612               fpos->SetVParameter( uv.Y() );
10613             }
10614           }
10615           node->setXYZ( pos.X(), pos.Y(), pos.Z() );
10616         }
10617       } // loop on edge._nodes
10618
10619       if ( !eos._sWOL.IsNull() ) // prepare for shrink()
10620       {
10621         if ( isOnEdge )
10622           edge._pos.back().SetCoord( u, 0,0);
10623         else
10624           edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
10625
10626         if ( edgeOnSameNode )
10627           edgeOnSameNode->_pos.back() = edge._pos.back();
10628       }
10629
10630     } // loop on eos._edges to create nodes
10631
10632
10633     if ( !getMeshDS()->IsEmbeddedMode() )
10634       // Log node movement
10635       for ( size_t i = 0; i < eos._edges.size(); ++i )
10636       {
10637         SMESH_TNodeXYZ p ( eos._edges[i]->_nodes.back() );
10638         getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
10639       }
10640   }
10641
10642
10643   // Create volumes
10644
10645   helper.SetElementsOnShape(true);
10646
10647   vector< vector<const SMDS_MeshNode*>* > nnVec;
10648   set< vector<const SMDS_MeshNode*>* >    nnSet;
10649   set< int >                       degenEdgeInd;
10650   vector<const SMDS_MeshElement*>     degenVols;
10651
10652   TopExp_Explorer exp( data._solid, TopAbs_FACE );
10653   for ( ; exp.More(); exp.Next() )
10654   {
10655     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
10656     if ( data._ignoreFaceIds.count( faceID ))
10657       continue;
10658     _EdgesOnShape*    eos = data.GetShapeEdges( faceID );
10659     SMDS_MeshGroup* group = StdMeshers_ViscousLayers::CreateGroup( eos->_hyp.GetGroupName(),
10660                                                                    *helper.GetMesh(),
10661                                                                    SMDSAbs_Volume );
10662     std::vector< const SMDS_MeshElement* > vols;
10663     const bool isReversedFace = data._reversedFaceIds.count( faceID );
10664     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
10665     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
10666     while ( fIt->more() )
10667     {
10668       const SMDS_MeshElement* face = fIt->next();
10669       const int            nbNodes = face->NbCornerNodes();
10670       nnVec.resize( nbNodes );
10671       nnSet.clear();
10672       degenEdgeInd.clear();
10673       size_t maxZ = 0, minZ = std::numeric_limits<size_t>::max();
10674       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
10675       for ( int iN = 0; iN < nbNodes; ++iN )
10676       {
10677         const SMDS_MeshNode* n = nIt->next();
10678         _LayerEdge*       edge = data._n2eMap[ n ];
10679         const int i = isReversedFace ? nbNodes-1-iN : iN;
10680         nnVec[ i ] = & edge->_nodes;
10681         maxZ = std::max( maxZ, nnVec[ i ]->size() );
10682         minZ = std::min( minZ, nnVec[ i ]->size() );
10683
10684         if ( helper.HasDegeneratedEdges() )
10685           nnSet.insert( nnVec[ i ]);
10686       }
10687
10688       if ( maxZ == 0 )
10689         continue;
10690       if ( 0 < nnSet.size() && nnSet.size() < 3 )
10691         continue;
10692
10693       vols.clear();
10694       const SMDS_MeshElement* vol;
10695
10696       switch ( nbNodes )
10697       {
10698       case 3: // TRIA
10699       {
10700         // PENTA
10701         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10702         {
10703           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
10704                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
10705           vols.push_back( vol );
10706         }
10707
10708         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10709         {
10710           for ( int iN = 0; iN < nbNodes; ++iN )
10711             if ( nnVec[ iN ]->size() < iZ+1 )
10712               degenEdgeInd.insert( iN );
10713
10714           if ( degenEdgeInd.size() == 1 )  // PYRAM
10715           {
10716             int i2 = *degenEdgeInd.begin();
10717             int i0 = helper.WrapIndex( i2 - 1, nbNodes );
10718             int i1 = helper.WrapIndex( i2 + 1, nbNodes );
10719             vol = helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
10720                                     (*nnVec[i1])[iZ  ], (*nnVec[i0])[iZ  ], (*nnVec[i2]).back());
10721             vols.push_back( vol );
10722           }
10723           else  // TETRA
10724           {
10725             int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
10726             vol = helper.AddVolume( (*nnVec[  0 ])[ i3 == 0 ? iZ-1 : nnVec[0]->size()-1 ],
10727                                     (*nnVec[  1 ])[ i3 == 1 ? iZ-1 : nnVec[1]->size()-1 ],
10728                                     (*nnVec[  2 ])[ i3 == 2 ? iZ-1 : nnVec[2]->size()-1 ],
10729                                     (*nnVec[ i3 ])[ iZ ]);
10730             vols.push_back( vol );
10731           }
10732         }
10733         break; // TRIA
10734       }
10735       case 4: // QUAD
10736       {
10737         // HEX
10738         for ( size_t iZ = 1; iZ < minZ; ++iZ )
10739         {
10740           vol = helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
10741                                   (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
10742                                   (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
10743                                   (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
10744           vols.push_back( vol );
10745         }
10746
10747         for ( size_t iZ = minZ; iZ < maxZ; ++iZ )
10748         {
10749           for ( int iN = 0; iN < nbNodes; ++iN )
10750             if ( nnVec[ iN ]->size() < iZ+1 )
10751               degenEdgeInd.insert( iN );
10752
10753           switch ( degenEdgeInd.size() )
10754           {
10755           case 2: // PENTA
10756           {
10757             int i2 = *degenEdgeInd.begin();
10758             int i3 = *degenEdgeInd.rbegin();
10759             bool ok = ( i3 - i2 == 1 );
10760             if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
10761             int i0 = helper.WrapIndex( i3 + 1, nbNodes );
10762             int i1 = helper.WrapIndex( i0 + 1, nbNodes );
10763
10764             vol = helper.AddVolume( nnVec[i3]->back(), (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
10765                                     nnVec[i2]->back(), (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
10766             vols.push_back( vol );
10767             if ( !ok && vol )
10768               degenVols.push_back( vol );
10769           }
10770           break;
10771
10772           default: // degen HEX
10773           {
10774             vol = helper.AddVolume( nnVec[0]->size() > iZ-1 ? (*nnVec[0])[iZ-1] : nnVec[0]->back(),
10775                                     nnVec[1]->size() > iZ-1 ? (*nnVec[1])[iZ-1] : nnVec[1]->back(),
10776                                     nnVec[2]->size() > iZ-1 ? (*nnVec[2])[iZ-1] : nnVec[2]->back(),
10777                                     nnVec[3]->size() > iZ-1 ? (*nnVec[3])[iZ-1] : nnVec[3]->back(),
10778                                     nnVec[0]->size() > iZ   ? (*nnVec[0])[iZ]   : nnVec[0]->back(),
10779                                     nnVec[1]->size() > iZ   ? (*nnVec[1])[iZ]   : nnVec[1]->back(),
10780                                     nnVec[2]->size() > iZ   ? (*nnVec[2])[iZ]   : nnVec[2]->back(),
10781                                     nnVec[3]->size() > iZ   ? (*nnVec[3])[iZ]   : nnVec[3]->back());
10782             vols.push_back( vol );
10783             degenVols.push_back( vol );
10784           }
10785           }
10786         }
10787         break; // HEX
10788       }
10789       default:
10790         return error("Not supported type of element", data._index);
10791
10792       } // switch ( nbNodes )
10793
10794       if ( group )
10795         for ( size_t i = 0; i < vols.size(); ++i )
10796           group->Add( vols[ i ]);
10797
10798     } // while ( fIt->more() )
10799   } // loop on FACEs
10800
10801   if ( !degenVols.empty() )
10802   {
10803     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
10804     if ( !err || err->IsOK() )
10805     {
10806       SMESH_BadInputElements* badElems =
10807         new SMESH_BadInputElements( getMeshDS(), COMPERR_WARNING, "Bad quality volumes created" );
10808       badElems->myBadElements.insert( badElems->myBadElements.end(),
10809                                       degenVols.begin(),degenVols.end() );
10810       err.reset( badElems );
10811     }
10812   }
10813
10814   return true;
10815 }
10816
10817 namespace VISCOUS_3D
10818 {
10819   struct ShrinkFace;
10820   //--------------------------------------------------------------------------------
10821   /*!
10822    * \brief Pair of periodic FACEs
10823    */
10824   struct PeriodicFaces
10825   {
10826     typedef StdMeshers_ProjectionUtils::TrsfFinder3D Trsf;
10827
10828     ShrinkFace*  _shriFace[2];
10829     TNodeNodeMap _nnMap;
10830     Trsf         _trsf;
10831
10832     PeriodicFaces( ShrinkFace* sf1, ShrinkFace* sf2 ): _shriFace{ sf1, sf2 } {}
10833     bool IncludeShrunk( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces ) const;
10834     bool MoveNodes( const TopoDS_Face& tgtFace );
10835     void Clear() { _nnMap.clear(); }
10836     bool IsEmpty() const { return _nnMap.empty(); }
10837   };
10838
10839   //--------------------------------------------------------------------------------
10840   /*!
10841    * \brief Shrink FACE data used to find periodic FACEs
10842    */
10843   struct ShrinkFace
10844   {
10845     // ................................................................................
10846     struct BndPart //!< part of FACE boundary, either shrink or no-shrink
10847     {
10848       bool                         _isShrink, _isReverse;
10849       int                          _nbSegments;
10850       AverageHyp*                  _hyp;
10851       std::vector< SMESH_NodeXYZ > _nodes;
10852       TopAbs_ShapeEnum             _vertSWOLType[2]; // shrink part includes VERTEXes
10853       AverageHyp*                  _vertHyp[2];
10854       double                       _edgeWOLLen[2]; // length of wol EDGE
10855       double                       _tol; // to compare _edgeWOLLen's
10856
10857       BndPart():
10858         _isShrink(0), _isReverse(0), _nbSegments(0), _hyp(0),
10859         _vertSWOLType{ TopAbs_WIRE, TopAbs_WIRE }, _vertHyp{ 0, 0 }, _edgeWOLLen{ 0., 0.}
10860       {}
10861
10862       bool IsEqualLengthEWOL( const BndPart& other ) const
10863       {
10864         return ( std::abs( _edgeWOLLen[0] - other._edgeWOLLen[0] ) < _tol &&
10865                  std::abs( _edgeWOLLen[1] - other._edgeWOLLen[1] ) < _tol );
10866       }
10867
10868       bool operator==( const BndPart& other ) const
10869       {
10870         return ( _isShrink       == other._isShrink &&
10871                  _nbSegments     == other._nbSegments &&
10872                  _nodes.size()   == other._nodes.size() &&
10873                  vertSWOLType1() == other.vertSWOLType1() &&
10874                  vertSWOLType2() == other.vertSWOLType2() &&
10875                  (( !_isShrink ) ||
10876                   ( *_hyp        == *other._hyp &&
10877                     vertHyp1()   == other.vertHyp1() &&
10878                     vertHyp2()   == other.vertHyp2() &&
10879                     IsEqualLengthEWOL( other )))
10880                  );
10881       }
10882       bool CanAppend( const BndPart& other )
10883       {
10884         return ( _isShrink  == other._isShrink  &&
10885                  (( !_isShrink ) ||
10886                   ( *_hyp        == *other._hyp &&
10887                     *_hyp        == vertHyp2()  &&
10888                     vertHyp2()   == other.vertHyp1() ))
10889                  );
10890       }
10891       void Append( const BndPart& other )
10892       {
10893         _nbSegments += other._nbSegments;
10894         bool hasCommonNode = ( _nodes.back()->GetID() == other._nodes.front()->GetID() );
10895         _nodes.insert( _nodes.end(), other._nodes.begin() + hasCommonNode, other._nodes.end() );
10896         _vertSWOLType[1] = other._vertSWOLType[1];
10897         if ( _isShrink ) {
10898           _vertHyp[1]    = other._vertHyp[1];
10899           _edgeWOLLen[1] = other._edgeWOLLen[1];
10900         }
10901       }
10902       const SMDS_MeshNode* Node(size_t i)  const
10903       {
10904         return _nodes[ _isReverse ? ( _nodes.size() - 1 - i ) : i ]._node;
10905       }
10906       void Reverse() { _isReverse = !_isReverse; }
10907       const TopAbs_ShapeEnum& vertSWOLType1() const { return _vertSWOLType[ _isReverse  ]; }
10908       const TopAbs_ShapeEnum& vertSWOLType2() const { return _vertSWOLType[ !_isReverse ]; }
10909       const AverageHyp&       vertHyp1()      const { return *(_vertHyp[ _isReverse  ]); }
10910       const AverageHyp&       vertHyp2()      const { return *(_vertHyp[ !_isReverse ]); }
10911     };
10912     // ................................................................................
10913
10914     SMESH_subMesh*       _subMesh;
10915     _SolidData*          _data1;
10916     _SolidData*          _data2;
10917
10918     std::list< BndPart > _boundary;
10919     int                  _boundarySize, _nbBoundaryParts;
10920
10921     void Init( SMESH_subMesh* sm, _SolidData* sd1, _SolidData* sd2 )
10922     {
10923       _subMesh = sm; _data1 = sd1; _data2 = sd2;
10924     }
10925     bool IsSame( const TopoDS_Face& face ) const
10926     {
10927       return _subMesh->GetSubShape().IsSame( face );
10928     }
10929     bool IsShrunk( const TopTools_MapOfShape& shrunkFaces ) const
10930     {
10931       return shrunkFaces.Contains( _subMesh->GetSubShape() );
10932     }
10933
10934     //================================================================================
10935     /*!
10936      * Check if meshes on two FACEs are equal
10937      */
10938     bool IsPeriodic( ShrinkFace& other, PeriodicFaces& periodic )
10939     {
10940       if ( !IsSameNbElements( other ))
10941         return false;
10942
10943       this->SetBoundary();
10944       other.SetBoundary();
10945       if ( this->_boundarySize    != other._boundarySize ||
10946            this->_nbBoundaryParts != other._nbBoundaryParts )
10947         return false;
10948
10949       for ( int isReverse = 0; isReverse < 2; ++isReverse )
10950       {
10951         if ( isReverse )
10952           Reverse( _boundary );
10953
10954         // check boundaries
10955         bool equalBoundary = false;
10956         for ( int iP = 0; iP < _nbBoundaryParts &&  !equalBoundary; ++iP )
10957         {
10958           if ( ! ( equalBoundary = ( this->_boundary == other._boundary )))
10959             // set first part at end
10960             _boundary.splice( _boundary.end(), _boundary, _boundary.begin() );
10961         }
10962         if ( !equalBoundary )
10963           continue;
10964
10965         // check connectivity
10966         std::set<const SMDS_MeshElement*> elemsThis, elemsOther;
10967         this->GetElements( elemsThis  );
10968         other.GetElements( elemsOther );
10969         SMESH_MeshEditor::Sew_Error err =
10970           SMESH_MeshEditor::FindMatchingNodes( elemsThis, elemsOther,
10971                                                this->_boundary.front().Node(0),
10972                                                other._boundary.front().Node(0),
10973                                                this->_boundary.front().Node(1),
10974                                                other._boundary.front().Node(1),
10975                                                periodic._nnMap );
10976         if ( err != SMESH_MeshEditor::SEW_OK )
10977           continue;
10978
10979         // check node positions
10980         std::vector< gp_XYZ > srcPnts, tgtPnts;
10981         this->GetBoundaryPoints( srcPnts );
10982         other.GetBoundaryPoints( tgtPnts );
10983         if ( !periodic._trsf.Solve( srcPnts, tgtPnts )) {
10984           continue;
10985         }
10986         double tol = std::numeric_limits<double>::max(); // tolerance by segment size
10987         for ( size_t i = 1; i < srcPnts.size(); ++i ) {
10988           tol = Min( tol, ( srcPnts[i-1] - srcPnts[i] ).SquareModulus() );
10989         }
10990         tol = 0.01 * Sqrt( tol );
10991         for ( BndPart& boundary : _boundary ) { // tolerance by VL thickness
10992           if ( boundary._isShrink )
10993             tol = Min( tol, boundary._hyp->Get1stLayerThickness() / 50. );
10994         }
10995         bool nodeCoincide = true;
10996         TNodeNodeMap::iterator n2n = periodic._nnMap.begin();
10997         for ( ; n2n != periodic._nnMap.end() &&  nodeCoincide; ++n2n )
10998         {
10999           SMESH_NodeXYZ nSrc = n2n->first;
11000           SMESH_NodeXYZ nTgt = n2n->second;
11001           gp_XYZ pTgt = periodic._trsf.Transform( nSrc );
11002           nodeCoincide = (( pTgt - nTgt ).SquareModulus() < tol * tol );
11003         }
11004         if ( nodeCoincide )
11005           return true;
11006       }
11007       return false;
11008     }
11009
11010     bool IsSameNbElements( ShrinkFace& other ) // check number of mesh faces
11011     {
11012       SMESHDS_SubMesh* sm1 = this->_subMesh->GetSubMeshDS();
11013       SMESHDS_SubMesh* sm2 = other._subMesh->GetSubMeshDS();
11014       return ( sm1->NbElements() == sm2->NbElements() &&
11015                sm1->NbNodes()    == sm2->NbNodes() );
11016     }
11017
11018     void Reverse( std::list< BndPart >& boundary )
11019     {
11020       boundary.reverse();
11021       for ( std::list< BndPart >::iterator part = boundary.begin(); part != boundary.end(); ++part )
11022         part->Reverse();
11023     }
11024
11025     void SetBoundary()
11026     {
11027       if ( !_boundary.empty() )
11028         return;
11029
11030       TopoDS_Face F = TopoDS::Face( _subMesh->GetSubShape() );
11031       if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
11032       std::list< TopoDS_Edge > edges;
11033       std::list< int > nbEdgesInWire;
11034       /*int nbWires =*/ SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
11035
11036       // std::list< TopoDS_Edge >::iterator edgesEnd = edges.end();
11037       // if ( nbWires > 1 ) {
11038       //   edgesEnd = edges.begin();
11039       //   std::advance( edgesEnd, nbEdgesInWire.front() );
11040       // }
11041       StdMeshers_FaceSide fSide( F, edges, _subMesh->GetFather(),
11042                                  /*fwd=*/true, /*skipMedium=*/true );
11043       _boundarySize = fSide.NbSegments();
11044
11045       //TopoDS_Vertex vv[2];
11046       //std::list< TopoDS_Edge >::iterator edgeIt = edges.begin();
11047       for ( int iE = 0; iE < nbEdgesInWire.front(); ++iE )
11048       {
11049         BndPart bndPart;
11050
11051         std::vector<const SMDS_MeshNode*> nodes = fSide.GetOrderedNodes( iE );
11052         bndPart._nodes.assign( nodes.begin(), nodes.end() );
11053         bndPart._nbSegments = bndPart._nodes.size() - 1;
11054
11055         _EdgesOnShape*  eos = _data1->GetShapeEdges( fSide.EdgeID( iE ));
11056
11057         bndPart._isShrink = ( eos->SWOLType() == TopAbs_FACE );
11058         if ( bndPart._isShrink )
11059           if ((           _data1->_noShrinkShapes.count( eos->_shapeID )) ||
11060               ( _data2 && _data2->_noShrinkShapes.count( eos->_shapeID )))
11061             bndPart._isShrink = false;
11062
11063         if ( bndPart._isShrink )
11064         {
11065           bndPart._hyp = & eos->_hyp;
11066           _EdgesOnShape* eov[2] = { _data1->GetShapeEdges( fSide.FirstVertex( iE )),
11067                                     _data1->GetShapeEdges( fSide.LastVertex ( iE )) };
11068           for ( int iV = 0; iV < 2; ++iV )
11069           {
11070             bndPart._vertHyp     [iV] = & eov[iV]->_hyp;
11071             bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11072             if ( _data1->_noShrinkShapes.count( eov[iV]->_shapeID ))
11073               bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11074             if ( _data2 && bndPart._vertSWOLType[iV] != TopAbs_SHAPE )
11075             {
11076               eov[iV] = _data2->GetShapeEdges( iV ? fSide.LastVertex(iE) : fSide.FirstVertex(iE ));
11077               if ( _data2->_noShrinkShapes.count( eov[iV]->_shapeID ))
11078                 bndPart._vertSWOLType[iV] = TopAbs_SHAPE;
11079               else if ( eov[iV]->SWOLType() > bndPart._vertSWOLType[iV] )
11080                 bndPart._vertSWOLType[iV] = eov[iV]->SWOLType();
11081             }
11082           }
11083           bndPart._edgeWOLLen[0] = fSide.EdgeLength( iE - 1 );
11084           bndPart._edgeWOLLen[1] = fSide.EdgeLength( iE + 1 );
11085
11086           bndPart._tol = std::numeric_limits<double>::max(); // tolerance by segment size
11087           for ( size_t i = 1; i < bndPart._nodes.size(); ++i )
11088             bndPart._tol = Min( bndPart._tol,
11089                                 ( bndPart._nodes[i-1] - bndPart._nodes[i] ).SquareModulus() );
11090         }
11091
11092         if ( _boundary.empty() || ! _boundary.back().CanAppend( bndPart ))
11093           _boundary.push_back( bndPart );
11094         else
11095           _boundary.back().Append( bndPart );
11096       }
11097
11098       _nbBoundaryParts = _boundary.size();
11099       if ( _nbBoundaryParts > 1 && _boundary.front()._isShrink == _boundary.back()._isShrink )
11100       {
11101         _boundary.back().Append( _boundary.front() );
11102         _boundary.pop_front();
11103         --_nbBoundaryParts;
11104       }
11105     }
11106
11107     void GetElements( std::set<const SMDS_MeshElement*>& theElems)
11108     {
11109       if ( SMESHDS_SubMesh* sm = _subMesh->GetSubMeshDS() )
11110         for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
11111           theElems.insert( theElems.end(), fIt->next() );
11112
11113       return ;
11114     }
11115
11116     void GetBoundaryPoints( std::vector< gp_XYZ >& points )
11117     {
11118       points.reserve( _boundarySize );
11119       size_t  nb = _boundary.rbegin()->_nodes.size();
11120       smIdType lastID = _boundary.rbegin()->Node( nb - 1 )->GetID();
11121       std::list< BndPart >::const_iterator part = _boundary.begin();
11122       for ( ; part != _boundary.end(); ++part )
11123       {
11124         size_t nb = part->_nodes.size();
11125         size_t iF = 0;
11126         size_t iR = nb - 1;
11127         size_t* i = part->_isReverse ? &iR : &iF;
11128         if ( part->_nodes[ *i ]->GetID() == lastID )
11129           ++iF, --iR;
11130         for ( ; iF < nb; ++iF, --iR )
11131           points.push_back( part->_nodes[ *i ]);
11132         --iF, ++iR;
11133         lastID = part->_nodes[ *i ]->GetID();
11134       }
11135     }
11136   }; // struct ShrinkFace
11137
11138   //--------------------------------------------------------------------------------
11139   /*!
11140    * \brief Periodic FACEs
11141    */
11142   struct Periodicity
11143   {
11144     std::vector< ShrinkFace >    _shrinkFaces;
11145     std::vector< PeriodicFaces > _periodicFaces;
11146
11147     PeriodicFaces* GetPeriodic( const TopoDS_Face& face, const TopTools_MapOfShape& shrunkFaces )
11148     {
11149       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11150         if ( _periodicFaces[ i ].IncludeShrunk( face, shrunkFaces ))
11151           return & _periodicFaces[ i ];
11152       return 0;
11153     }
11154     void ClearPeriodic( const TopoDS_Face& face )
11155     {
11156       for ( size_t i = 0; i < _periodicFaces.size(); ++i )
11157         if ( _periodicFaces[ i ]._shriFace[0]->IsSame( face ) ||
11158              _periodicFaces[ i ]._shriFace[1]->IsSame( face ))
11159           _periodicFaces[ i ].Clear();
11160     }
11161   };
11162
11163   //================================================================================
11164   /*!
11165    * Check if a pair includes the given FACE and the other FACE is already shrunk
11166    */
11167   bool PeriodicFaces::IncludeShrunk( const TopoDS_Face&         face,
11168                                      const TopTools_MapOfShape& shrunkFaces ) const
11169   {
11170     if ( IsEmpty() ) return false;
11171     return (( _shriFace[0]->IsSame( face ) && _shriFace[1]->IsShrunk( shrunkFaces )) ||
11172             ( _shriFace[1]->IsSame( face ) && _shriFace[0]->IsShrunk( shrunkFaces )));
11173   }
11174
11175   //================================================================================
11176   /*!
11177    * Make equal meshes on periodic faces by moving corresponding nodes
11178    */
11179   bool PeriodicFaces::MoveNodes( const TopoDS_Face& tgtFace )
11180   {
11181     int iTgt = _shriFace[1]->IsSame( tgtFace );
11182     int iSrc = 1 - iTgt;
11183
11184     _SolidData* dataSrc = _shriFace[iSrc]->_data1;
11185     _SolidData* dataTgt = _shriFace[iTgt]->_data1;
11186
11187     Trsf * trsf = & _trsf, trsfInverse;
11188     if ( iSrc != 0 )
11189     {
11190       trsfInverse = _trsf;
11191       if ( !trsfInverse.Invert())
11192         return false;
11193       trsf = &trsfInverse;
11194     }
11195     SMESHDS_Mesh* meshDS = dataSrc->GetHelper().GetMeshDS();
11196
11197     dumpFunction(SMESH_Comment("periodicMoveNodes_F")
11198                                << _shriFace[iSrc]->_subMesh->GetId() << "_F"
11199                                << _shriFace[iTgt]->_subMesh->GetId() );
11200     TNode2Edge::iterator n2e;
11201     TNodeNodeMap::iterator n2n = _nnMap.begin();
11202     for ( ; n2n != _nnMap.end(); ++n2n )
11203     {
11204       const SMDS_MeshNode* const* nn = & n2n->first;
11205       const SMDS_MeshNode*      nSrc = nn[ iSrc ];
11206       const SMDS_MeshNode*      nTgt = nn[ iTgt ];
11207
11208       if (( nSrc->GetPosition()->GetDim() == 2 ) ||
11209           (( n2e = dataSrc->_n2eMap.find( nSrc )) == dataSrc->_n2eMap.end() ))
11210       {
11211         SMESH_NodeXYZ pSrc = nSrc;
11212         gp_XYZ pTgt = trsf->Transform( pSrc );
11213         meshDS->MoveNode( nTgt, pTgt.X(), pTgt.Y(), pTgt.Z() );
11214       }
11215       else
11216       {
11217         _LayerEdge* leSrc = n2e->second;
11218         n2e = dataTgt->_n2eMap.find( nTgt );
11219         if ( n2e == dataTgt->_n2eMap.end() )
11220           break;
11221         _LayerEdge* leTgt = n2e->second;
11222         if ( leSrc->_nodes.size() != leTgt->_nodes.size() )
11223           break;
11224         for ( size_t iN = 1; iN < leSrc->_nodes.size(); ++iN )
11225         {
11226           SMESH_NodeXYZ pSrc = leSrc->_nodes[ iN ];
11227           gp_XYZ pTgt = trsf->Transform( pSrc );
11228           meshDS->MoveNode( leTgt->_nodes[ iN ], pTgt.X(), pTgt.Y(), pTgt.Z() );
11229
11230           dumpMove( leTgt->_nodes[ iN ]);
11231         }
11232       }
11233     }
11234     bool done = ( n2n == _nnMap.end() );
11235     debugMsg( "PeriodicFaces::MoveNodes "
11236               << _shriFace[iSrc]->_subMesh->GetId() << " -> "
11237               << _shriFace[iTgt]->_subMesh->GetId() << " -- "
11238               << ( done ? "DONE" : "FAIL"));
11239     dumpFunctionEnd();
11240
11241     return done;
11242   }
11243 } // namespace VISCOUS_3D; Periodicity part
11244
11245
11246 //================================================================================
11247 /*!
11248  * \brief Find FACEs to shrink, that are equally meshed before shrink (i.e. periodic)
11249  *        and should remain equal after shrink
11250  */
11251 //================================================================================
11252
11253 void _ViscousBuilder::findPeriodicFaces()
11254 {
11255   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11256   // _LayerEdge's inflated along FACE or EDGE)
11257   std::map< TGeomID, std::list< _SolidData* > > id2sdMap;
11258   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11259   {
11260     _SolidData& data = _sdVec[i];
11261     std::map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11262     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11263       if ( s2s->second.ShapeType() == TopAbs_FACE )
11264         id2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11265   }
11266
11267   _periodicity.reset( new Periodicity );
11268   _periodicity->_shrinkFaces.resize( id2sdMap.size() );
11269
11270   std::map< TGeomID, std::list< _SolidData* > >::iterator id2sdIt = id2sdMap.begin();
11271   for ( size_t i = 0; i < id2sdMap.size(); ++i, ++id2sdIt )
11272   {
11273     _SolidData* sd1 = id2sdIt->second.front();
11274     _SolidData* sd2 = id2sdIt->second.back();
11275     _periodicity->_shrinkFaces[ i ].Init( _mesh->GetSubMeshContaining( id2sdIt->first ), sd1, sd2 );
11276   }
11277
11278   for (   size_t i1 = 0;      i1 < _periodicity->_shrinkFaces.size(); ++i1 )
11279     for ( size_t i2 = i1 + 1; i2 < _periodicity->_shrinkFaces.size(); ++i2 )
11280     {
11281       PeriodicFaces pf( & _periodicity->_shrinkFaces[ i1 ],
11282                         & _periodicity->_shrinkFaces[ i2 ]);
11283       if ( pf._shriFace[0]->IsPeriodic( *pf._shriFace[1], pf ))
11284       {
11285         _periodicity->_periodicFaces.push_back( pf );
11286       }
11287     }
11288   return;
11289 }
11290
11291 //================================================================================
11292 /*!
11293  * \brief Shrink 2D mesh on faces to let space for inflated layers
11294  */
11295 //================================================================================
11296
11297 bool _ViscousBuilder::shrink(_SolidData& theData)
11298 {
11299   // make map of (ids of FACEs to shrink mesh on) to (list of _SolidData containing
11300   // _LayerEdge's inflated along FACE or EDGE)
11301   map< TGeomID, list< _SolidData* > > f2sdMap;
11302   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11303   {
11304     _SolidData& data = _sdVec[i];
11305     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
11306     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
11307       if ( s2s->second.ShapeType() == TopAbs_FACE && !_shrunkFaces.Contains( s2s->second ))
11308       {
11309         f2sdMap[ getMeshDS()->ShapeToIndex( s2s->second )].push_back( &data );
11310
11311         // Put mesh faces on the shrunk FACE to the proxy sub-mesh to avoid
11312         // usage of mesh faces made in addBoundaryElements() by the 3D algo or
11313         // by StdMeshers_QuadToTriaAdaptor
11314         if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
11315         {
11316           SMESH_ProxyMesh::SubMesh* proxySub =
11317             data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
11318           if ( proxySub->NbElements() == 0 )
11319           {
11320             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11321             while ( fIt->more() )
11322             {
11323               const SMDS_MeshElement* f = fIt->next();
11324               // as a result 3D algo will use elements from proxySub and not from smDS
11325               proxySub->AddElement( f );
11326               f->setIsMarked( true );
11327
11328               // Mark nodes on the FACE to discriminate them from nodes
11329               // added by addBoundaryElements(); marked nodes are to be smoothed while shrink()
11330               for ( int iN = 0, nbN = f->NbNodes(); iN < nbN; ++iN )
11331               {
11332                 const SMDS_MeshNode* n = f->GetNode( iN );
11333                 if ( n->GetPosition()->GetDim() == 2 )
11334                   n->setIsMarked( true );
11335               }
11336             }
11337           }
11338         }
11339       }
11340   }
11341
11342   SMESH_MesherHelper helper( *_mesh );
11343   helper.ToFixNodeParameters( true );
11344
11345   // EDGEs to shrink
11346   map< TGeomID, _Shrinker1D > e2shrMap;
11347   vector< _EdgesOnShape* > subEOS;
11348   vector< _LayerEdge* > lEdges;
11349
11350   // loop on FACEs to shrink mesh on
11351   map< TGeomID, list< _SolidData* > >::iterator f2sd = f2sdMap.begin();
11352   for ( ; f2sd != f2sdMap.end(); ++f2sd )
11353   {
11354     list< _SolidData* > & dataList = f2sd->second;
11355     if ( dataList.front()->_n2eMap.empty() ||
11356          dataList.back() ->_n2eMap.empty() )
11357       continue; // not yet computed
11358     if ( dataList.front() != &theData &&
11359          dataList.back()  != &theData )
11360       continue;
11361
11362     _SolidData&      data = *dataList.front();
11363     _SolidData*     data2 = dataList.size() > 1 ? dataList.back() : 0;
11364     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
11365     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
11366     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
11367
11368     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
11369
11370     _shrunkFaces.Add( F );
11371     helper.SetSubShape( F );
11372
11373     // ==============================
11374     // Use periodicity to move nodes
11375     // ==============================
11376
11377     PeriodicFaces* periodic = _periodicity->GetPeriodic( F, _shrunkFaces );
11378     bool movedByPeriod = ( periodic && periodic->MoveNodes( F ));
11379
11380     // ===========================
11381     // Prepare data for shrinking
11382     // ===========================
11383
11384     // Collect nodes to smooth (they are marked at the beginning of this method)
11385     vector < const SMDS_MeshNode* > smoothNodes;
11386
11387     if ( !movedByPeriod )
11388     {
11389       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
11390       while ( nIt->more() )
11391       {
11392         const SMDS_MeshNode* n = nIt->next();
11393         if ( n->isMarked() )
11394           smoothNodes.push_back( n );
11395       }
11396     }
11397     // Find out face orientation
11398     double refSign = 1;
11399     const set<TGeomID> ignoreShapes;
11400     bool isOkUV;
11401     if ( !smoothNodes.empty() )
11402     {
11403       vector<_Simplex> simplices;
11404       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
11405       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of simplex nodes
11406       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
11407       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
11408       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper, refSign ))
11409         refSign = -1;
11410     }
11411
11412     // Find _LayerEdge's inflated along F
11413     subEOS.clear();
11414     lEdges.clear();
11415     {
11416       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false,
11417                                                                 /*complexFirst=*/true); //!!!
11418       while ( subIt->more() )
11419       {
11420         const TGeomID subID = subIt->next()->GetId();
11421         if ( data._noShrinkShapes.count( subID ))
11422           continue;
11423         _EdgesOnShape* eos = data.GetShapeEdges( subID );
11424         if ( !eos || eos->_sWOL.IsNull() )
11425           if ( data2 ) // check in adjacent SOLID
11426           {
11427             eos = data2->GetShapeEdges( subID );
11428             if ( !eos || eos->_sWOL.IsNull() )
11429               continue;
11430           }
11431         subEOS.push_back( eos );
11432
11433         if ( !movedByPeriod )
11434           for ( size_t i = 0; i < eos->_edges.size(); ++i )
11435           {
11436             lEdges.push_back( eos->_edges[ i ] );
11437             prepareEdgeToShrink( *eos->_edges[ i ], *eos, helper, smDS );
11438           }
11439       }
11440     }
11441
11442     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
11443     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11444     while ( fIt->more() )
11445       if ( const SMDS_MeshElement* f = fIt->next() )
11446         dumpChangeNodes( f );
11447     dumpFunctionEnd();
11448
11449     // Replace source nodes by target nodes in mesh faces to shrink
11450     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
11451     const SMDS_MeshNode* nodes[20];
11452     for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11453     {
11454       _EdgesOnShape& eos = * subEOS[ iS ];
11455       for ( size_t i = 0; i < eos._edges.size(); ++i )
11456       {
11457         _LayerEdge& edge = *eos._edges[i];
11458         const SMDS_MeshNode* srcNode = edge._nodes[0];
11459         const SMDS_MeshNode* tgtNode = edge._nodes.back();
11460         SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
11461         while ( fIt->more() )
11462         {
11463           const SMDS_MeshElement* f = fIt->next();
11464           if ( !smDS->Contains( f ) || !f->isMarked() )
11465             continue;
11466           SMDS_NodeIteratorPtr nIt = f->nodeIterator();
11467           for ( int iN = 0; nIt->more(); ++iN )
11468           {
11469             const SMDS_MeshNode* n = nIt->next();
11470             nodes[iN] = ( n == srcNode ? tgtNode : n );
11471           }
11472           helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
11473           dumpChangeNodes( f );
11474         }
11475       }
11476     }
11477     dumpFunctionEnd();
11478
11479     // find out if a FACE is concave
11480     const bool isConcaveFace = isConcave( F, helper );
11481
11482     // Create _SmoothNode's on face F
11483     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
11484     {
11485       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
11486       const bool sortSimplices = isConcaveFace;
11487       for ( size_t i = 0; i < smoothNodes.size(); ++i )
11488       {
11489         const SMDS_MeshNode* n = smoothNodes[i];
11490         nodesToSmooth[ i ]._node = n;
11491         // src nodes must be already replaced by tgt nodes to have tgt nodes in _simplices
11492         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
11493         // fix up incorrect uv of nodes on the FACE
11494         helper.GetNodeUV( F, n, 0, &isOkUV);
11495         dumpMove( n );
11496       }
11497       dumpFunctionEnd();
11498     }
11499     //if ( nodesToSmooth.empty() ) continue;
11500
11501     // Find EDGE's to shrink and set simpices to LayerEdge's
11502     set< _Shrinker1D* > eShri1D;
11503     {
11504       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11505       {
11506         _EdgesOnShape& eos = * subEOS[ iS ];
11507         if ( eos.SWOLType() == TopAbs_EDGE )
11508         {
11509           SMESH_subMesh* edgeSM = _mesh->GetSubMesh( eos._sWOL );
11510           VISCOUS_3D::ToClearSubWithMain( edgeSM, data._solid );
11511           if ( !movedByPeriod )
11512           {
11513             _Shrinker1D& shrinker = e2shrMap[ edgeSM->GetId() ];
11514             eShri1D.insert( & shrinker );
11515             shrinker.AddEdge( eos._edges[0], eos, helper );
11516             // restore params of nodes on EDGE if the EDGE has been already
11517             // shrunk while shrinking other FACE
11518             shrinker.RestoreParams();
11519           }
11520         }
11521         for ( size_t i = 0; i < eos._edges.size(); ++i )
11522         {
11523           _LayerEdge& edge = * eos._edges[i];
11524           _Simplex::GetSimplices( /*tgtNode=*/edge._nodes.back(), edge._simplices, ignoreShapes );
11525
11526           // additionally mark tgt node; only marked nodes will be used in SetNewLength2d()
11527           // not-marked nodes are those added by refine()
11528           edge._nodes.back()->setIsMarked( true );
11529         }
11530       }
11531     }
11532
11533     bool toFixTria = false; // to improve quality of trias by diagonal swap
11534     if ( isConcaveFace && !movedByPeriod )
11535     {
11536       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
11537       if ( hasTria != hasQuad ) {
11538         toFixTria = hasTria;
11539       }
11540       else {
11541         set<int> nbNodesSet;
11542         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
11543         while ( fIt->more() && nbNodesSet.size() < 2 )
11544           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
11545         toFixTria = ( *nbNodesSet.begin() == 3 );
11546       }
11547     }
11548
11549     // ==================
11550     // Perform shrinking
11551     // ==================
11552
11553     bool shrunk = !movedByPeriod;
11554     int nbBad, shriStep=0, smooStep=0;
11555     _SmoothNode::SmoothType smoothType
11556       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
11557     SMESH_Comment errMsg;
11558     while ( shrunk )
11559     {
11560       shriStep++;
11561       // Move boundary nodes (actually just set new UV)
11562       // -----------------------------------------------
11563       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
11564       shrunk = false;
11565       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11566       {
11567         _EdgesOnShape& eos = * subEOS[ iS ];
11568         for ( size_t i = 0; i < eos._edges.size(); ++i )
11569         {
11570           shrunk |= eos._edges[i]->SetNewLength2d( surface, F, eos, helper );
11571         }
11572       }
11573       dumpFunctionEnd();
11574
11575       // Move nodes on EDGE's
11576       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
11577       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
11578       for ( ; shr != eShri1D.end(); ++shr )
11579         (*shr)->Compute( /*set3D=*/false, helper );
11580
11581       // Smoothing in 2D
11582       // -----------------
11583       int nbNoImpSteps = 0;
11584       bool       moved = true;
11585       nbBad = 1;
11586       while (( nbNoImpSteps < 5 && nbBad > 0) && moved)
11587       {
11588         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11589
11590         int oldBadNb = nbBad;
11591         nbBad = 0;
11592         moved = false;
11593         // '% 5' minimizes NB FUNCTIONS on viscous_layers_00/B2 case
11594         _SmoothNode::SmoothType smooTy = ( smooStep % 5 ) ? smoothType : _SmoothNode::LAPLACIAN;
11595         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11596         {
11597           moved |= nodesToSmooth[i].Smooth( nbBad, surface, helper, refSign,
11598                                             smooTy, /*set3D=*/isConcaveFace);
11599         }
11600         if ( nbBad < oldBadNb )
11601           nbNoImpSteps = 0;
11602         else
11603           nbNoImpSteps++;
11604
11605         dumpFunctionEnd();
11606       }
11607
11608       errMsg.clear();
11609       if ( nbBad > 0 )
11610         errMsg << "Can't shrink 2D mesh on face " << f2sd->first;
11611       if ( shriStep > 200 )
11612         errMsg << "Infinite loop at shrinking 2D mesh on face " << f2sd->first;
11613       if ( !errMsg.empty() )
11614         break;
11615
11616       // Fix narrow triangles by swapping diagonals
11617       // ---------------------------------------
11618       if ( toFixTria )
11619       {
11620         set<const SMDS_MeshNode*> usedNodes;
11621         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
11622
11623         // update working data
11624         set<const SMDS_MeshNode*>::iterator n;
11625         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
11626         {
11627           n = usedNodes.find( nodesToSmooth[ i ]._node );
11628           if ( n != usedNodes.end())
11629           {
11630             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
11631                                     nodesToSmooth[ i ]._simplices,
11632                                     ignoreShapes, NULL,
11633                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
11634             usedNodes.erase( n );
11635           }
11636         }
11637         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
11638         {
11639           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
11640           if ( n != usedNodes.end())
11641           {
11642             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
11643                                     lEdges[i]->_simplices,
11644                                     ignoreShapes );
11645             usedNodes.erase( n );
11646           }
11647         }
11648       }
11649       // TODO: check effect of this additional smooth
11650       // additional laplacian smooth to increase allowed shrink step
11651       // for ( int st = 1; st; --st )
11652       // {
11653       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11654       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11655       //   {
11656       //     nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11657       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
11658       //   }
11659       // }
11660
11661     } // while ( shrunk )
11662
11663     if ( !errMsg.empty() ) // Try to re-compute the shrink FACE
11664     {
11665       debugMsg( "Re-compute FACE " << f2sd->first << " because " << errMsg );
11666
11667       // remove faces
11668       SMESHDS_SubMesh* psm = data._proxyMesh->getFaceSubM( F );
11669       {
11670         vector< const SMDS_MeshElement* > facesToRm;
11671         if ( psm )
11672         {
11673           facesToRm.reserve( psm->NbElements() );
11674           for ( SMDS_ElemIteratorPtr ite = psm->GetElements(); ite->more(); )
11675             facesToRm.push_back( ite->next() );
11676
11677           for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11678             if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11679               psm->Clear();
11680         }
11681         for ( size_t i = 0; i < facesToRm.size(); ++i )
11682           getMeshDS()->RemoveFreeElement( facesToRm[i], smDS, /*fromGroups=*/false );
11683       }
11684       // remove nodes
11685       {
11686         TIDSortedNodeSet nodesToKeep; // nodes of _LayerEdge to keep
11687         for ( size_t iS = 0; iS < subEOS.size(); ++iS ) {
11688           for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11689             nodesToKeep.insert( ++( subEOS[iS]->_edges[i]->_nodes.begin() ),
11690                                 subEOS[iS]->_edges[i]->_nodes.end() );
11691         }
11692         SMDS_NodeIteratorPtr itn = smDS->GetNodes();
11693         while ( itn->more() ) {
11694           const SMDS_MeshNode* n = itn->next();
11695           if ( !nodesToKeep.count( n ))
11696             getMeshDS()->RemoveFreeNode( n, smDS, /*fromGroups=*/false );
11697         }
11698       }
11699       _periodicity->ClearPeriodic( F );
11700
11701       // restore position and UV of target nodes
11702       gp_Pnt p;
11703       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11704         for ( size_t i = 0; i < subEOS[iS]->_edges.size(); ++i )
11705         {
11706           _LayerEdge*       edge = subEOS[iS]->_edges[i];
11707           SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( edge->_nodes.back() );
11708           if ( edge->_pos.empty() ||
11709                edge->Is( _LayerEdge::SHRUNK )) continue;
11710           if ( subEOS[iS]->SWOLType() == TopAbs_FACE )
11711           {
11712             SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11713             pos->SetUParameter( edge->_pos[0].X() );
11714             pos->SetVParameter( edge->_pos[0].Y() );
11715             p = surface->Value( edge->_pos[0].X(), edge->_pos[0].Y() );
11716           }
11717           else
11718           {
11719             SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11720             pos->SetUParameter( edge->_pos[0].Coord( U_TGT ));
11721             p = BRepAdaptor_Curve( TopoDS::Edge( subEOS[iS]->_sWOL )).Value( pos->GetUParameter() );
11722           }
11723           tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
11724           dumpMove( tgtNode );
11725         }
11726       // shrink EDGE sub-meshes and set proxy sub-meshes
11727       UVPtStructVec uvPtVec;
11728       set< _Shrinker1D* >::iterator shrIt = eShri1D.begin();
11729       for ( shrIt = eShri1D.begin(); shrIt != eShri1D.end(); ++shrIt )
11730       {
11731         _Shrinker1D* shr = (*shrIt);
11732         shr->Compute( /*set3D=*/true, helper );
11733
11734         // set proxy mesh of EDGEs w/o layers
11735         map< double, const SMDS_MeshNode* > nodes;
11736         SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), shr->GeomEdge(),/*skipMedium=*/true, nodes);
11737         // remove refinement nodes
11738         const SMDS_MeshNode* sn0 = shr->SrcNode(0), *sn1 = shr->SrcNode(1);
11739         const SMDS_MeshNode* tn0 = shr->TgtNode(0), *tn1 = shr->TgtNode(1);
11740         map< double, const SMDS_MeshNode* >::iterator u2n = nodes.begin();
11741         if ( u2n->second == sn0 || u2n->second == sn1 )
11742         {
11743           while ( u2n->second != tn0 && u2n->second != tn1 )
11744             ++u2n;
11745           nodes.erase( nodes.begin(), u2n );
11746         }
11747         u2n = --nodes.end();
11748         if ( u2n->second == sn0 || u2n->second == sn1 )
11749         {
11750           while ( u2n->second != tn0 && u2n->second != tn1 )
11751             --u2n;
11752           nodes.erase( ++u2n, nodes.end() );
11753         }
11754         // set proxy sub-mesh
11755         uvPtVec.resize( nodes.size() );
11756         u2n = nodes.begin();
11757         BRepAdaptor_Curve2d curve( shr->GeomEdge(), F );
11758         for ( size_t i = 0; i < nodes.size(); ++i, ++u2n )
11759         {
11760           uvPtVec[ i ].node = u2n->second;
11761           uvPtVec[ i ].param = u2n->first;
11762           uvPtVec[ i ].SetUV( curve.Value( u2n->first ).XY() );
11763         }
11764         StdMeshers_FaceSide fSide( uvPtVec, F, shr->GeomEdge(), _mesh );
11765         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11766       }
11767
11768       // set proxy mesh of EDGEs with layers
11769       vector< _LayerEdge* > edges;
11770       for ( size_t iS = 0; iS < subEOS.size(); ++iS )
11771       {
11772         _EdgesOnShape& eos = * subEOS[ iS ];
11773         if ( eos.ShapeType() != TopAbs_EDGE ) continue;
11774         if ( eos.size() == 0 )
11775           continue;
11776
11777         const TopoDS_Edge& E = TopoDS::Edge( eos._shape );
11778         data.SortOnEdge( E, eos._edges );
11779
11780         edges.clear();
11781         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 0, E, /*CumOri=*/false )))
11782           if ( !eov->_edges.empty() )
11783             edges.push_back( eov->_edges[0] ); // on 1st VERTEX
11784
11785         edges.insert( edges.end(), eos._edges.begin(), eos._edges.end() );
11786
11787         if ( _EdgesOnShape* eov = data.GetShapeEdges( helper.IthVertex( 1, E, /*CumOri=*/false )))
11788           if ( !eov->_edges.empty() )
11789             edges.push_back( eov->_edges[0] ); // on last VERTEX
11790
11791         uvPtVec.resize( edges.size() );
11792         for ( size_t i = 0; i < edges.size(); ++i )
11793         {
11794           uvPtVec[ i ].node = edges[i]->_nodes.back();
11795           uvPtVec[ i ].param = helper.GetNodeU( E, edges[i]->_nodes[0] );
11796           uvPtVec[ i ].SetUV( helper.GetNodeUV( F, edges[i]->_nodes.back() ));
11797         }
11798         // if ( edges.empty() )
11799         //   continue;
11800         BRep_Tool::Range( E, uvPtVec[0].param, uvPtVec.back().param );
11801         StdMeshers_FaceSide fSide( uvPtVec, F, E, _mesh );
11802         StdMeshers_ViscousLayers2D::SetProxyMeshOfEdge( fSide );
11803       }
11804       // temporary clear the FACE sub-mesh from faces made by refine()
11805       vector< const SMDS_MeshElement* > elems;
11806       elems.reserve( smDS->NbElements() + smDS->NbNodes() );
11807       for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11808         elems.push_back( ite->next() );
11809       for ( SMDS_NodeIteratorPtr ite = smDS->GetNodes(); ite->more(); )
11810         elems.push_back( ite->next() );
11811       smDS->Clear();
11812
11813       // compute the mesh on the FACE
11814       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
11815       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE_SUBMESH );
11816
11817       // re-fill proxy sub-meshes of the FACE
11818       for ( size_t i = 0 ; i < _sdVec.size(); ++i )
11819         if (( psm = _sdVec[i]._proxyMesh->getFaceSubM( F )))
11820           for ( SMDS_ElemIteratorPtr ite = smDS->GetElements(); ite->more(); )
11821             psm->AddElement( ite->next() );
11822
11823       // re-fill smDS
11824       for ( size_t i = 0; i < elems.size(); ++i )
11825         smDS->AddElement( elems[i] );
11826
11827       if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
11828         return error( errMsg );
11829
11830     } // end of re-meshing in case of failed smoothing
11831     else if ( !movedByPeriod )
11832     {
11833       // No wrongly shaped faces remain; final smooth. Set node XYZ.
11834       bool isStructuredFixed = false;
11835       if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
11836         isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
11837       if ( !isStructuredFixed )
11838       {
11839         if ( isConcaveFace ) // fix narrow faces by swapping diagonals
11840           fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
11841
11842         for ( int st = 3; st; --st )
11843         {
11844           switch( st ) {
11845           case 1: smoothType = _SmoothNode::LAPLACIAN; break;
11846           case 2: smoothType = _SmoothNode::LAPLACIAN; break;
11847           case 3: smoothType = _SmoothNode::ANGULAR; break;
11848           }
11849           dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
11850           for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11851           {
11852             nodesToSmooth[i].Smooth( nbBad,surface,helper,refSign,
11853                                      smoothType,/*set3D=*/st==1 );
11854           }
11855           dumpFunctionEnd();
11856         }
11857       }
11858       if ( !getMeshDS()->IsEmbeddedMode() )
11859         // Log node movement
11860         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
11861         {
11862           SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
11863           getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
11864         }
11865     }
11866
11867     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
11868     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
11869     if ( data2 )
11870       VISCOUS_3D::ToClearSubWithMain( sm, data2->_solid );
11871
11872   } // loop on FACES to shrink mesh on
11873
11874
11875   // Replace source nodes by target nodes in shrunk mesh edges
11876
11877   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
11878   for ( ; e2shr != e2shrMap.end(); ++e2shr )
11879     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
11880
11881   return true;
11882 }
11883
11884 //================================================================================
11885 /*!
11886  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
11887  */
11888 //================================================================================
11889
11890 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
11891                                            _EdgesOnShape&         eos,
11892                                            SMESH_MesherHelper&    helper,
11893                                            const SMESHDS_SubMesh* /*faceSubMesh*/)
11894 {
11895   const SMDS_MeshNode* srcNode = edge._nodes[0];
11896   const SMDS_MeshNode* tgtNode = edge._nodes.back();
11897
11898   if ( eos.SWOLType() == TopAbs_FACE )
11899   {
11900     if ( tgtNode->GetPosition()->GetDim() != 2 ) // not inflated edge
11901     {
11902       edge._pos.clear();
11903       edge.Set( _LayerEdge::SHRUNK );
11904       return srcNode == tgtNode;
11905     }
11906     gp_XY srcUV ( edge._pos[0].X(), edge._pos[0].Y() );          //helper.GetNodeUV( F, srcNode );
11907     gp_XY tgtUV = edge.LastUV( TopoDS::Face( eos._sWOL ), eos ); //helper.GetNodeUV( F, tgtNode );
11908     gp_Vec2d uvDir( srcUV, tgtUV );
11909     double uvLen = uvDir.Magnitude();
11910     uvDir /= uvLen;
11911     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
11912     edge._len = uvLen;
11913
11914     //edge._pos.resize(1);
11915     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
11916
11917     // set UV of source node to target node
11918     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
11919     pos->SetUParameter( srcUV.X() );
11920     pos->SetVParameter( srcUV.Y() );
11921   }
11922   else // _sWOL is TopAbs_EDGE
11923   {
11924     if ( tgtNode->GetPosition()->GetDim() != 1 ) // not inflated edge
11925     {
11926       edge._pos.clear();
11927       edge.Set( _LayerEdge::SHRUNK );
11928       return srcNode == tgtNode;
11929     }
11930     const TopoDS_Edge&    E = TopoDS::Edge( eos._sWOL );
11931     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
11932     if ( !edgeSM || edgeSM->NbElements() == 0 )
11933       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11934
11935     const SMDS_MeshNode* n2 = 0;
11936     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
11937     while ( eIt->more() && !n2 )
11938     {
11939       const SMDS_MeshElement* e = eIt->next();
11940       if ( !edgeSM->Contains(e)) continue;
11941       n2 = e->GetNode( 0 );
11942       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
11943     }
11944     if ( !n2 )
11945       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
11946
11947     if ( n2 == tgtNode       || // for 3D_mesh_GHS3D_01/B1
11948          n2 == edge._nodes[1] ) // bos #20643
11949     {
11950       // shrunk by other SOLID
11951       edge.Set( _LayerEdge::SHRUNK ); // ???
11952       return true;
11953     }
11954
11955     double uSrc = helper.GetNodeU( E, srcNode, n2 );
11956     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
11957     double u2   = helper.GetNodeU( E, n2,      srcNode );
11958
11959     //edge._pos.clear();
11960
11961     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
11962     {
11963       // tgtNode is located so that it does not make faces with wrong orientation
11964       edge.Set( _LayerEdge::SHRUNK );
11965       return true;
11966     }
11967     //edge._pos.resize(1);
11968     edge._pos[0].SetCoord( U_TGT, uTgt );
11969     edge._pos[0].SetCoord( U_SRC, uSrc );
11970     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
11971
11972     edge._simplices.resize( 1 );
11973     edge._simplices[0]._nPrev = n2;
11974
11975     // set U of source node to the target node
11976     SMDS_EdgePositionPtr pos = tgtNode->GetPosition();
11977     pos->SetUParameter( uSrc );
11978   }
11979   return true;
11980 }
11981
11982 //================================================================================
11983 /*!
11984  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
11985  */
11986 //================================================================================
11987
11988 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
11989 {
11990   if ( edge._nodes.size() == 1 )
11991   {
11992     edge._pos.clear();
11993     edge._len = 0;
11994
11995     const SMDS_MeshNode* srcNode = edge._nodes[0];
11996     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
11997     if ( S.IsNull() ) return;
11998
11999     gp_Pnt p;
12000
12001     switch ( S.ShapeType() )
12002     {
12003     case TopAbs_EDGE:
12004     {
12005       double f,l;
12006       TopLoc_Location loc;
12007       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
12008       if ( curve.IsNull() ) return;
12009       SMDS_EdgePositionPtr ePos = srcNode->GetPosition();
12010       p = curve->Value( ePos->GetUParameter() );
12011       break;
12012     }
12013     case TopAbs_VERTEX:
12014     {
12015       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
12016       break;
12017     }
12018     default: return;
12019     }
12020     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
12021     dumpMove( srcNode );
12022   }
12023 }
12024
12025 //================================================================================
12026 /*!
12027  * \brief Try to fix triangles with high aspect ratio by swapping diagonals
12028  */
12029 //================================================================================
12030
12031 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
12032                                   SMESH_MesherHelper&         helper,
12033                                   const bool                  is2D,
12034                                   const int                   step,
12035                                   set<const SMDS_MeshNode*> * involvedNodes)
12036 {
12037   SMESH::Controls::AspectRatio qualifier;
12038   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
12039   const double maxAspectRatio = is2D ? 4. : 2;
12040   _NodeCoordHelper xyz( F, helper, is2D );
12041
12042   // find bad triangles
12043
12044   vector< const SMDS_MeshElement* > badTrias;
12045   vector< double >                  badAspects;
12046   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
12047   SMDS_ElemIteratorPtr fIt = sm->GetElements();
12048   while ( fIt->more() )
12049   {
12050     const SMDS_MeshElement * f = fIt->next();
12051     if ( f->NbCornerNodes() != 3 ) continue;
12052     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
12053     double aspect = qualifier.GetValue( points );
12054     if ( aspect > maxAspectRatio )
12055     {
12056       badTrias.push_back( f );
12057       badAspects.push_back( aspect );
12058     }
12059   }
12060   if ( step == 1 )
12061   {
12062     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
12063     SMDS_ElemIteratorPtr fIt = sm->GetElements();
12064     while ( fIt->more() )
12065     {
12066       const SMDS_MeshElement * f = fIt->next();
12067       if ( f->NbCornerNodes() == 3 )
12068         dumpChangeNodes( f );
12069     }
12070     dumpFunctionEnd();
12071   }
12072   if ( badTrias.empty() )
12073     return;
12074
12075   // find couples of faces to swap diagonal
12076
12077   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
12078   vector< T2Trias > triaCouples; 
12079
12080   TIDSortedElemSet involvedFaces, emptySet;
12081   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
12082   {
12083     T2Trias trias    [3];
12084     double  aspRatio [3];
12085     int i1, i2, i3;
12086
12087     if ( !involvedFaces.insert( badTrias[iTia] ).second )
12088       continue;
12089     for ( int iP = 0; iP < 3; ++iP )
12090       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
12091
12092     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
12093     int bestCouple = -1;
12094     for ( int iSide = 0; iSide < 3; ++iSide )
12095     {
12096       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
12097       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
12098       trias [iSide].first  = badTrias[iTia];
12099       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
12100                                                              & i1, & i2 );
12101       if (( ! trias[iSide].second ) ||
12102           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
12103           ( ! sm->Contains( trias[iSide].second )))
12104         continue;
12105
12106       // aspect ratio of an adjacent tria
12107       for ( int iP = 0; iP < 3; ++iP )
12108         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
12109       double aspectInit = qualifier.GetValue( points2 );
12110
12111       // arrange nodes as after diag-swaping
12112       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
12113         i3 = helper.WrapIndex( i1-1, 3 );
12114       else
12115         i3 = helper.WrapIndex( i1+1, 3 );
12116       points1 = points;
12117       points1( 1+ iSide ) = points2( 1+ i3 );
12118       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
12119
12120       // aspect ratio after diag-swaping
12121       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
12122       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
12123         continue;
12124
12125       // prevent inversion of a triangle
12126       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
12127       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
12128       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
12129         continue;
12130
12131       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
12132         bestCouple = iSide;
12133     }
12134
12135     if ( bestCouple >= 0 )
12136     {
12137       triaCouples.push_back( trias[bestCouple] );
12138       involvedFaces.insert ( trias[bestCouple].second );
12139     }
12140     else
12141     {
12142       involvedFaces.erase( badTrias[iTia] );
12143     }
12144   }
12145   if ( triaCouples.empty() )
12146     return;
12147
12148   // swap diagonals
12149
12150   SMESH_MeshEditor editor( helper.GetMesh() );
12151   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12152   for ( size_t i = 0; i < triaCouples.size(); ++i )
12153   {
12154     dumpChangeNodes( triaCouples[i].first );
12155     dumpChangeNodes( triaCouples[i].second );
12156     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
12157   }
12158
12159   if ( involvedNodes )
12160     for ( size_t i = 0; i < triaCouples.size(); ++i )
12161     {
12162       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
12163                              triaCouples[i].first->end_nodes() );
12164       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
12165                              triaCouples[i].second->end_nodes() );
12166     }
12167
12168   // just for debug dump resulting triangles
12169   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
12170   for ( size_t i = 0; i < triaCouples.size(); ++i )
12171   {
12172     dumpChangeNodes( triaCouples[i].first );
12173     dumpChangeNodes( triaCouples[i].second );
12174   }
12175 }
12176
12177 //================================================================================
12178 /*!
12179  * \brief Move target node to it's final position on the FACE during shrinking
12180  */
12181 //================================================================================
12182
12183 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
12184                                  const TopoDS_Face&    F,
12185                                  _EdgesOnShape&        eos,
12186                                  SMESH_MesherHelper&   helper )
12187 {
12188   if ( Is( SHRUNK ))
12189     return false; // already at the target position
12190
12191   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
12192
12193   if ( eos.SWOLType() == TopAbs_FACE )
12194   {
12195     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
12196     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
12197     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
12198     const double uvLen = tgtUV.Distance( curUV );
12199     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
12200
12201     // Select shrinking step such that not to make faces with wrong orientation.
12202     double stepSize = 1e100;
12203     for ( size_t i = 0; i < _simplices.size(); ++i )
12204     {
12205       if ( !_simplices[i]._nPrev->isMarked() ||
12206            !_simplices[i]._nNext->isMarked() )
12207         continue; // simplex of quadrangle created by addBoundaryElements()
12208
12209       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
12210       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev, tgtNode );
12211       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext, tgtNode );
12212       gp_XY dirN = uvN2 - uvN1;
12213       double det = uvDir.Crossed( dirN );
12214       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
12215       gp_XY dirN2Cur = curUV - uvN1;
12216       double step = dirN.Crossed( dirN2Cur ) / det;
12217       if ( step > 0 )
12218         stepSize = Min( step, stepSize );
12219     }
12220     gp_Pnt2d newUV;
12221     if ( uvLen <= stepSize )
12222     {
12223       newUV = tgtUV;
12224       Set( SHRUNK );
12225       //_pos.clear();
12226     }
12227     else if ( stepSize > 0 )
12228     {
12229       newUV = curUV + uvDir.XY() * stepSize * kSafe;
12230     }
12231     else
12232     {
12233       return true;
12234     }
12235     SMDS_FacePositionPtr pos = tgtNode->GetPosition();
12236     pos->SetUParameter( newUV.X() );
12237     pos->SetVParameter( newUV.Y() );
12238
12239 #ifdef __myDEBUG
12240     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12241     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12242     dumpMove( tgtNode );
12243 #else
12244     if ( surface.IsNull() ) {}
12245 #endif
12246   }
12247   else // _sWOL is TopAbs_EDGE
12248   {
12249     const TopoDS_Edge&      E = TopoDS::Edge( eos._sWOL );
12250     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
12251     SMDS_EdgePositionPtr tgtPos = tgtNode->GetPosition();
12252
12253     const double u2     = helper.GetNodeU( E, n2, tgtNode );
12254     const double uSrc   = _pos[0].Coord( U_SRC );
12255     const double lenTgt = _pos[0].Coord( LEN_TGT );
12256
12257     double newU = _pos[0].Coord( U_TGT );
12258     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
12259     {
12260       Set( _LayerEdge::SHRUNK );
12261       //_pos.clear();
12262     }
12263     else
12264     {
12265       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
12266     }
12267     tgtPos->SetUParameter( newU );
12268 #ifdef __myDEBUG
12269     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
12270     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
12271     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
12272     dumpMove( tgtNode );
12273 #endif
12274   }
12275
12276   return true;
12277 }
12278
12279 //================================================================================
12280 /*!
12281  * \brief Perform smooth on the FACE
12282  *  \retval bool - true if the node has been moved
12283  */
12284 //================================================================================
12285
12286 bool _SmoothNode::Smooth(int&                  nbBad,
12287                          Handle(Geom_Surface)& surface,
12288                          SMESH_MesherHelper&   helper,
12289                          const double          refSign,
12290                          SmoothType            how,
12291                          bool                  set3D)
12292 {
12293   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
12294
12295   // get uv of surrounding nodes
12296   vector<gp_XY> uv( _simplices.size() );
12297   for ( size_t i = 0; i < _simplices.size(); ++i )
12298     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
12299
12300   // compute new UV for the node
12301   gp_XY newPos (0,0);
12302   if ( how == TFI && _simplices.size() == 4 )
12303   {
12304     gp_XY corners[4];
12305     for ( size_t i = 0; i < _simplices.size(); ++i )
12306       if ( _simplices[i]._nOpp )
12307         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
12308       else
12309         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
12310
12311     newPos = helper.calcTFI ( 0.5, 0.5,
12312                               corners[0], corners[1], corners[2], corners[3],
12313                               uv[1], uv[2], uv[3], uv[0] );
12314   }
12315   else if ( how == ANGULAR )
12316   {
12317     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
12318   }
12319   else if ( how == CENTROIDAL && _simplices.size() > 3 )
12320   {
12321     // average centers of diagonals wieghted with their reciprocal lengths
12322     if ( _simplices.size() == 4 )
12323     {
12324       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
12325       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
12326       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
12327     }
12328     else
12329     {
12330       double sumWeight = 0;
12331       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
12332       for ( int i = 0; i < nb; ++i )
12333       {
12334         int iFrom = i + 2;
12335         int iTo   = i + _simplices.size() - 1;
12336         for ( int j = iFrom; j < iTo; ++j )
12337         {
12338           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
12339           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
12340           sumWeight += w;
12341           newPos += w * ( uv[i]+uv[i2] );
12342         }
12343       }
12344       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
12345     }
12346   }
12347   else
12348   {
12349     // Laplacian smooth
12350     for ( size_t i = 0; i < _simplices.size(); ++i )
12351       newPos += uv[i];
12352     newPos /= _simplices.size();
12353   }
12354
12355   // count quality metrics (orientation) of triangles around the node
12356   int nbOkBefore = 0;
12357   gp_XY tgtUV = helper.GetNodeUV( face, _node );
12358   for ( size_t i = 0; i < _simplices.size(); ++i )
12359     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
12360
12361   int nbOkAfter = 0;
12362   for ( size_t i = 0; i < _simplices.size(); ++i )
12363     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
12364
12365   if ( nbOkAfter < nbOkBefore )
12366   {
12367     nbBad += _simplices.size() - nbOkBefore;
12368     return false;
12369   }
12370
12371   SMDS_FacePositionPtr pos = _node->GetPosition();
12372   pos->SetUParameter( newPos.X() );
12373   pos->SetVParameter( newPos.Y() );
12374
12375 #ifdef __myDEBUG
12376   set3D = true;
12377 #endif
12378   if ( set3D )
12379   {
12380     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
12381     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
12382     dumpMove( _node );
12383   }
12384
12385   nbBad += _simplices.size() - nbOkAfter;
12386   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
12387 }
12388
12389 //================================================================================
12390 /*!
12391  * \brief Computes new UV using angle based smoothing technique
12392  */
12393 //================================================================================
12394
12395 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
12396                                      const gp_XY&   uvToFix,
12397                                      const double   refSign)
12398 {
12399   uv.push_back( uv.front() );
12400
12401   vector< gp_XY >  edgeDir ( uv.size() );
12402   vector< double > edgeSize( uv.size() );
12403   for ( size_t i = 1; i < edgeDir.size(); ++i )
12404   {
12405     edgeDir [i-1] = uv[i] - uv[i-1];
12406     edgeSize[i-1] = edgeDir[i-1].Modulus();
12407     if ( edgeSize[i-1] < numeric_limits<double>::min() )
12408       edgeDir[i-1].SetX( 100 );
12409     else
12410       edgeDir[i-1] /= edgeSize[i-1] * refSign;
12411   }
12412   edgeDir.back()  = edgeDir.front();
12413   edgeSize.back() = edgeSize.front();
12414
12415   gp_XY  newPos(0,0);
12416   //int    nbEdges = 0;
12417   double sumSize = 0;
12418   for ( size_t i = 1; i < edgeDir.size(); ++i )
12419   {
12420     if ( edgeDir[i-1].X() > 1. ) continue;
12421     int i1 = i-1;
12422     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
12423     if ( i == edgeDir.size() ) break;
12424     gp_XY p = uv[i];
12425     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
12426     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
12427     gp_XY bisec = norm1 + norm2;
12428     double bisecSize = bisec.Modulus();
12429     if ( bisecSize < numeric_limits<double>::min() )
12430     {
12431       bisec = -edgeDir[i1] + edgeDir[i];
12432       bisecSize = bisec.Modulus();
12433     }
12434     bisec /= bisecSize;
12435
12436     gp_XY  dirToN  = uvToFix - p;
12437     double distToN = dirToN.Modulus();
12438     if ( bisec * dirToN < 0 )
12439       distToN = -distToN;
12440
12441     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
12442     //++nbEdges;
12443     sumSize += edgeSize[i1] + edgeSize[i];
12444   }
12445   newPos /= /*nbEdges * */sumSize;
12446   return newPos;
12447 }
12448
12449 //================================================================================
12450 /*!
12451  * \brief Keep a _LayerEdge inflated along the EDGE
12452  */
12453 //================================================================================
12454
12455 void _Shrinker1D::AddEdge( const _LayerEdge*   e,
12456                            _EdgesOnShape&      eos,
12457                            SMESH_MesherHelper& helper )
12458 {
12459   // init
12460   if ( _nodes.empty() )
12461   {
12462     _edges[0] = _edges[1] = 0;
12463     _done = false;
12464   }
12465   // check _LayerEdge
12466   if ( e == _edges[0] || e == _edges[1] || e->_nodes.size() < 2 )
12467     return;
12468   if ( eos.SWOLType() != TopAbs_EDGE )
12469     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12470   if ( _edges[0] && !_geomEdge.IsSame( eos._sWOL ))
12471     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
12472
12473   // store _LayerEdge
12474   _geomEdge = TopoDS::Edge( eos._sWOL );
12475   double f,l;
12476   BRep_Tool::Range( _geomEdge, f,l );
12477   double u = helper.GetNodeU( _geomEdge, e->_nodes[0], e->_nodes.back());
12478   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
12479
12480   // Check if the nodes are already shrunk by another SOLID
12481
12482   const SMDS_MeshNode* tgtNode0 = TgtNode( 0 );
12483   const SMDS_MeshNode* tgtNode1 = TgtNode( 1 );
12484
12485   _done = (( tgtNode0 && tgtNode0->NbInverseElements( SMDSAbs_Edge ) == 2 ) ||
12486            ( tgtNode1 && tgtNode1->NbInverseElements( SMDSAbs_Edge ) == 2 ));
12487   if ( _done )
12488     _nodes.resize( 1, nullptr );
12489
12490   // Update _nodes
12491
12492   if ( _nodes.empty() )
12493   {
12494     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( _geomEdge );
12495     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
12496       return;
12497     TopLoc_Location loc;
12498     Handle(Geom_Curve) C = BRep_Tool::Curve( _geomEdge, loc, f,l );
12499     GeomAdaptor_Curve aCurve(C, f,l);
12500     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
12501
12502     smIdType nbExpectNodes = eSubMesh->NbNodes();
12503     _initU  .reserve( nbExpectNodes );
12504     _normPar.reserve( nbExpectNodes );
12505     _nodes  .reserve( nbExpectNodes );
12506     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
12507     while ( nIt->more() )
12508     {
12509       const SMDS_MeshNode* node = nIt->next();
12510
12511       // skip refinement nodes
12512       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
12513            node == tgtNode0 || node == tgtNode1 )
12514         continue;
12515       bool hasMarkedFace = false;
12516       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
12517       while ( fIt->more() && !hasMarkedFace )
12518         hasMarkedFace = fIt->next()->isMarked();
12519       if ( !hasMarkedFace )
12520         continue;
12521
12522       _nodes.push_back( node );
12523       _initU.push_back( helper.GetNodeU( _geomEdge, node ));
12524       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
12525       _normPar.push_back(  len / totLen );
12526     }
12527   }
12528   else
12529   {
12530     // remove target node of the _LayerEdge from _nodes
12531     size_t nbFound = 0;
12532     for ( size_t i = 0; i < _nodes.size(); ++i )
12533       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
12534         _nodes[i] = 0, nbFound++;
12535     if ( nbFound == _nodes.size() )
12536       _nodes.clear();
12537   }
12538 }
12539
12540 //================================================================================
12541 /*!
12542  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
12543  */
12544 //================================================================================
12545
12546 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
12547 {
12548   if ( _done || _nodes.empty())
12549     return;
12550   const _LayerEdge* e = _edges[0];
12551   if ( !e ) e = _edges[1];
12552   if ( !e ) return;
12553
12554   _done =  (( !_edges[0] || _edges[0]->Is( _LayerEdge::SHRUNK )) &&
12555             ( !_edges[1] || _edges[1]->Is( _LayerEdge::SHRUNK )));
12556
12557   double f,l;
12558   if ( set3D || _done )
12559   {
12560     dumpFunction(SMESH_Comment("shrink1D_E") << helper.GetMeshDS()->ShapeToIndex( _geomEdge )<<
12561                  "_F" << helper.GetSubShapeID() );
12562     Handle(Geom_Curve) C = BRep_Tool::Curve(_geomEdge, f,l);
12563     GeomAdaptor_Curve aCurve(C, f,l);
12564
12565     if ( _edges[0] )
12566       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12567     if ( _edges[1] )
12568       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12569     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
12570
12571     for ( size_t i = 0; i < _nodes.size(); ++i )
12572     {
12573       if ( !_nodes[i] ) continue;
12574       double len = totLen * _normPar[i];
12575       GCPnts_AbscissaPoint discret( aCurve, len, f );
12576       if ( !discret.IsDone() )
12577         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
12578       double u = discret.Parameter();
12579       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12580       pos->SetUParameter( u );
12581       gp_Pnt p = C->Value( u );
12582       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
12583       dumpMove( _nodes[i] );
12584     }
12585     dumpFunctionEnd();
12586   }
12587   else
12588   {
12589     BRep_Tool::Range( _geomEdge, f,l );
12590     if ( _edges[0] )
12591       f = helper.GetNodeU( _geomEdge, _edges[0]->_nodes.back(), _nodes[0] );
12592     if ( _edges[1] )
12593       l = helper.GetNodeU( _geomEdge, _edges[1]->_nodes.back(), _nodes.back() );
12594     
12595     for ( size_t i = 0; i < _nodes.size(); ++i )
12596     {
12597       if ( !_nodes[i] ) continue;
12598       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
12599       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12600       pos->SetUParameter( u );
12601     }
12602   }
12603 }
12604
12605 //================================================================================
12606 /*!
12607  * \brief Restore initial parameters of nodes on EDGE
12608  */
12609 //================================================================================
12610
12611 void _Shrinker1D::RestoreParams()
12612 {
12613   if ( _done )
12614     for ( size_t i = 0; i < _nodes.size(); ++i )
12615     {
12616       if ( !_nodes[i] ) continue;
12617       SMDS_EdgePositionPtr pos = _nodes[i]->GetPosition();
12618       pos->SetUParameter( _initU[i] );
12619     }
12620   _done = false;
12621 }
12622
12623 //================================================================================
12624 /*!
12625  * \brief Replace source nodes by target nodes in shrunk mesh edges
12626  */
12627 //================================================================================
12628
12629 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
12630 {
12631   const SMDS_MeshNode* nodes[3];
12632   for ( int i = 0; i < 2; ++i )
12633   {
12634     if ( !_edges[i] ) continue;
12635
12636     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _geomEdge );
12637     if ( !eSubMesh ) return;
12638     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
12639     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
12640     const SMDS_MeshNode* scdNode = _edges[i]->_nodes[1];
12641     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
12642     while ( eIt->more() )
12643     {
12644       const SMDS_MeshElement* e = eIt->next();
12645       if ( !eSubMesh->Contains( e ) || e->GetNodeIndex( scdNode ) >= 0 )
12646           continue;
12647       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
12648       for ( int iN = 0; iN < e->NbNodes(); ++iN )
12649       {
12650         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
12651         nodes[iN] = ( n == srcNode ? tgtNode : n );
12652       }
12653       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
12654     }
12655   }
12656 }
12657
12658 //================================================================================
12659 /*!
12660  * \brief Setup quadPoints
12661  */
12662 //================================================================================
12663
12664 _Mapper2D::_Mapper2D( const TParam2ColumnMap & param2ColumnMap, const TNode2Edge& n2eMap )
12665 {
12666   size_t i, iSize = _quadPoints.iSize = param2ColumnMap.size();
12667   size_t j, jSize = _quadPoints.jSize = param2ColumnMap.begin()->second.size();
12668   if ( _quadPoints.iSize < 3 ||
12669        _quadPoints.jSize < 3 )
12670     return;
12671   _quadPoints.uv_grid.resize( iSize * jSize );
12672
12673   // set nodes
12674   i = 0;
12675   for ( auto & u_columnNodes : param2ColumnMap )
12676   {
12677     for ( j = 0; j < u_columnNodes.second.size(); ++j )
12678       _quadPoints.UVPt( i, j ).node = u_columnNodes.second[ j ];
12679     ++i;
12680   }
12681
12682   // compute x parameter on borders
12683   uvPnt( 0, 0       ).x = 0;
12684   uvPnt( 0, jSize-1 ).x = 0;
12685   gp_Pnt p0, pPrev0 = SMESH_NodeXYZ( uvPnt( 0, 0       ).node );
12686   gp_Pnt p1, pPrev1 = SMESH_NodeXYZ( uvPnt( 0, jSize-1 ).node );
12687   for ( i = 1; i < iSize; ++i )
12688   {
12689     p0 = SMESH_NodeXYZ( uvPnt( i, 0       ).node );
12690     p1 = SMESH_NodeXYZ( uvPnt( i, jSize-1 ).node );
12691     uvPnt( i, 0       ).x = uvPnt( i-1, 0       ).x + p0.Distance( pPrev0 );
12692     uvPnt( i, jSize-1 ).x = uvPnt( i-1, jSize-1 ).x + p1.Distance( pPrev1 );
12693     pPrev0 = p0;
12694     pPrev1 = p1;
12695   }
12696   for ( i = 1; i < iSize-1; ++i )
12697   {
12698     uvPnt( i, 0       ).x /= uvPnt( iSize-1, 0       ).x;
12699     uvPnt( i, jSize-1 ).x /= uvPnt( iSize-1, jSize-1 ).x;
12700     uvPnt( i, 0       ).y = 0;
12701     uvPnt( i, jSize-1 ).y = 1;
12702   }
12703
12704   // compute y parameter on borders
12705   uvPnt( 0,       0 ).y = 0;
12706   uvPnt( iSize-1, 0 ).y = 0;
12707   pPrev0 = SMESH_NodeXYZ( uvPnt( 0,       0 ).node );
12708   pPrev1 = SMESH_NodeXYZ( uvPnt( iSize-1, 0 ).node );
12709   for ( j = 1; j < jSize; ++j )
12710   {
12711     p0 = SMESH_NodeXYZ( uvPnt( 0,       j ).node );
12712     p1 = SMESH_NodeXYZ( uvPnt( iSize-1, j ).node );
12713     uvPnt( 0,       j ).y = uvPnt( 0,       j-1 ).y + p0.Distance( pPrev0 );
12714     uvPnt( iSize-1, j ).y = uvPnt( iSize-1, j-1 ).y + p1.Distance( pPrev1 );
12715     pPrev0 = p0;
12716     pPrev1 = p1;
12717   }
12718   for ( j = 1; j < jSize-1; ++j )
12719   {
12720     uvPnt( 0,       j ).y /= uvPnt( 0,       jSize-1 ).y;
12721     uvPnt( iSize-1, j ).y /= uvPnt( iSize-1, jSize-1 ).y;
12722     uvPnt( 0,       j ).x = 0;
12723     uvPnt( iSize-1, j ).x = 1;
12724   }
12725
12726   // compute xy of internal nodes
12727   for ( i = 1; i < iSize-1; ++i )
12728   {
12729     const double x0 = uvPnt( i, 0       ).x;
12730     const double x1 = uvPnt( i, jSize-1 ).x;
12731     for ( j = 1; j < jSize-1; ++j )
12732     {
12733       const double y0 = uvPnt( 0,       j ).y;
12734       const double y1 = uvPnt( iSize-1, j ).y;
12735       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
12736       double y = y0 + x * (y1 - y0);
12737       uvPnt( i, j ).x = x;
12738       uvPnt( i, j ).y = y;
12739     }
12740   }
12741
12742   // replace base nodes with target ones
12743   for ( i = 0; i < iSize; ++i )
12744     for ( j = 0; j < jSize; ++j )
12745     {
12746       auto n2e = n2eMap.find( uvPnt( i, j ).node );
12747       uvPnt( i, j ).node = n2e->second->_nodes.back();
12748     }
12749
12750   return;
12751 }
12752
12753 //================================================================================
12754 /*!
12755  * \brief Compute positions of nodes of 2D structured mesh using TFI
12756  */
12757 //================================================================================
12758
12759 bool _Mapper2D::ComputeNodePositions()
12760 {
12761   if ( _quadPoints.uv_grid.empty() )
12762     return true;
12763
12764   size_t i, iSize = _quadPoints.iSize;
12765   size_t j, jSize = _quadPoints.jSize;
12766
12767   SMESH_NodeXYZ a0 ( uvPnt( 0,       0       ).node );
12768   SMESH_NodeXYZ a1 ( uvPnt( iSize-1, 0       ).node );
12769   SMESH_NodeXYZ a2 ( uvPnt( iSize-1, jSize-1 ).node );
12770   SMESH_NodeXYZ a3 ( uvPnt( 0,       jSize-1 ).node );
12771
12772   for ( i = 1; i < iSize-1; ++i )
12773   {
12774     SMESH_NodeXYZ p0 ( uvPnt( i, 0       ).node );
12775     SMESH_NodeXYZ p2 ( uvPnt( i, jSize-1 ).node );
12776     for ( j = 1; j < jSize-1; ++j )
12777     {
12778       SMESH_NodeXYZ p1 ( uvPnt( iSize-1, j ).node );
12779       SMESH_NodeXYZ p3 ( uvPnt( 0,       j ).node );
12780       double x = uvPnt( i, j ).x;
12781       double y = uvPnt( i, j ).y;
12782
12783       gp_XYZ p = SMESH_MesherHelper::calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
12784       const_cast< SMDS_MeshNode* >( uvPnt( i, j ).node )->setXYZ( p.X(), p.Y(), p.Z() );
12785
12786       dumpMove( uvPnt( i, j ).node );
12787     }
12788   }
12789   return true;
12790 }
12791
12792 //================================================================================
12793 /*!
12794  * \brief Creates 2D and 1D elements on boundaries of new prisms
12795  */
12796 //================================================================================
12797
12798 bool _ViscousBuilder::addBoundaryElements(_SolidData& data)
12799 {
12800   SMESH_MesherHelper helper( *_mesh );
12801
12802   vector< const SMDS_MeshNode* > faceNodes;
12803
12804   //for ( size_t i = 0; i < _sdVec.size(); ++i )
12805   {
12806     //_SolidData& data = _sdVec[i];
12807     TopTools_IndexedMapOfShape geomEdges;
12808     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
12809     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
12810     {
12811       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
12812       const TGeomID edgeID = getMeshDS()->ShapeToIndex( E );
12813       if ( data._noShrinkShapes.count( edgeID ))
12814         continue;
12815
12816       // Get _LayerEdge's based on E
12817
12818       map< double, const SMDS_MeshNode* > u2nodes;
12819       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
12820         continue;
12821
12822       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
12823       TNode2Edge & n2eMap = data._n2eMap;
12824       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
12825       {
12826         //check if 2D elements are needed on E
12827         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
12828         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
12829         ledges.push_back( n2e->second );
12830         u2n++;
12831         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
12832           continue; // no layers on E
12833         ledges.push_back( n2eMap[ u2n->second ]);
12834
12835         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
12836         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
12837         int nbSharedPyram = 0;
12838         SMDS_ElemIteratorPtr vIt = tgtN1->GetInverseElementIterator(SMDSAbs_Volume);
12839         while ( vIt->more() )
12840         {
12841           const SMDS_MeshElement* v = vIt->next();
12842           nbSharedPyram += int( v->GetNodeIndex( tgtN0 ) >= 0 );
12843         }
12844         if ( nbSharedPyram > 1 )
12845           continue; // not free border of the pyramid
12846
12847         faceNodes.clear();
12848         faceNodes.push_back( ledges[0]->_nodes[0] );
12849         faceNodes.push_back( ledges[1]->_nodes[0] );
12850         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
12851         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
12852
12853         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
12854           continue; // faces already created
12855       }
12856       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
12857         ledges.push_back( n2eMap[ u2n->second ]);
12858
12859       // Find out orientation and type of face to create
12860
12861       bool reverse = false, isOnFace;
12862       TopoDS_Shape F;
12863
12864       map< TGeomID, TopoDS_Shape >::iterator e2f = data._shrinkShape2Shape.find( edgeID );
12865       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
12866       {
12867         F = e2f->second.Oriented( TopAbs_FORWARD );
12868         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
12869         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
12870           reverse = !reverse, F.Reverse();
12871         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
12872           reverse = !reverse;
12873       }
12874       else if ( !data._ignoreFaceIds.count( e2f->first ))
12875       {
12876         // find FACE with layers sharing E
12877         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE, &data._solid );
12878         if ( fIt->more() )
12879           F = *( fIt->next() );
12880       }
12881       // Find the sub-mesh to add new faces
12882       SMESHDS_SubMesh* sm = 0;
12883       if ( isOnFace )
12884         sm = getMeshDS()->MeshElements( F );
12885       else
12886         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
12887       if ( !sm )
12888         return error("error in addBoundaryElements()", data._index);
12889
12890       // Find a proxy sub-mesh of the FACE of an adjacent SOLID, which will use the new boundary
12891       // faces for 3D meshing (PAL23414)
12892       SMESHDS_SubMesh* adjSM = 0;
12893       if ( isOnFace )
12894       {
12895         const TGeomID   faceID = sm->GetID();
12896         PShapeIteratorPtr soIt = helper.GetAncestors( F, *_mesh, TopAbs_SOLID );
12897         while ( const TopoDS_Shape* solid = soIt->next() )
12898           if ( !solid->IsSame( data._solid ))
12899           {
12900             size_t iData = _solids.FindIndex( *solid ) - 1;
12901             if ( iData < _sdVec.size() &&
12902                  _sdVec[ iData ]._ignoreFaceIds.count( faceID ) &&
12903                  _sdVec[ iData ]._shrinkShape2Shape.count( edgeID ) == 0 )
12904             {
12905               SMESH_ProxyMesh::SubMesh* proxySub =
12906                 _sdVec[ iData ]._proxyMesh->getFaceSubM( TopoDS::Face( F ), /*create=*/false);
12907               if ( proxySub && proxySub->NbElements() > 0 )
12908                 adjSM = proxySub;
12909             }
12910           }
12911       }
12912
12913       // Make faces
12914       const int dj1 = reverse ? 0 : 1;
12915       const int dj2 = reverse ? 1 : 0;
12916       vector< const SMDS_MeshElement*> ff; // new faces row
12917       SMESHDS_Mesh* m = getMeshDS();
12918       for ( size_t j = 1; j < ledges.size(); ++j )
12919       {
12920         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
12921         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
12922         ff.resize( std::max( nn1.size(), nn2.size() ), NULL );
12923         if ( nn1.size() == nn2.size() )
12924         {
12925           if ( isOnFace )
12926             for ( size_t z = 1; z < nn1.size(); ++z )
12927               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12928           else
12929             for ( size_t z = 1; z < nn1.size(); ++z )
12930               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
12931         }
12932         else if ( nn1.size() == 1 )
12933         {
12934           if ( isOnFace )
12935             for ( size_t z = 1; z < nn2.size(); ++z )
12936               sm->AddElement( ff[z-1] = m->AddFace( nn1[0], nn2[z-1], nn2[z] ));
12937           else
12938             for ( size_t z = 1; z < nn2.size(); ++z )
12939               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
12940         }
12941         else
12942         {
12943           if ( isOnFace )
12944             for ( size_t z = 1; z < nn1.size(); ++z )
12945               sm->AddElement( ff[z-1] = m->AddFace( nn1[z-1], nn2[0], nn1[z] ));
12946           else
12947             for ( size_t z = 1; z < nn1.size(); ++z )
12948               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
12949         }
12950
12951         if ( adjSM ) // add faces to a proxy SM of the adjacent SOLID
12952         {
12953           for ( size_t z = 0; z < ff.size(); ++z )
12954             if ( ff[ z ])
12955               adjSM->AddElement( ff[ z ]);
12956           ff.clear();
12957         }
12958       }
12959
12960       // Make edges
12961       for ( int isFirst = 0; isFirst < 2; ++isFirst )
12962       {
12963         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
12964         _EdgesOnShape* eos = data.GetShapeEdges( edge );
12965         if ( eos && eos->SWOLType() == TopAbs_EDGE )
12966         {
12967           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
12968           if ( nn.size() < 2 || nn[1]->NbInverseElements( SMDSAbs_Edge ) >= 2 )
12969             continue;
12970           helper.SetSubShape( eos->_sWOL );
12971           helper.SetElementsOnShape( true );
12972           for ( size_t z = 1; z < nn.size(); ++z )
12973             helper.AddEdge( nn[z-1], nn[z] );
12974         }
12975       }
12976
12977     } // loop on EDGE's
12978   } // loop on _SolidData's
12979
12980   return true;
12981 }