Salome HOME
IPAL52478: Too thin viscous layers are constructed
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers.cxx
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers.cxx
21 // Created   : Wed Dec  1 15:15:34 2010
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_ProxyMesh.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRepAdaptor_Surface.hxx>
49 #include <BRepLProp_SLProps.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <Bnd_B3d.hxx>
53 #include <ElCLib.hxx>
54 #include <GCPnts_AbscissaPoint.hxx>
55 #include <Geom2d_Circle.hxx>
56 #include <Geom2d_Line.hxx>
57 #include <Geom2d_TrimmedCurve.hxx>
58 #include <GeomAdaptor_Curve.hxx>
59 #include <GeomLib.hxx>
60 #include <Geom_Circle.hxx>
61 #include <Geom_Curve.hxx>
62 #include <Geom_Line.hxx>
63 #include <Geom_TrimmedCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_Failure.hxx>
67 #include <TColStd_Array1OfReal.hxx>
68 #include <TopExp.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopTools_IndexedMapOfShape.hxx>
71 #include <TopTools_ListOfShape.hxx>
72 #include <TopTools_MapOfShape.hxx>
73 #include <TopoDS.hxx>
74 #include <TopoDS_Edge.hxx>
75 #include <TopoDS_Face.hxx>
76 #include <TopoDS_Vertex.hxx>
77 #include <gp_Ax1.hxx>
78 #include <gp_Vec.hxx>
79 #include <gp_XY.hxx>
80
81 #include <list>
82 #include <string>
83 #include <cmath>
84 #include <limits>
85
86 #ifdef _DEBUG_
87 //#define __myDEBUG
88 //#define __NOT_INVALIDATE_BAD_SMOOTH
89 #endif
90
91 using namespace std;
92
93 //================================================================================
94 namespace VISCOUS_3D
95 {
96   typedef int TGeomID;
97
98   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
99
100   const double theMinSmoothCosin = 0.1;
101   const double theSmoothThickToElemSizeRatio = 0.3;
102
103   // what part of thickness is allowed till intersection
104   // defined by SALOME_TESTS/Grids/smesh/viscous_layers_00/A5
105   const double theThickToIntersection = 1.5;
106
107   bool needSmoothing( double cosin, double tgtThick, double elemSize )
108   {
109     return cosin * tgtThick > theSmoothThickToElemSizeRatio * elemSize;
110   }
111
112   /*!
113    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
114    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
115    */
116   struct _MeshOfSolid : public SMESH_ProxyMesh,
117                         public SMESH_subMeshEventListenerData
118   {
119     bool                  _n2nMapComputed;
120     SMESH_ComputeErrorPtr _warning;
121
122     _MeshOfSolid( SMESH_Mesh* mesh)
123       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
124     {
125       SMESH_ProxyMesh::setMesh( *mesh );
126     }
127
128     // returns submesh for a geom face
129     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
130     {
131       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
132       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
133     }
134     void setNode2Node(const SMDS_MeshNode*                 srcNode,
135                       const SMDS_MeshNode*                 proxyNode,
136                       const SMESH_ProxyMesh::SubMesh* subMesh)
137     {
138       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
139     }
140   };
141   //--------------------------------------------------------------------------------
142   /*!
143    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
144    * It is used to clear an inferior dim sub-meshes modified by viscous layers
145    */
146   class _ShrinkShapeListener : SMESH_subMeshEventListener
147   {
148     _ShrinkShapeListener()
149       : SMESH_subMeshEventListener(/*isDeletable=*/false,
150                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
151   public:
152     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
153     virtual void ProcessEvent(const int                       event,
154                               const int                       eventType,
155                               SMESH_subMesh*                  solidSM,
156                               SMESH_subMeshEventListenerData* data,
157                               const SMESH_Hypothesis*         hyp)
158     {
159       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
160       {
161         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
162       }
163     }
164   };
165   //--------------------------------------------------------------------------------
166   /*!
167    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
168    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
169    * delete the data as soon as it has been used
170    */
171   class _ViscousListener : SMESH_subMeshEventListener
172   {
173     _ViscousListener():
174       SMESH_subMeshEventListener(/*isDeletable=*/false,
175                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
176     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
177   public:
178     virtual void ProcessEvent(const int                       event,
179                               const int                       eventType,
180                               SMESH_subMesh*                  subMesh,
181                               SMESH_subMeshEventListenerData* data,
182                               const SMESH_Hypothesis*         hyp)
183     {
184       if ( SMESH_subMesh::COMPUTE_EVENT       == eventType &&
185            SMESH_subMesh::CHECK_COMPUTE_STATE != event)
186       {
187         // delete SMESH_ProxyMesh containing temporary faces
188         subMesh->DeleteEventListener( this );
189       }
190     }
191     // Finds or creates proxy mesh of the solid
192     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
193                                       const TopoDS_Shape& solid,
194                                       bool                toCreate=false)
195     {
196       if ( !mesh ) return 0;
197       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
198       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
199       if ( !data && toCreate )
200       {
201         data = new _MeshOfSolid(mesh);
202         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
203         sm->SetEventListener( Get(), data, sm );
204       }
205       return data;
206     }
207     // Removes proxy mesh of the solid
208     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
209     {
210       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
211     }
212   };
213   
214   //================================================================================
215   /*!
216    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
217    * the main shape when sub-mesh of the main shape is cleared,
218    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
219    * is cleared
220    */
221   //================================================================================
222
223   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
224   {
225     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
226     SMESH_subMeshEventListenerData* data =
227       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
228     if ( data )
229     {
230       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
231            data->mySubMeshes.end())
232         data->mySubMeshes.push_back( sub );
233     }
234     else
235     {
236       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
237       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
238     }
239   }
240   struct _SolidData;
241   //--------------------------------------------------------------------------------
242   /*!
243    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
244    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
245    * The class is used to check validity of face or volumes around a smoothed node;
246    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
247    */
248   struct _Simplex
249   {
250     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
251     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
252     _Simplex(const SMDS_MeshNode* nPrev=0,
253              const SMDS_MeshNode* nNext=0,
254              const SMDS_MeshNode* nOpp=0)
255       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
256     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt, double& vol) const
257     {
258       const double M[3][3] =
259         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
260          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
261          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
262       vol = ( + M[0][0]*M[1][1]*M[2][2]
263               + M[0][1]*M[1][2]*M[2][0]
264               + M[0][2]*M[1][0]*M[2][1]
265               - M[0][0]*M[1][2]*M[2][1]
266               - M[0][1]*M[1][0]*M[2][2]
267               - M[0][2]*M[1][1]*M[2][0]);
268       return vol > 1e-100;
269     }
270     bool IsForward(const gp_XY&         tgtUV,
271                    const SMDS_MeshNode* smoothedNode,
272                    const TopoDS_Face&   face,
273                    SMESH_MesherHelper&  helper,
274                    const double         refSign) const
275     {
276       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
277       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
278       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
279       double d = v1 ^ v2;
280       return d*refSign > 1e-100;
281     }
282     bool IsNeighbour(const _Simplex& other) const
283     {
284       return _nPrev == other._nNext || _nNext == other._nPrev;
285     }
286     static void GetSimplices( const SMDS_MeshNode* node,
287                               vector<_Simplex>&   simplices,
288                               const set<TGeomID>& ingnoreShapes,
289                               const _SolidData*   dataToCheckOri = 0,
290                               const bool          toSort = false);
291     static void SortSimplices(vector<_Simplex>& simplices);
292   };
293   //--------------------------------------------------------------------------------
294   /*!
295    * Structure used to take into account surface curvature while smoothing
296    */
297   struct _Curvature
298   {
299     double _r; // radius
300     double _k; // factor to correct node smoothed position
301     double _h2lenRatio; // avgNormProj / (2*avgDist)
302   public:
303     static _Curvature* New( double avgNormProj, double avgDist )
304     {
305       _Curvature* c = 0;
306       if ( fabs( avgNormProj / avgDist ) > 1./200 )
307       {
308         c = new _Curvature;
309         c->_r = avgDist * avgDist / avgNormProj;
310         c->_k = avgDist * avgDist / c->_r / c->_r;
311         //c->_k = avgNormProj / c->_r;
312         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
313         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
314       }
315       return c;
316     }
317     double lenDelta(double len) const { return _k * ( _r + len ); }
318     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
319   };
320   //--------------------------------------------------------------------------------
321
322   struct _2NearEdges;
323   struct _LayerEdge;
324   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
325
326   //--------------------------------------------------------------------------------
327   /*!
328    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
329    * and a node of the most internal layer (_nodes.back())
330    */
331   struct _LayerEdge
332   {
333     typedef gp_XYZ (_LayerEdge::*PSmooFun)();
334
335     vector< const SMDS_MeshNode*> _nodes;
336
337     gp_XYZ              _normal; // to solid surface
338     vector<gp_XYZ>      _pos; // points computed during inflation
339     double              _len; // length achived with the last inflation step
340     double              _cosin; // of angle (_normal ^ surface)
341     double              _lenFactor; // to compute _len taking _cosin into account
342
343     // face or edge w/o layer along or near which _LayerEdge is inflated
344     TopoDS_Shape        _sWOL;
345     // simplices connected to the source node (_nodes[0]);
346     // used for smoothing and quality check of _LayerEdge's based on the FACE
347     vector<_Simplex>    _simplices;
348     PSmooFun            _smooFunction; // smoothing function
349     // data for smoothing of _LayerEdge's based on the EDGE
350     _2NearEdges*        _2neibors;
351
352     _Curvature*         _curvature;
353     // TODO:: detele _Curvature, _plnNorm
354
355     void SetNewLength( double len, SMESH_MesherHelper& helper );
356     bool SetNewLength2d( Handle(Geom_Surface)& surface,
357                          const TopoDS_Face&    F,
358                          SMESH_MesherHelper&   helper );
359     void SetDataByNeighbors( const SMDS_MeshNode* n1,
360                              const SMDS_MeshNode* n2,
361                              SMESH_MesherHelper&  helper);
362     void InvalidateStep( int curStep, bool restoreLength=false );
363     void ChooseSmooFunction(const set< TGeomID >& concaveVertices,
364                             const TNode2Edge&     n2eMap);
365     bool Smooth(int& badNb, const int step, const bool isConcaveFace);
366     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
367                       const TopoDS_Face&    F,
368                       SMESH_MesherHelper&   helper);
369     bool FindIntersection( SMESH_ElementSearcher&   searcher,
370                            double &                 distance,
371                            const double&            epsilon,
372                            const SMDS_MeshElement** face = 0);
373     bool SegTriaInter( const gp_Ax1&        lastSegment,
374                        const SMDS_MeshNode* n0,
375                        const SMDS_MeshNode* n1,
376                        const SMDS_MeshNode* n2,
377                        double&              dist,
378                        const double&        epsilon) const;
379     gp_Ax1 LastSegment(double& segLen) const;
380     gp_XY  LastUV( const TopoDS_Face& F ) const;
381     bool   IsOnEdge() const { return _2neibors; }
382     gp_XYZ Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
383     void   SetCosin( double cosin );
384     int    NbSteps() const { return _pos.size() - 1; } // nb inlation steps
385
386     gp_XYZ smoothLaplacian();
387     gp_XYZ smoothAngular();
388     gp_XYZ smoothLengthWeighted();
389     gp_XYZ smoothCentroidal();
390     gp_XYZ smoothNefPolygon();
391
392     enum { FUN_LAPLACIAN, FUN_LENWEIGHTED, FUN_CENTROIDAL, FUN_NEFPOLY, FUN_ANGULAR, FUN_NB };
393     static const int theNbSmooFuns = FUN_NB;
394     static PSmooFun _funs[theNbSmooFuns];
395     static const char* _funNames[theNbSmooFuns+1];
396     int smooFunID( PSmooFun fun=0) const;
397   };
398   _LayerEdge::PSmooFun _LayerEdge::_funs[theNbSmooFuns] = { &_LayerEdge::smoothLaplacian,
399                                                             &_LayerEdge::smoothLengthWeighted,
400                                                             &_LayerEdge::smoothCentroidal,
401                                                             &_LayerEdge::smoothNefPolygon,
402                                                             &_LayerEdge::smoothAngular };
403   const char* _LayerEdge::_funNames[theNbSmooFuns+1] = { "Laplacian",
404                                                          "LengthWeighted",
405                                                          "Centroidal",
406                                                          "NefPolygon",
407                                                          "Angular",
408                                                          "None"};
409   struct _LayerEdgeCmp
410   {
411     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
412     {
413       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
414       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
415     }
416   };
417   //--------------------------------------------------------------------------------
418   /*!
419    * A 2D half plane used by _LayerEdge::smoothNefPolygon()
420    */
421   struct _halfPlane
422   {
423     gp_XY _pos, _dir, _inNorm;
424     bool IsOut( const gp_XY p, const double tol ) const
425     {
426       return _inNorm * ( p - _pos ) < -tol;
427     }
428     bool FindInterestion( const _halfPlane& hp, gp_XY & intPnt )
429     {
430       const double eps = 1e-10;
431       double D = _dir.Crossed( hp._dir );
432       if ( fabs(D) < std::numeric_limits<double>::min())
433         return false;
434       gp_XY vec21 = _pos - hp._pos; 
435       double u = hp._dir.Crossed( vec21 ) / D; 
436       intPnt = _pos + _dir * u;
437       return true;
438     }
439   };
440   //--------------------------------------------------------------------------------
441   /*!
442    * Structure used to smooth a _LayerEdge based on an EDGE.
443    */
444   struct _2NearEdges
445   {
446     double               _wgt  [2]; // weights of _nodes
447     _LayerEdge*          _edges[2];
448
449      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
450     gp_XYZ*              _plnNorm;
451
452     _2NearEdges() { _edges[0]=_edges[1]=0; _plnNorm = 0; }
453     const SMDS_MeshNode* tgtNode(bool is2nd) {
454       return _edges[is2nd] ? _edges[is2nd]->_nodes.back() : 0;
455     }
456     const SMDS_MeshNode* srcNode(bool is2nd) {
457       return _edges[is2nd] ? _edges[is2nd]->_nodes[0] : 0;
458     }
459     void reverse() {
460       std::swap( _wgt  [0], _wgt  [1] );
461       std::swap( _edges[0], _edges[1] );
462     }
463   };
464   //--------------------------------------------------------------------------------
465   /*!
466    * \brief Convex FACE whose radius of curvature is less than the thickness of 
467    *        layers. It is used to detect distortion of prisms based on a convex
468    *        FACE and to update normals to enable further increasing the thickness
469    */
470   struct _ConvexFace
471   {
472     TopoDS_Face                     _face;
473
474     // edges whose _simplices are used to detect prism destorsion
475     vector< _LayerEdge* >           _simplexTestEdges;
476
477     // map a sub-shape to it's index in _SolidData::_endEdgeOnShape vector
478     map< TGeomID, int >             _subIdToEdgeEnd;
479
480     bool                            _normalsFixed;
481
482     bool GetCenterOfCurvature( _LayerEdge*         ledge,
483                                BRepLProp_SLProps&  surfProp,
484                                SMESH_MesherHelper& helper,
485                                gp_Pnt &            center ) const;
486     bool CheckPrisms() const;
487   };
488
489   //--------------------------------------------------------------------------------
490   /*!
491    * \brief Layers parameters got by averaging several hypotheses
492    */
493   struct AverageHyp
494   {
495     AverageHyp( const StdMeshers_ViscousLayers* hyp = 0 )
496       :_nbLayers(0), _nbHyps(0), _thickness(0), _stretchFactor(0)
497     {
498       Add( hyp );
499     }
500     void Add( const StdMeshers_ViscousLayers* hyp )
501     {
502       if ( hyp )
503       {
504         _nbHyps++;
505         _nbLayers       = hyp->GetNumberLayers();
506         //_thickness     += hyp->GetTotalThickness();
507         _thickness      = Max( _thickness, hyp->GetTotalThickness() );
508         _stretchFactor += hyp->GetStretchFactor();
509       }
510     }
511     double GetTotalThickness() const { return _thickness; /*_nbHyps ? _thickness / _nbHyps : 0;*/ }
512     double GetStretchFactor()  const { return _nbHyps ? _stretchFactor / _nbHyps : 0; }
513     int    GetNumberLayers()   const { return _nbLayers; }
514   private:
515     int     _nbLayers, _nbHyps;
516     double  _thickness, _stretchFactor;
517   };
518
519   //--------------------------------------------------------------------------------
520   /*!
521    * \brief Data of a SOLID
522    */
523   struct _SolidData
524   {
525     typedef const StdMeshers_ViscousLayers* THyp;
526     TopoDS_Shape                    _solid;
527     TGeomID                         _index; // SOLID id
528     _MeshOfSolid*                   _proxyMesh;
529     list< THyp >                    _hyps;
530     list< TopoDS_Shape >            _hypShapes;
531     map< TGeomID, THyp >            _face2hyp; // filled if _hyps.size() > 1
532     set< TGeomID >                  _reversedFaceIds;
533     set< TGeomID >                  _ignoreFaceIds; // WOL FACEs and FACEs of other SOLIDs
534
535     double                          _stepSize, _stepSizeCoeff, _geomSize;
536     const SMDS_MeshNode*            _stepSizeNodes[2];
537
538     TNode2Edge                      _n2eMap; // nodes and _LayerEdge's based on them
539
540     // map to find _n2eMap of another _SolidData by a shrink shape shared by two _SolidData's
541     map< TGeomID, TNode2Edge* >     _s2neMap;
542     // edges of _n2eMap. We keep same data in two containers because
543     // iteration over the map is 5 times longer than over the vector
544     vector< _LayerEdge* >           _edges;
545
546     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
547     //        layers and a FACE w/o layers
548     // value: the shape (FACE or EDGE) to shrink mesh on.
549     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
550     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
551
552     // Convex FACEs whose radius of curvature is less than the thickness of layers
553     map< TGeomID, _ConvexFace >      _convexFaces;
554
555     // shapes (EDGEs and VERTEXes) srink from which is forbidden due to collisions with
556     // the adjacent SOLID
557     set< TGeomID >                   _noShrinkShapes;
558
559     // <EDGE to smooth on> to <it's curve> -- for analytic smooth
560     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
561
562     // end indices in _edges of _LayerEdge on each shape, first go shapes to smooth
563     vector< int >                    _endEdgeOnShape;
564     int                              _nbShapesToSmooth;
565     set< TGeomID >                   _concaveFaces;
566
567     // data of averaged StdMeshers_ViscousLayers parameters for each shape with _LayerEdge's
568     vector< AverageHyp >             _hypOnShape;
569     double                           _maxThickness; // of all _hyps
570     double                           _minThickness; // of all _hyps
571
572     double                           _epsilon; // precision for SegTriaInter()
573
574     _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
575                _MeshOfSolid*       m=0)
576       :_solid(s), _proxyMesh(m) {}
577     ~_SolidData();
578
579     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
580                                        const int             iFrom,
581                                        const int             iTo,
582                                        const TopoDS_Face&    F,
583                                        SMESH_MesherHelper&   helper,
584                                        vector<_LayerEdge* >* edges=0);
585
586     void SortOnEdge( const TopoDS_Edge&  E,
587                      const int           iFrom,
588                      const int           iTo,
589                      SMESH_MesherHelper& helper);
590
591     void Sort2NeiborsOnEdge( const int iFrom, const int iTo);
592
593     _ConvexFace* GetConvexFace( const TGeomID faceID )
594     {
595       map< TGeomID, _ConvexFace >::iterator id2face = _convexFaces.find( faceID );
596       return id2face == _convexFaces.end() ? 0 : & id2face->second;
597     }
598     void GetEdgesOnShape( size_t end, int &  iBeg, int &  iEnd )
599     {
600       iBeg = end > 0 ? _endEdgeOnShape[ end-1 ] : 0;
601       iEnd = _endEdgeOnShape[ end ];
602     }
603
604     bool GetShapeEdges(const TGeomID shapeID, size_t& iEdgeEnd, int* iBeg=0, int* iEnd=0 ) const;
605
606     void AddShapesToSmooth( const set< TGeomID >& shapeIDs );
607
608     void PrepareEdgesToSmoothOnFace( _LayerEdge**       edgeBeg,
609                                      _LayerEdge**       edgeEnd,
610                                      const TopoDS_Face& face,
611                                      bool               substituteSrcNodes );
612   };
613   //--------------------------------------------------------------------------------
614   /*!
615    * \brief Container of centers of curvature at nodes on an EDGE bounding _ConvexFace
616    */
617   struct _CentralCurveOnEdge
618   {
619     bool                  _isDegenerated;
620     vector< gp_Pnt >      _curvaCenters;
621     vector< _LayerEdge* > _ledges;
622     vector< gp_XYZ >      _normals; // new normal for each of _ledges
623     vector< double >      _segLength2;
624
625     TopoDS_Edge           _edge;
626     TopoDS_Face           _adjFace;
627     bool                  _adjFaceToSmooth;
628
629     void Append( const gp_Pnt& center, _LayerEdge* ledge )
630     {
631       if ( _curvaCenters.size() > 0 )
632         _segLength2.push_back( center.SquareDistance( _curvaCenters.back() ));
633       _curvaCenters.push_back( center );
634       _ledges.push_back( ledge );
635       _normals.push_back( ledge->_normal );
636     }
637     bool FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal );
638     void SetShapes( const TopoDS_Edge&  edge,
639                     const _ConvexFace&  convFace,
640                     const _SolidData&   data,
641                     SMESH_MesherHelper& helper);
642   };
643   //--------------------------------------------------------------------------------
644   /*!
645    * \brief Data of node on a shrinked FACE
646    */
647   struct _SmoothNode
648   {
649     const SMDS_MeshNode*         _node;
650     vector<_Simplex>             _simplices; // for quality check
651
652     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
653
654     bool Smooth(int&                  badNb,
655                 Handle(Geom_Surface)& surface,
656                 SMESH_MesherHelper&   helper,
657                 const double          refSign,
658                 SmoothType            how,
659                 bool                  set3D);
660
661     gp_XY computeAngularPos(vector<gp_XY>& uv,
662                             const gp_XY&   uvToFix,
663                             const double   refSign );
664   };
665   //--------------------------------------------------------------------------------
666   /*!
667    * \brief Builder of viscous layers
668    */
669   class _ViscousBuilder
670   {
671   public:
672     _ViscousBuilder();
673     // does it's job
674     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
675                                   const TopoDS_Shape& shape);
676     // check validity of hypotheses
677     SMESH_ComputeErrorPtr CheckHypotheses( SMESH_Mesh&         mesh,
678                                            const TopoDS_Shape& shape );
679
680     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
681     void RestoreListeners();
682
683     // computes SMESH_ProxyMesh::SubMesh::_n2n;
684     bool MakeN2NMap( _MeshOfSolid* pm );
685
686   private:
687
688     bool findSolidsWithLayers();
689     bool findFacesWithLayers(const bool onlyWith=false);
690     void getIgnoreFaces(const TopoDS_Shape&             solid,
691                         const StdMeshers_ViscousLayers* hyp,
692                         const TopoDS_Shape&             hypShape,
693                         set<TGeomID>&                   ignoreFaces);
694     bool makeLayer(_SolidData& data);
695     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
696                      SMESH_MesherHelper& helper, _SolidData& data);
697     gp_XYZ getFaceNormal(const SMDS_MeshNode* n,
698                          const TopoDS_Face&   face,
699                          SMESH_MesherHelper&  helper,
700                          bool&                isOK,
701                          bool                 shiftInside=false);
702     gp_XYZ getWeigthedNormal( const SMDS_MeshNode*         n,
703                               std::pair< TGeomID, gp_XYZ > fId2Normal[],
704                               int                          nbFaces );
705     bool findNeiborsOnEdge(const _LayerEdge*     edge,
706                            const SMDS_MeshNode*& n1,
707                            const SMDS_MeshNode*& n2,
708                            _SolidData&           data);
709     void findSimplexTestEdges( _SolidData&                    data,
710                                vector< vector<_LayerEdge*> >& edgesByGeom);
711     void computeGeomSize( _SolidData& data );
712     bool sortEdges( _SolidData&                    data,
713                     vector< vector<_LayerEdge*> >& edgesByGeom);
714     void limitStepSizeByCurvature( _SolidData&  data );
715     void limitStepSize( _SolidData&             data,
716                         const SMDS_MeshElement* face,
717                         const _LayerEdge*       maxCosinEdge );
718     void limitStepSize( _SolidData& data, const double minSize);
719     bool inflate(_SolidData& data);
720     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
721     bool smoothAnalyticEdge( _SolidData&           data,
722                              const int             iFrom,
723                              const int             iTo,
724                              Handle(Geom_Surface)& surface,
725                              const TopoDS_Face&    F,
726                              SMESH_MesherHelper&   helper);
727     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper, int stepNb );
728     bool updateNormalsOfConvexFaces( _SolidData&         data,
729                                      SMESH_MesherHelper& helper,
730                                      int                 stepNb );
731     bool refine(_SolidData& data);
732     bool shrink();
733     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
734                               SMESH_MesherHelper& helper,
735                               const SMESHDS_SubMesh* faceSubMesh );
736     void restoreNoShrink( _LayerEdge& edge ) const;
737     void fixBadFaces(const TopoDS_Face&          F,
738                      SMESH_MesherHelper&         helper,
739                      const bool                  is2D,
740                      const int                   step,
741                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
742     bool addBoundaryElements();
743
744     bool error( const string& text, int solidID=-1 );
745     SMESHDS_Mesh* getMeshDS() const { return _mesh->GetMeshDS(); }
746
747     // debug
748     void makeGroupOfLE();
749
750     SMESH_Mesh*           _mesh;
751     SMESH_ComputeErrorPtr _error;
752
753     vector< _SolidData >  _sdVec;
754     int                   _tmpFaceID;
755   };
756   //--------------------------------------------------------------------------------
757   /*!
758    * \brief Shrinker of nodes on the EDGE
759    */
760   class _Shrinker1D
761   {
762     vector<double>                _initU;
763     vector<double>                _normPar;
764     vector<const SMDS_MeshNode*>  _nodes;
765     const _LayerEdge*             _edges[2];
766     bool                          _done;
767   public:
768     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
769     void Compute(bool set3D, SMESH_MesherHelper& helper);
770     void RestoreParams();
771     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
772   };
773   //--------------------------------------------------------------------------------
774   /*!
775    * \brief Class of temporary mesh face.
776    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
777    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
778    */
779   struct _TmpMeshFace : public SMDS_MeshElement
780   {
781     vector<const SMDS_MeshNode* > _nn;
782     _TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id, int faceID=-1):
783       SMDS_MeshElement(id), _nn(nodes) { setShapeId(faceID); }
784     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
785     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
786     virtual vtkIdType GetVtkType() const                      { return -1; }
787     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
788     virtual SMDSAbs_GeometryType GetGeomType() const
789     { return _nn.size() == 3 ? SMDSGeom_TRIANGLE : SMDSGeom_QUADRANGLE; }
790     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
791     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
792   };
793   //--------------------------------------------------------------------------------
794   /*!
795    * \brief Class of temporary mesh face storing _LayerEdge it's based on
796    */
797   struct _TmpMeshFaceOnEdge : public _TmpMeshFace
798   {
799     _LayerEdge *_le1, *_le2;
800     _TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
801       _TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
802     {
803       _nn[0]=_le1->_nodes[0];
804       _nn[1]=_le1->_nodes.back();
805       _nn[2]=_le2->_nodes.back();
806       _nn[3]=_le2->_nodes[0];
807     }
808   };
809   //--------------------------------------------------------------------------------
810   /*!
811    * \brief Retriever of node coordinates either directly of from a surface by node UV.
812    * \warning Location of a surface is ignored
813    */
814   struct _NodeCoordHelper
815   {
816     SMESH_MesherHelper&        _helper;
817     const TopoDS_Face&         _face;
818     Handle(Geom_Surface)       _surface;
819     gp_XYZ (_NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
820
821     _NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
822       : _helper( helper ), _face( F )
823     {
824       if ( is2D )
825       {
826         TopLoc_Location loc;
827         _surface = BRep_Tool::Surface( _face, loc );
828       }
829       if ( _surface.IsNull() )
830         _fun = & _NodeCoordHelper::direct;
831       else
832         _fun = & _NodeCoordHelper::byUV;
833     }
834     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
835
836   private:
837     gp_XYZ direct(const SMDS_MeshNode* n) const
838     {
839       return SMESH_TNodeXYZ( n );
840     }
841     gp_XYZ byUV  (const SMDS_MeshNode* n) const
842     {
843       gp_XY uv = _helper.GetNodeUV( _face, n );
844       return _surface->Value( uv.X(), uv.Y() ).XYZ();
845     }
846   };
847
848 } // namespace VISCOUS_3D
849
850
851
852 //================================================================================
853 // StdMeshers_ViscousLayers hypothesis
854 //
855 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
856   :SMESH_Hypothesis(hypId, studyId, gen),
857    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
858 {
859   _name = StdMeshers_ViscousLayers::GetHypType();
860   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
861 } // --------------------------------------------------------------------------------
862 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
863 {
864   if ( faceIds != _shapeIds )
865     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
866   if ( _isToIgnoreShapes != toIgnore )
867     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
868 } // --------------------------------------------------------------------------------
869 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
870 {
871   if ( thickness != _thickness )
872     _thickness = thickness, NotifySubMeshesHypothesisModification();
873 } // --------------------------------------------------------------------------------
874 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
875 {
876   if ( _nbLayers != nb )
877     _nbLayers = nb, NotifySubMeshesHypothesisModification();
878 } // --------------------------------------------------------------------------------
879 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
880 {
881   if ( _stretchFactor != factor )
882     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
883 } // --------------------------------------------------------------------------------
884 SMESH_ProxyMesh::Ptr
885 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
886                                   const TopoDS_Shape& theShape,
887                                   const bool          toMakeN2NMap) const
888 {
889   using namespace VISCOUS_3D;
890   _ViscousBuilder bulder;
891   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
892   if ( err && !err->IsOK() )
893     return SMESH_ProxyMesh::Ptr();
894
895   vector<SMESH_ProxyMesh::Ptr> components;
896   TopExp_Explorer exp( theShape, TopAbs_SOLID );
897   for ( ; exp.More(); exp.Next() )
898   {
899     if ( _MeshOfSolid* pm =
900          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
901     {
902       if ( toMakeN2NMap && !pm->_n2nMapComputed )
903         if ( !bulder.MakeN2NMap( pm ))
904           return SMESH_ProxyMesh::Ptr();
905       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
906       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
907
908       if ( pm->_warning && !pm->_warning->IsOK() )
909       {
910         SMESH_subMesh* sm = theMesh.GetSubMesh( exp.Current() );
911         SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
912         if ( !smError || smError->IsOK() )
913           smError = pm->_warning;
914       }
915     }
916     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
917   }
918   switch ( components.size() )
919   {
920   case 0: break;
921
922   case 1: return components[0];
923
924   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
925   }
926   return SMESH_ProxyMesh::Ptr();
927 } // --------------------------------------------------------------------------------
928 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
929 {
930   save << " " << _nbLayers
931        << " " << _thickness
932        << " " << _stretchFactor
933        << " " << _shapeIds.size();
934   for ( size_t i = 0; i < _shapeIds.size(); ++i )
935     save << " " << _shapeIds[i];
936   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
937   return save;
938 } // --------------------------------------------------------------------------------
939 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
940 {
941   int nbFaces, faceID, shapeToTreat;
942   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
943   while ( _shapeIds.size() < nbFaces && load >> faceID )
944     _shapeIds.push_back( faceID );
945   if ( load >> shapeToTreat )
946     _isToIgnoreShapes = !shapeToTreat;
947   else
948     _isToIgnoreShapes = true; // old behavior
949   return load;
950 } // --------------------------------------------------------------------------------
951 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
952                                                    const TopoDS_Shape& theShape)
953 {
954   // TODO
955   return false;
956 } // --------------------------------------------------------------------------------
957 SMESH_ComputeErrorPtr
958 StdMeshers_ViscousLayers::CheckHypothesis(SMESH_Mesh&                          theMesh,
959                                           const TopoDS_Shape&                  theShape,
960                                           SMESH_Hypothesis::Hypothesis_Status& theStatus)
961 {
962   VISCOUS_3D::_ViscousBuilder bulder;
963   SMESH_ComputeErrorPtr err = bulder.CheckHypotheses( theMesh, theShape );
964   if ( err && !err->IsOK() )
965     theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
966   else
967     theStatus = SMESH_Hypothesis::HYP_OK;
968
969   return err;
970 }
971 // --------------------------------------------------------------------------------
972 bool StdMeshers_ViscousLayers::IsShapeWithLayers(int shapeIndex) const
973 {
974   bool isIn =
975     ( std::find( _shapeIds.begin(), _shapeIds.end(), shapeIndex ) != _shapeIds.end() );
976   return IsToIgnoreShapes() ? !isIn : isIn;
977 }
978 // END StdMeshers_ViscousLayers hypothesis
979 //================================================================================
980
981 namespace VISCOUS_3D
982 {
983   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
984   {
985     gp_Vec dir;
986     double f,l;
987     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
988     gp_Pnt p = BRep_Tool::Pnt( fromV );
989     double distF = p.SquareDistance( c->Value( f ));
990     double distL = p.SquareDistance( c->Value( l ));
991     c->D1(( distF < distL ? f : l), p, dir );
992     if ( distL < distF ) dir.Reverse();
993     return dir.XYZ();
994   }
995   //--------------------------------------------------------------------------------
996   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
997                      SMESH_MesherHelper& helper)
998   {
999     gp_Vec dir;
1000     double f,l; gp_Pnt p;
1001     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
1002     if ( c.IsNull() ) return gp_XYZ( 1e100, 1e100, 1e100 );
1003     double u = helper.GetNodeU( E, atNode );
1004     c->D1( u, p, dir );
1005     return dir.XYZ();
1006   }
1007   //--------------------------------------------------------------------------------
1008   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1009                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok,
1010                      double* cosin=0);
1011   //--------------------------------------------------------------------------------
1012   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
1013                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
1014   {
1015     double f,l;
1016     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
1017     if ( c.IsNull() )
1018     {
1019       TopoDS_Vertex v = helper.IthVertex( 0, fromE );
1020       return getFaceDir( F, v, node, helper, ok );
1021     }
1022     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
1023     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1024     gp_Pnt p; gp_Vec du, dv, norm;
1025     surface->D1( uv.X(),uv.Y(), p, du,dv );
1026     norm = du ^ dv;
1027
1028     double u = helper.GetNodeU( fromE, node, 0, &ok );
1029     c->D1( u, p, du );
1030     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
1031     if ( o == TopAbs_REVERSED )
1032       du.Reverse();
1033
1034     gp_Vec dir = norm ^ du;
1035
1036     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
1037          helper.IsClosedEdge( fromE ))
1038     {
1039       if ( fabs(u-f) < fabs(u-l)) c->D1( l, p, dv );
1040       else                        c->D1( f, p, dv );
1041       if ( o == TopAbs_REVERSED )
1042         dv.Reverse();
1043       gp_Vec dir2 = norm ^ dv;
1044       dir = dir.Normalized() + dir2.Normalized();
1045     }
1046     return dir.XYZ();
1047   }
1048   //--------------------------------------------------------------------------------
1049   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
1050                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
1051                      bool& ok, double* cosin)
1052   {
1053     TopoDS_Face faceFrw = F;
1054     faceFrw.Orientation( TopAbs_FORWARD );
1055     double f,l; TopLoc_Location loc;
1056     TopoDS_Edge edges[2]; // sharing a vertex
1057     int nbEdges = 0;
1058     {
1059       TopoDS_Vertex VV[2];
1060       TopExp_Explorer exp( faceFrw, TopAbs_EDGE );
1061       for ( ; exp.More() && nbEdges < 2; exp.Next() )
1062       {
1063         const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1064         if ( SMESH_Algo::isDegenerated( e )) continue;
1065         TopExp::Vertices( e, VV[0], VV[1], /*CumOri=*/true );
1066         if ( VV[1].IsSame( fromV )) {
1067           nbEdges += edges[ 0 ].IsNull();
1068           edges[ 0 ] = e;
1069         }
1070         else if ( VV[0].IsSame( fromV )) {
1071           nbEdges += edges[ 1 ].IsNull();
1072           edges[ 1 ] = e;
1073         }
1074       }
1075     }
1076     gp_XYZ dir(0,0,0), edgeDir[2];
1077     if ( nbEdges == 2 )
1078     {
1079       // get dirs of edges going fromV
1080       ok = true;
1081       for ( size_t i = 0; i < nbEdges && ok; ++i )
1082       {
1083         edgeDir[i] = getEdgeDir( edges[i], fromV );
1084         double size2 = edgeDir[i].SquareModulus();
1085         if (( ok = size2 > numeric_limits<double>::min() ))
1086           edgeDir[i] /= sqrt( size2 );
1087       }
1088       if ( !ok ) return dir;
1089
1090       // get angle between the 2 edges
1091       gp_Vec faceNormal;
1092       double angle = helper.GetAngle( edges[0], edges[1], faceFrw, fromV, &faceNormal );
1093       if ( Abs( angle ) < 5 * M_PI/180 )
1094       {
1095         dir = ( faceNormal.XYZ() ^ edgeDir[0].Reversed()) + ( faceNormal.XYZ() ^ edgeDir[1] );
1096       }
1097       else
1098       {
1099         dir = edgeDir[0] + edgeDir[1];
1100         if ( angle < 0 )
1101           dir.Reverse();
1102       }
1103       if ( cosin ) {
1104         double angle = gp_Vec( edgeDir[0] ).Angle( dir );
1105         *cosin = Cos( angle );
1106       }
1107     }
1108     else if ( nbEdges == 1 )
1109     {
1110       dir = getFaceDir( faceFrw, edges[ edges[0].IsNull() ], node, helper, ok );
1111       if ( cosin ) *cosin = 1.;
1112     }
1113     else
1114     {
1115       ok = false;
1116     }
1117
1118     return dir;
1119   }
1120
1121   //================================================================================
1122   /*!
1123    * \brief Finds concave VERTEXes of a FACE
1124    */
1125   //================================================================================
1126
1127   bool getConcaveVertices( const TopoDS_Face&  F,
1128                            SMESH_MesherHelper& helper,
1129                            set< TGeomID >*     vertices = 0)
1130   {
1131     // check angles at VERTEXes
1132     TError error;
1133     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
1134     for ( size_t iW = 0; iW < wires.size(); ++iW )
1135     {
1136       const int nbEdges = wires[iW]->NbEdges();
1137       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
1138         continue;
1139       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1140       {
1141         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
1142         int iE2 = ( iE1 + 1 ) % nbEdges;
1143         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
1144           iE2 = ( iE2 + 1 ) % nbEdges;
1145         TopoDS_Vertex V = wires[iW]->FirstVertex( iE2 );
1146         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
1147                                         wires[iW]->Edge( iE2 ), F, V );
1148         if ( angle < -5. * M_PI / 180. )
1149         {
1150           if ( !vertices )
1151             return true;
1152           vertices->insert( helper.GetMeshDS()->ShapeToIndex( V ));
1153         }
1154       }
1155     }
1156     return vertices ? !vertices->empty() : false;
1157   }
1158
1159   //================================================================================
1160   /*!
1161    * \brief Returns true if a FACE is bound by a concave EDGE
1162    */
1163   //================================================================================
1164
1165   bool isConcave( const TopoDS_Face&  F,
1166                   SMESH_MesherHelper& helper,
1167                   set< TGeomID >*     vertices = 0 )
1168   {
1169     bool isConcv = false;
1170     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
1171     //   return true;
1172     gp_Vec2d drv1, drv2;
1173     gp_Pnt2d p;
1174     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
1175     for ( ; eExp.More(); eExp.Next() )
1176     {
1177       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1178       if ( SMESH_Algo::isDegenerated( E )) continue;
1179       // check if 2D curve is concave
1180       BRepAdaptor_Curve2d curve( E, F );
1181       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
1182       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
1183       curve.Intervals( intervals, GeomAbs_C2 );
1184       bool isConvex = true;
1185       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
1186       {
1187         double u1 = intervals( i );
1188         double u2 = intervals( i+1 );
1189         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
1190         double cross = drv2 ^ drv1;
1191         if ( E.Orientation() == TopAbs_REVERSED )
1192           cross = -cross;
1193         isConvex = ( cross > 0.1 ); //-1e-9 );
1194       }
1195       if ( !isConvex )
1196       {
1197         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
1198         isConcv = true;
1199         if ( vertices )
1200           break;
1201         else
1202           return true;
1203       }
1204     }
1205
1206     // check angles at VERTEXes
1207     if ( getConcaveVertices( F, helper, vertices ))
1208       isConcv = true;
1209
1210     return isConcv;
1211   }
1212
1213   //================================================================================
1214   /*!
1215    * \brief Computes mimimal distance of face in-FACE nodes from an EDGE
1216    *  \param [in] face - the mesh face to treat
1217    *  \param [in] nodeOnEdge - a node on the EDGE
1218    *  \param [out] faceSize - the computed distance
1219    *  \return bool - true if faceSize computed
1220    */
1221   //================================================================================
1222
1223   bool getDistFromEdge( const SMDS_MeshElement* face,
1224                         const SMDS_MeshNode*    nodeOnEdge,
1225                         double &                faceSize )
1226   {
1227     faceSize = Precision::Infinite();
1228     bool done = false;
1229
1230     int nbN  = face->NbCornerNodes();
1231     int iOnE = face->GetNodeIndex( nodeOnEdge );
1232     int iNext[2] = { SMESH_MesherHelper::WrapIndex( iOnE+1, nbN ),
1233                      SMESH_MesherHelper::WrapIndex( iOnE-1, nbN ) };
1234     const SMDS_MeshNode* nNext[2] = { face->GetNode( iNext[0] ),
1235                                       face->GetNode( iNext[1] ) };
1236     gp_XYZ segVec, segEnd = SMESH_TNodeXYZ( nodeOnEdge ); // segment on EDGE
1237     double segLen = -1.;
1238     // look for two neighbor not in-FACE nodes of face
1239     for ( int i = 0; i < 2; ++i )
1240     {
1241       if ( nNext[i]->GetPosition()->GetDim() != 2 &&
1242            nNext[i]->GetID() < nodeOnEdge->GetID() )
1243       {
1244         // look for an in-FACE node
1245         for ( int iN = 0; iN < nbN; ++iN )
1246         {
1247           if ( iN == iOnE || iN == iNext[i] )
1248             continue;
1249           SMESH_TNodeXYZ pInFace = face->GetNode( iN );
1250           gp_XYZ v = pInFace - segEnd;
1251           if ( segLen < 0 )
1252           {
1253             segVec = SMESH_TNodeXYZ( nNext[i] ) - segEnd;
1254             segLen = segVec.Modulus();
1255           }
1256           double distToSeg = v.Crossed( segVec ).Modulus() / segLen;
1257           faceSize = Min( faceSize, distToSeg );
1258           done = true;
1259         }
1260         segLen = -1;
1261       }
1262     }
1263     return done;
1264   }
1265
1266   //--------------------------------------------------------------------------------
1267   // DEBUG. Dump intermediate node positions into a python script
1268   // HOWTO use: run python commands written in a console to see
1269   //  construction steps of viscous layers
1270 #ifdef __myDEBUG
1271   ofstream* py;
1272   int       theNbPyFunc;
1273   struct PyDump {
1274     PyDump(SMESH_Mesh& m) {
1275       int tag = 3 + m.GetId();
1276       const char* fname = "/tmp/viscous.py";
1277       cout << "execfile('"<<fname<<"')"<<endl;
1278       py = new ofstream(fname);
1279       *py << "import SMESH" << endl
1280           << "from salome.smesh import smeshBuilder" << endl
1281           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
1282           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:" << tag <<"')" << endl
1283           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
1284       theNbPyFunc = 0;
1285     }
1286     void Finish() {
1287       if (py) {
1288         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Viscous Prisms',"
1289           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA))"<<endl;
1290         *py << "mesh.GroupOnFilter(SMESH.VOLUME,'Neg Volumes',"
1291           "smesh.GetFilter(SMESH.VOLUME,SMESH.FT_Volume3D,'<',0))"<<endl;
1292       }
1293       delete py; py=0;
1294     }
1295     ~PyDump() { Finish(); cout << "NB FUNCTIONS: " << theNbPyFunc << endl; }
1296   };
1297 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
1298 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
1299 #define dumpMoveComm(n,txt) { _dumpMove(n, __LINE__, txt);}
1300 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
1301   void _dumpFunction(const string& fun, int ln)
1302   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl; ++theNbPyFunc; }
1303   void _dumpMove(const SMDS_MeshNode* n, int ln, const char* txt="")
1304   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
1305                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<" "<< txt << endl; }
1306   void _dumpCmd(const string& txt, int ln)
1307   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
1308   void dumpFunctionEnd()
1309   { if (py) *py<< "  return"<< endl; }
1310   void dumpChangeNodes( const SMDS_MeshElement* f )
1311   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
1312       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
1313       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
1314 #define debugMsg( txt ) { cout << txt << " (line: " << __LINE__ << ")" << endl; }
1315 #else
1316   struct PyDump { PyDump(SMESH_Mesh&) {} void Finish() {} };
1317 #define dumpFunction(f) f
1318 #define dumpMove(n)
1319 #define dumpMoveComm(n,txt)
1320 #define dumpCmd(txt)
1321 #define dumpFunctionEnd()
1322 #define dumpChangeNodes(f)
1323 #define debugMsg( txt ) {}
1324 #endif
1325 }
1326
1327 using namespace VISCOUS_3D;
1328
1329 //================================================================================
1330 /*!
1331  * \brief Constructor of _ViscousBuilder
1332  */
1333 //================================================================================
1334
1335 _ViscousBuilder::_ViscousBuilder()
1336 {
1337   _error = SMESH_ComputeError::New(COMPERR_OK);
1338   _tmpFaceID = 0;
1339 }
1340
1341 //================================================================================
1342 /*!
1343  * \brief Stores error description and returns false
1344  */
1345 //================================================================================
1346
1347 bool _ViscousBuilder::error(const string& text, int solidId )
1348 {
1349   const string prefix = string("Viscous layers builder: ");
1350   _error->myName    = COMPERR_ALGO_FAILED;
1351   _error->myComment = prefix + text;
1352   if ( _mesh )
1353   {
1354     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
1355     if ( !sm && !_sdVec.empty() )
1356       sm = _mesh->GetSubMeshContaining( solidId = _sdVec[0]._index );
1357     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1358     {
1359       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1360       if ( smError && smError->myAlgo )
1361         _error->myAlgo = smError->myAlgo;
1362       smError = _error;
1363       sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1364     }
1365     // set KO to all solids
1366     for ( size_t i = 0; i < _sdVec.size(); ++i )
1367     {
1368       if ( _sdVec[i]._index == solidId )
1369         continue;
1370       sm = _mesh->GetSubMesh( _sdVec[i]._solid );
1371       if ( !sm->IsEmpty() )
1372         continue;
1373       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1374       if ( !smError || smError->IsOK() )
1375       {
1376         smError = SMESH_ComputeError::New( COMPERR_ALGO_FAILED, prefix + "failed");
1377         sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1378       }
1379     }
1380   }
1381   makeGroupOfLE(); // debug
1382
1383   return false;
1384 }
1385
1386 //================================================================================
1387 /*!
1388  * \brief At study restoration, restore event listeners used to clear an inferior
1389  *  dim sub-mesh modified by viscous layers
1390  */
1391 //================================================================================
1392
1393 void _ViscousBuilder::RestoreListeners()
1394 {
1395   // TODO
1396 }
1397
1398 //================================================================================
1399 /*!
1400  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1401  */
1402 //================================================================================
1403
1404 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1405 {
1406   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1407   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1408   for ( ; fExp.More(); fExp.Next() )
1409   {
1410     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1411     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1412
1413     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1414       continue;
1415     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1416       continue;
1417
1418     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1419       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1420
1421     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1422     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1423     while( prxIt->more() )
1424     {
1425       const SMDS_MeshElement* fSrc = srcIt->next();
1426       const SMDS_MeshElement* fPrx = prxIt->next();
1427       if ( fSrc->NbNodes() != fPrx->NbNodes())
1428         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1429       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1430         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1431     }
1432   }
1433   pm->_n2nMapComputed = true;
1434   return true;
1435 }
1436
1437 //================================================================================
1438 /*!
1439  * \brief Does its job
1440  */
1441 //================================================================================
1442
1443 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1444                                                const TopoDS_Shape& theShape)
1445 {
1446   // TODO: set priority of solids during Gen::Compute()
1447
1448   _mesh = & theMesh;
1449
1450   // check if proxy mesh already computed
1451   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1452   if ( !exp.More() )
1453     return error("No SOLID's in theShape"), _error;
1454
1455   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1456     return SMESH_ComputeErrorPtr(); // everything already computed
1457
1458   PyDump debugDump( theMesh );
1459
1460   // TODO: ignore already computed SOLIDs 
1461   if ( !findSolidsWithLayers())
1462     return _error;
1463
1464   if ( !findFacesWithLayers() )
1465     return _error;
1466
1467   for ( size_t i = 0; i < _sdVec.size(); ++i )
1468   {
1469     if ( ! makeLayer(_sdVec[i]) )
1470       return _error;
1471
1472     if ( _sdVec[i]._edges.size() == 0 )
1473       continue;
1474     
1475     if ( ! inflate(_sdVec[i]) )
1476       return _error;
1477
1478     if ( ! refine(_sdVec[i]) )
1479       return _error;
1480   }
1481   if ( !shrink() )
1482     return _error;
1483
1484   addBoundaryElements();
1485
1486   makeGroupOfLE(); // debug
1487   debugDump.Finish();
1488
1489   return _error;
1490 }
1491
1492 //================================================================================
1493 /*!
1494  * \brief Check validity of hypotheses
1495  */
1496 //================================================================================
1497
1498 SMESH_ComputeErrorPtr _ViscousBuilder::CheckHypotheses( SMESH_Mesh&         mesh,
1499                                                         const TopoDS_Shape& shape )
1500 {
1501   _mesh = & mesh;
1502
1503   if ( _ViscousListener::GetSolidMesh( _mesh, shape, /*toCreate=*/false))
1504     return SMESH_ComputeErrorPtr(); // everything already computed
1505
1506
1507   findSolidsWithLayers();
1508   bool ok = findFacesWithLayers();
1509
1510   // remove _MeshOfSolid's of _SolidData's
1511   for ( size_t i = 0; i < _sdVec.size(); ++i )
1512     _ViscousListener::RemoveSolidMesh( _mesh, _sdVec[i]._solid );
1513
1514   if ( !ok )
1515     return _error;
1516
1517   return SMESH_ComputeErrorPtr();
1518 }
1519
1520 //================================================================================
1521 /*!
1522  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1523  */
1524 //================================================================================
1525
1526 bool _ViscousBuilder::findSolidsWithLayers()
1527 {
1528   // get all solids
1529   TopTools_IndexedMapOfShape allSolids;
1530   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1531   _sdVec.reserve( allSolids.Extent());
1532
1533   SMESH_Gen* gen = _mesh->GetGen();
1534   SMESH_HypoFilter filter;
1535   for ( int i = 1; i <= allSolids.Extent(); ++i )
1536   {
1537     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1538     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1539     if ( !algo ) continue;
1540     // TODO: check if algo is hidden
1541     const list <const SMESHDS_Hypothesis *> & allHyps =
1542       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1543     _SolidData* soData = 0;
1544     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1545     const StdMeshers_ViscousLayers* viscHyp = 0;
1546     for ( ; hyp != allHyps.end(); ++hyp )
1547       if ( viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp ))
1548       {
1549         TopoDS_Shape hypShape;
1550         filter.Init( filter.Is( viscHyp ));
1551         _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1552
1553         if ( !soData )
1554         {
1555           _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1556                                                                     allSolids(i),
1557                                                                     /*toCreate=*/true);
1558           _sdVec.push_back( _SolidData( allSolids(i), proxyMesh ));
1559           soData = & _sdVec.back();
1560           soData->_index = getMeshDS()->ShapeToIndex( allSolids(i));
1561         }
1562         soData->_hyps.push_back( viscHyp );
1563         soData->_hypShapes.push_back( hypShape );
1564       }
1565   }
1566   if ( _sdVec.empty() )
1567     return error
1568       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1569
1570   return true;
1571 }
1572
1573 //================================================================================
1574 /*!
1575  * \brief 
1576  */
1577 //================================================================================
1578
1579 bool _ViscousBuilder::findFacesWithLayers(const bool onlyWith)
1580 {
1581   SMESH_MesherHelper helper( *_mesh );
1582   TopExp_Explorer exp;
1583   TopTools_IndexedMapOfShape solids;
1584
1585   // collect all faces to ignore defined by hyp
1586   for ( size_t i = 0; i < _sdVec.size(); ++i )
1587   {
1588     solids.Add( _sdVec[i]._solid );
1589
1590     // get faces to ignore defined by each hyp
1591     typedef const StdMeshers_ViscousLayers* THyp;
1592     typedef std::pair< set<TGeomID>, THyp > TFacesOfHyp;
1593     list< TFacesOfHyp > ignoreFacesOfHyps;
1594     list< THyp >::iterator              hyp = _sdVec[i]._hyps.begin();
1595     list< TopoDS_Shape >::iterator hypShape = _sdVec[i]._hypShapes.begin();
1596     for ( ; hyp != _sdVec[i]._hyps.end(); ++hyp, ++hypShape )
1597     {
1598       ignoreFacesOfHyps.push_back( TFacesOfHyp( set<TGeomID>(), *hyp ));
1599       getIgnoreFaces( _sdVec[i]._solid, *hyp, *hypShape, ignoreFacesOfHyps.back().first );
1600     }
1601
1602     // fill _SolidData::_face2hyp and check compatibility of hypotheses
1603     const int nbHyps = _sdVec[i]._hyps.size();
1604     if ( nbHyps > 1 )
1605     {
1606       // check if two hypotheses define different parameters for the same FACE
1607       list< TFacesOfHyp >::iterator igFacesOfHyp;
1608       for ( exp.Init( _sdVec[i]._solid, TopAbs_FACE ); exp.More(); exp.Next() )
1609       {
1610         const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
1611         THyp hyp = 0;
1612         igFacesOfHyp = ignoreFacesOfHyps.begin();
1613         for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1614           if ( ! igFacesOfHyp->first.count( faceID ))
1615           {
1616             if ( hyp )
1617               return error(SMESH_Comment("Several hypotheses define "
1618                                          "Viscous Layers on the face #") << faceID );
1619             hyp = igFacesOfHyp->second;
1620           }
1621         if ( hyp )
1622           _sdVec[i]._face2hyp.insert( make_pair( faceID, hyp ));
1623         else
1624           _sdVec[i]._ignoreFaceIds.insert( faceID );
1625       }
1626
1627       // check if two hypotheses define different number of viscous layers for
1628       // adjacent faces of a solid
1629       set< int > nbLayersSet;
1630       igFacesOfHyp = ignoreFacesOfHyps.begin();
1631       for ( ; igFacesOfHyp != ignoreFacesOfHyps.end(); ++igFacesOfHyp )
1632       {
1633         nbLayersSet.insert( igFacesOfHyp->second->GetNumberLayers() );
1634       }
1635       if ( nbLayersSet.size() > 1 )
1636       {
1637         for ( exp.Init( _sdVec[i]._solid, TopAbs_EDGE ); exp.More(); exp.Next() )
1638         {
1639           PShapeIteratorPtr fIt = helper.GetAncestors( exp.Current(), *_mesh, TopAbs_FACE );
1640           THyp hyp1 = 0, hyp2 = 0;
1641           while( const TopoDS_Shape* face = fIt->next() )
1642           {
1643             const TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
1644             map< TGeomID, THyp >::iterator f2h = _sdVec[i]._face2hyp.find( faceID );
1645             if ( f2h != _sdVec[i]._face2hyp.end() )
1646             {
1647               ( hyp1 ? hyp2 : hyp1 ) = f2h->second;
1648             }
1649           }
1650           if ( hyp1 && hyp2 &&
1651                hyp1->GetNumberLayers() != hyp2->GetNumberLayers() )
1652           {
1653             return error("Two hypotheses define different number of "
1654                          "viscous layers on adjacent faces");
1655           }
1656         }
1657       }
1658     } // if ( nbHyps > 1 )
1659     else
1660     {
1661       _sdVec[i]._ignoreFaceIds.swap( ignoreFacesOfHyps.back().first );
1662     }
1663   } // loop on _sdVec
1664
1665   if ( onlyWith ) // is called to check hypotheses compatibility only
1666     return true;
1667
1668   // fill _SolidData::_reversedFaceIds
1669   for ( size_t i = 0; i < _sdVec.size(); ++i )
1670   {
1671     exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1672     for ( ; exp.More(); exp.Next() )
1673     {
1674       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1675       const TGeomID faceID = getMeshDS()->ShapeToIndex( face );
1676       if ( //!sdVec[i]._ignoreFaceIds.count( faceID ) &&
1677           helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) > 1 &&
1678           helper.IsReversedSubMesh( face ))
1679       {
1680         _sdVec[i]._reversedFaceIds.insert( faceID );
1681       }
1682     }
1683   }
1684
1685   // Find faces to shrink mesh on (solution 2 in issue 0020832);
1686   TopTools_IndexedMapOfShape shapes;
1687   for ( size_t i = 0; i < _sdVec.size(); ++i )
1688   {
1689     shapes.Clear();
1690     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1691     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1692     {
1693       const TopoDS_Shape& edge = shapes(iE);
1694       // find 2 faces sharing an edge
1695       TopoDS_Shape FF[2];
1696       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1697       while ( fIt->more())
1698       {
1699         const TopoDS_Shape* f = fIt->next();
1700         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1701           FF[ int( !FF[0].IsNull()) ] = *f;
1702       }
1703       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1704       // check presence of layers on them
1705       int ignore[2];
1706       for ( int j = 0; j < 2; ++j )
1707         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1708       if ( ignore[0] == ignore[1] )
1709         continue; // nothing interesting
1710       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1711       // check presence of layers on fWOL within an adjacent SOLID
1712       bool collision = false;
1713       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1714       while ( const TopoDS_Shape* solid = sIt->next() )
1715         if ( !solid->IsSame( _sdVec[i]._solid ))
1716         {
1717           int iSolid = solids.FindIndex( *solid );
1718           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
1719           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1720           {
1721             //_sdVec[i]._noShrinkShapes.insert( iFace );
1722             //fWOL.Nullify();
1723             collision = true;
1724           }
1725         }
1726       // add edge to maps
1727       if ( !fWOL.IsNull())
1728       {
1729         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1730         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1731         if ( collision )
1732         {
1733           // _shrinkShape2Shape will be used to temporary inflate _LayerEdge's based
1734           // on the edge but shrink won't be performed
1735           _sdVec[i]._noShrinkShapes.insert( edgeInd );
1736         }
1737       }
1738     }
1739   }
1740   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1741   // the algo of the SOLID sharing the FACE does not support it
1742   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1743   for ( size_t i = 0; i < _sdVec.size(); ++i )
1744   {
1745     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1746     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1747     {
1748       const TopoDS_Shape& fWOL = e2f->second;
1749       const TGeomID     edgeID = e2f->first;
1750       bool notShrinkFace = false;
1751       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1752       while ( soIt->more() )
1753       {
1754         const TopoDS_Shape* solid = soIt->next();
1755         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1756         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1757         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1758         notShrinkFace = true;
1759         size_t iSolid = 0;
1760         for ( ; iSolid < _sdVec.size(); ++iSolid )
1761         {
1762           if ( _sdVec[iSolid]._solid.IsSame( *solid ) ) {
1763             if ( _sdVec[iSolid]._shrinkShape2Shape.count( edgeID ))
1764               notShrinkFace = false;
1765             break;
1766           }
1767         }
1768         if ( notShrinkFace )
1769         {
1770           _sdVec[i]._noShrinkShapes.insert( edgeID );
1771
1772           // add VERTEXes of the edge in _noShrinkShapes
1773           TopoDS_Shape edge = getMeshDS()->IndexToShape( edgeID );
1774           for ( TopoDS_Iterator vIt( edge ); vIt.More(); vIt.Next() )
1775             _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( vIt.Value() ));
1776
1777           // check if there is a collision with to-shrink-from EDGEs in iSolid
1778           if ( iSolid == _sdVec.size() )
1779             continue; // no VL in the solid
1780           shapes.Clear();
1781           TopExp::MapShapes( fWOL, TopAbs_EDGE, shapes);
1782           for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1783           {
1784             const TopoDS_Edge& E = TopoDS::Edge( shapes( iE ));
1785             const TGeomID    eID = getMeshDS()->ShapeToIndex( E );
1786             if ( eID == edgeID ||
1787                  !_sdVec[iSolid]._shrinkShape2Shape.count( eID ) ||
1788                  _sdVec[i]._noShrinkShapes.count( eID ))
1789               continue;
1790             for ( int is1st = 0; is1st < 2; ++is1st )
1791             {
1792               TopoDS_Vertex V = helper.IthVertex( is1st, E );
1793               if ( _sdVec[i]._noShrinkShapes.count( getMeshDS()->ShapeToIndex( V ) ))
1794               {
1795                 // _sdVec[i]._noShrinkShapes.insert( eID );
1796                 // V = helper.IthVertex( !is1st, E );
1797                 // _sdVec[i]._noShrinkShapes.insert( getMeshDS()->ShapeToIndex( V ));
1798                 //iE = 0; // re-start the loop on EDGEs of fWOL
1799                 return error("No way to make a conformal mesh with "
1800                              "the given set of faces with layers", _sdVec[i]._index);
1801               }
1802             }
1803           }
1804         }
1805
1806       } // while ( soIt->more() )
1807     } // loop on _sdVec[i]._shrinkShape2Shape
1808   } // loop on _sdVec to fill in _SolidData::_noShrinkShapes
1809
1810   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1811
1812   for ( size_t i = 0; i < _sdVec.size(); ++i )
1813   {
1814     shapes.Clear();
1815     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1816     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1817     {
1818       const TopoDS_Shape& vertex = shapes(iV);
1819       // find faces WOL sharing the vertex
1820       vector< TopoDS_Shape > facesWOL;
1821       int totalNbFaces = 0;
1822       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1823       while ( fIt->more())
1824       {
1825         const TopoDS_Shape* f = fIt->next();
1826         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1827         {
1828           totalNbFaces++;
1829           const int fID = getMeshDS()->ShapeToIndex( *f );
1830           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) /*&&
1831                !_sdVec[i]._noShrinkShapes.count( fID )*/)
1832             facesWOL.push_back( *f );
1833         }
1834       }
1835       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1836         continue; // no layers at this vertex or no WOL
1837       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1838       switch ( facesWOL.size() )
1839       {
1840       case 1:
1841       {
1842         helper.SetSubShape( facesWOL[0] );
1843         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1844         {
1845           TopoDS_Shape seamEdge;
1846           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1847           while ( eIt->more() && seamEdge.IsNull() )
1848           {
1849             const TopoDS_Shape* e = eIt->next();
1850             if ( helper.IsRealSeam( *e ) )
1851               seamEdge = *e;
1852           }
1853           if ( !seamEdge.IsNull() )
1854           {
1855             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1856             break;
1857           }
1858         }
1859         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1860         break;
1861       }
1862       case 2:
1863       {
1864         // find an edge shared by 2 faces
1865         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1866         while ( eIt->more())
1867         {
1868           const TopoDS_Shape* e = eIt->next();
1869           if ( helper.IsSubShape( *e, facesWOL[0]) &&
1870                helper.IsSubShape( *e, facesWOL[1]))
1871           {
1872             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1873           }
1874         }
1875         break;
1876       }
1877       default:
1878         return error("Not yet supported case", _sdVec[i]._index);
1879       }
1880     }
1881   }
1882
1883   // add FACEs of other SOLIDs to _ignoreFaceIds
1884   for ( size_t i = 0; i < _sdVec.size(); ++i )
1885   {
1886     shapes.Clear();
1887     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1888
1889     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1890     {
1891       if ( !shapes.Contains( exp.Current() ))
1892         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1893     }
1894   }
1895
1896   return true;
1897 }
1898
1899 //================================================================================
1900 /*!
1901  * \brief Finds FACEs w/o layers for a given SOLID by an hypothesis
1902  */
1903 //================================================================================
1904
1905 void _ViscousBuilder::getIgnoreFaces(const TopoDS_Shape&             solid,
1906                                      const StdMeshers_ViscousLayers* hyp,
1907                                      const TopoDS_Shape&             hypShape,
1908                                      set<TGeomID>&                   ignoreFaceIds)
1909 {
1910   TopExp_Explorer exp;
1911
1912   vector<TGeomID> ids = hyp->GetBndShapes();
1913   if ( hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1914   {
1915     for ( size_t ii = 0; ii < ids.size(); ++ii )
1916     {
1917       const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1918       if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1919         ignoreFaceIds.insert( ids[ii] );
1920     }
1921   }
1922   else // FACEs with layers are given
1923   {
1924     exp.Init( solid, TopAbs_FACE );
1925     for ( ; exp.More(); exp.Next() )
1926     {
1927       TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1928       if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1929         ignoreFaceIds.insert( faceInd );
1930     }
1931   }
1932
1933   // ignore internal FACEs if inlets and outlets are specified
1934   if ( hyp->IsToIgnoreShapes() )
1935   {
1936     TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1937     TopExp::MapShapesAndAncestors( hypShape,
1938                                    TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1939
1940     for ( exp.Init( solid, TopAbs_FACE ); exp.More(); exp.Next() )
1941     {
1942       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1943       if ( SMESH_MesherHelper::NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1944         continue;
1945
1946       int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1947       if ( nbSolids > 1 )
1948         ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( face ));
1949     }
1950   }
1951 }
1952
1953 //================================================================================
1954 /*!
1955  * \brief Create the inner surface of the viscous layer and prepare data for infation
1956  */
1957 //================================================================================
1958
1959 bool _ViscousBuilder::makeLayer(_SolidData& data)
1960 {
1961   // get all sub-shapes to make layers on
1962   set<TGeomID> subIds, faceIds;
1963   subIds = data._noShrinkShapes;
1964   TopExp_Explorer exp( data._solid, TopAbs_FACE );
1965   for ( ; exp.More(); exp.Next() )
1966     {
1967       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1968       if ( ! data._ignoreFaceIds.count( fSubM->GetId() ))
1969         faceIds.insert( fSubM->GetId() );
1970       SMESH_subMeshIteratorPtr subIt = fSubM->getDependsOnIterator(/*includeSelf=*/true);
1971       while ( subIt->more() )
1972         subIds.insert( subIt->next()->GetId() );
1973     }
1974
1975   // make a map to find new nodes on sub-shapes shared with other SOLID
1976   map< TGeomID, TNode2Edge* >::iterator s2ne;
1977   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1978   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1979   {
1980     TGeomID shapeInd = s2s->first;
1981     for ( size_t i = 0; i < _sdVec.size(); ++i )
1982     {
1983       if ( _sdVec[i]._index == data._index ) continue;
1984       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1985       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1986            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1987       {
1988         data._s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1989         break;
1990       }
1991     }
1992   }
1993
1994   // Create temporary faces and _LayerEdge's
1995
1996   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
1997
1998   data._stepSize = Precision::Infinite();
1999   data._stepSizeNodes[0] = 0;
2000
2001   SMESH_MesherHelper helper( *_mesh );
2002   helper.SetSubShape( data._solid );
2003   helper.SetElementsOnShape( true );
2004
2005   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
2006   TNode2Edge::iterator n2e2;
2007
2008   // collect _LayerEdge's of shapes they are based on
2009   const int nbShapes = getMeshDS()->MaxShapeIndex();
2010   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
2011
2012   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
2013   {
2014     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
2015     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
2016
2017     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
2018     SMESH_ProxyMesh::SubMesh* proxySub =
2019       data._proxyMesh->getFaceSubM( F, /*create=*/true);
2020
2021     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2022     while ( eIt->more() )
2023     {
2024       const SMDS_MeshElement* face = eIt->next();
2025       double          faceMaxCosin = -1;
2026       _LayerEdge*     maxCosinEdge = 0;
2027       int             nbDegenNodes = 0;
2028
2029       newNodes.resize( face->NbCornerNodes() );
2030       for ( size_t i = 0 ; i < newNodes.size(); ++i )
2031       {
2032         const SMDS_MeshNode* n = face->GetNode( i );
2033         const int      shapeID = n->getshapeId();
2034         const bool onDegenShap = helper.IsDegenShape( shapeID );
2035         const bool onDegenEdge = ( onDegenShap && n->GetPosition()->GetDim() == 1 );
2036         if ( onDegenShap )
2037         {
2038           if ( onDegenEdge )
2039           {
2040             // substitute n on a degenerated EDGE with a node on a corresponding VERTEX
2041             const TopoDS_Shape& E = getMeshDS()->IndexToShape( shapeID );
2042             TopoDS_Vertex       V = helper.IthVertex( 0, TopoDS::Edge( E ));
2043             if ( const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() )) {
2044               n = vN;
2045               nbDegenNodes++;
2046             }
2047           }
2048           else
2049           {
2050             nbDegenNodes++;
2051           }
2052         }
2053         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
2054         if ( !(*n2e).second )
2055         {
2056           // add a _LayerEdge
2057           _LayerEdge* edge = new _LayerEdge();
2058           edge->_nodes.push_back( n );
2059           n2e->second = edge;
2060           edgesByGeom[ shapeID ].push_back( edge );
2061           const bool noShrink = data._noShrinkShapes.count( shapeID );
2062
2063           SMESH_TNodeXYZ xyz( n );
2064
2065           // set edge data or find already refined _LayerEdge and get data from it
2066           if (( !noShrink                                                     ) &&
2067               ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE        ) &&
2068               (( s2ne = data._s2neMap.find( shapeID )) != data._s2neMap.end() ) &&
2069               (( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end()     ))
2070           {
2071             _LayerEdge* foundEdge = (*n2e2).second;
2072             gp_XYZ        lastPos = edge->Copy( *foundEdge, helper );
2073             foundEdge->_pos.push_back( lastPos );
2074             // location of the last node is modified and we restore it by foundEdge->_pos.back()
2075             const_cast< SMDS_MeshNode* >
2076               ( edge->_nodes.back() )->setXYZ( xyz.X(), xyz.Y(), xyz.Z() );
2077           }
2078           else
2079           {
2080             if ( !noShrink )
2081             {
2082               edge->_nodes.push_back( helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() ));
2083             }
2084             if ( !setEdgeData( *edge, subIds, helper, data ))
2085               return false;
2086           }
2087           dumpMove(edge->_nodes.back());
2088
2089           if ( edge->_cosin > faceMaxCosin )
2090           {
2091             faceMaxCosin = edge->_cosin;
2092             maxCosinEdge = edge;
2093           }
2094         }
2095         newNodes[ i ] = n2e->second->_nodes.back();
2096
2097         if ( onDegenEdge )
2098           data._n2eMap.insert( make_pair( face->GetNode( i ), n2e->second ));
2099       }
2100       if ( newNodes.size() - nbDegenNodes < 2 )
2101         continue;
2102
2103       // create a temporary face
2104       const SMDS_MeshElement* newFace =
2105         new _TmpMeshFace( newNodes, --_tmpFaceID, face->getshapeId() );
2106       proxySub->AddElement( newFace );
2107
2108       // compute inflation step size by min size of element on a convex surface
2109       if ( faceMaxCosin > theMinSmoothCosin )
2110         limitStepSize( data, face, maxCosinEdge );
2111
2112     } // loop on 2D elements on a FACE
2113   } // loop on FACEs of a SOLID
2114
2115   data._epsilon = 1e-7;
2116   if ( data._stepSize < 1. )
2117     data._epsilon *= data._stepSize;
2118
2119   // Put _LayerEdge's into the vector data._edges
2120   if ( !sortEdges( data, edgesByGeom ))
2121     return false;
2122
2123   // limit data._stepSize depending on surface curvature and fill data._convexFaces
2124   limitStepSizeByCurvature( data ); // !!! it must be before node substitution in _Simplex
2125
2126   // Set target nodes into _Simplex and _LayerEdge's to _2NearEdges
2127   TNode2Edge::iterator n2e;
2128   const SMDS_MeshNode* nn[2];
2129   for ( size_t i = 0; i < data._edges.size(); ++i )
2130   {
2131     _LayerEdge* edge = data._edges[i];
2132     if ( edge->IsOnEdge() )
2133     {
2134       // get neighbor nodes
2135       bool hasData = ( edge->_2neibors->_edges[0] );
2136       if ( hasData ) // _LayerEdge is a copy of another one
2137       {
2138         nn[0] = edge->_2neibors->srcNode(0);
2139         nn[1] = edge->_2neibors->srcNode(1);
2140       }
2141       else if ( !findNeiborsOnEdge( edge, nn[0],nn[1], data ))
2142       {
2143         return false;
2144       }
2145       // set neighbor _LayerEdge's
2146       for ( int j = 0; j < 2; ++j )
2147       {
2148         if (( n2e = data._n2eMap.find( nn[j] )) == data._n2eMap.end() )
2149           return error("_LayerEdge not found by src node", data._index);
2150         edge->_2neibors->_edges[j] = n2e->second;
2151       }
2152       if ( !hasData )
2153         edge->SetDataByNeighbors( nn[0], nn[1], helper);
2154     }
2155
2156     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2157     {
2158       _Simplex& s = edge->_simplices[j];
2159       s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
2160       s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
2161     }
2162
2163     // For an _LayerEdge on a degenerated EDGE, copy some data from
2164     // a corresponding _LayerEdge on a VERTEX
2165     // (issue 52453, pb on a downloaded SampleCase2-Tet-netgen-mephisto.hdf)
2166     if ( helper.IsDegenShape( edge->_nodes[0]->getshapeId() ))
2167     {
2168       // Generally we should not get here
2169       const TopoDS_Shape& E = getMeshDS()->IndexToShape( edge->_nodes[0]->getshapeId() );
2170       if ( E.ShapeType() != TopAbs_EDGE )
2171         continue;
2172       TopoDS_Vertex V = helper.IthVertex( 0, TopoDS::Edge( E ));
2173       const SMDS_MeshNode* vN = SMESH_Algo::VertexNode( V, getMeshDS() );
2174       if (( n2e = data._n2eMap.find( vN )) == data._n2eMap.end() )
2175         continue;
2176       const _LayerEdge* vEdge = n2e->second;
2177       edge->_normal    = vEdge->_normal;
2178       edge->_lenFactor = vEdge->_lenFactor;
2179       edge->_cosin     = vEdge->_cosin;
2180     }
2181   }
2182
2183   // fix _LayerEdge::_2neibors on EDGEs to smooth
2184   map< TGeomID,Handle(Geom_Curve)>::iterator e2c = data._edge2curve.begin();
2185   for ( ; e2c != data._edge2curve.end(); ++e2c )
2186     if ( !e2c->second.IsNull() )
2187     {
2188       size_t iEdgeEnd; int iBeg, iEnd;
2189       if ( data.GetShapeEdges( e2c->first, iEdgeEnd, &iBeg, &iEnd ))
2190         data.Sort2NeiborsOnEdge( iBeg, iEnd );
2191     }
2192
2193   dumpFunctionEnd();
2194   return true;
2195 }
2196
2197 //================================================================================
2198 /*!
2199  * \brief Compute inflation step size by min size of element on a convex surface
2200  */
2201 //================================================================================
2202
2203 void _ViscousBuilder::limitStepSize( _SolidData&             data,
2204                                      const SMDS_MeshElement* face,
2205                                      const _LayerEdge*       maxCosinEdge )
2206 {
2207   int iN = 0;
2208   double minSize = 10 * data._stepSize;
2209   const int nbNodes = face->NbCornerNodes();
2210   for ( int i = 0; i < nbNodes; ++i )
2211   {
2212     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
2213     const SMDS_MeshNode*  curN = face->GetNode( i );
2214     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
2215          curN-> GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
2216     {
2217       double dist = SMESH_TNodeXYZ( curN ).Distance( nextN );
2218       if ( dist < minSize )
2219         minSize = dist, iN = i;
2220     }
2221   }
2222   double newStep = 0.8 * minSize / maxCosinEdge->_lenFactor;
2223   if ( newStep < data._stepSize )
2224   {
2225     data._stepSize = newStep;
2226     data._stepSizeCoeff = 0.8 / maxCosinEdge->_lenFactor;
2227     data._stepSizeNodes[0] = face->GetNode( iN );
2228     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
2229   }
2230 }
2231
2232 //================================================================================
2233 /*!
2234  * \brief Compute inflation step size by min size of element on a convex surface
2235  */
2236 //================================================================================
2237
2238 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
2239 {
2240   if ( minSize < data._stepSize )
2241   {
2242     data._stepSize = minSize;
2243     if ( data._stepSizeNodes[0] )
2244     {
2245       double dist =
2246         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2247       data._stepSizeCoeff = data._stepSize / dist;
2248     }
2249   }
2250 }
2251
2252 //================================================================================
2253 /*!
2254  * \brief Limit data._stepSize by evaluating curvature of shapes and fill data._convexFaces
2255  */
2256 //================================================================================
2257
2258 void _ViscousBuilder::limitStepSizeByCurvature( _SolidData& data )
2259 {
2260   const int nbTestPnt = 5; // on a FACE sub-shape
2261
2262   BRepLProp_SLProps surfProp( 2, 1e-6 );
2263   SMESH_MesherHelper helper( *_mesh );
2264
2265   data._convexFaces.clear();
2266
2267   TopExp_Explorer face( data._solid, TopAbs_FACE );
2268   for ( ; face.More(); face.Next() )
2269   {
2270     const TopoDS_Face& F = TopoDS::Face( face.Current() );
2271     SMESH_subMesh *   sm = _mesh->GetSubMesh( F );
2272     const TGeomID faceID = sm->GetId();
2273     if ( data._ignoreFaceIds.count( faceID )) continue;
2274
2275     BRepAdaptor_Surface surface( F, false );
2276     surfProp.SetSurface( surface );
2277
2278     bool isTooCurved = false;
2279     int iBeg, iEnd;
2280
2281     _ConvexFace cnvFace;
2282     const double        oriFactor = ( F.Orientation() == TopAbs_REVERSED ? +1. : -1. );
2283     SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
2284     while ( smIt->more() )
2285     {
2286       sm = smIt->next();
2287       const TGeomID subID = sm->GetId();
2288       // find _LayerEdge's of a sub-shape
2289       size_t edgesEnd;
2290       if ( data.GetShapeEdges( subID, edgesEnd, &iBeg, &iEnd ))
2291         cnvFace._subIdToEdgeEnd.insert( make_pair( subID, edgesEnd ));
2292       else
2293         continue;
2294       // check concavity and curvature and limit data._stepSize
2295       const double minCurvature =
2296         1. / ( data._hypOnShape[ edgesEnd ].GetTotalThickness() * ( 1+theThickToIntersection ));
2297       int nbLEdges = iEnd - iBeg;
2298       int iStep    = Max( 1, nbLEdges / nbTestPnt );
2299       for ( ; iBeg < iEnd; iBeg += iStep )
2300       {
2301         gp_XY uv = helper.GetNodeUV( F, data._edges[ iBeg ]->_nodes[0] );
2302         surfProp.SetParameters( uv.X(), uv.Y() );
2303         if ( !surfProp.IsCurvatureDefined() )
2304           continue;
2305         if ( surfProp.MaxCurvature() * oriFactor > minCurvature )
2306         {
2307           limitStepSize( data, 0.9 / surfProp.MaxCurvature() * oriFactor );
2308           isTooCurved = true;
2309         }
2310         if ( surfProp.MinCurvature() * oriFactor > minCurvature )
2311         {
2312           limitStepSize( data, 0.9 / surfProp.MinCurvature() * oriFactor );
2313           isTooCurved = true;
2314         }
2315       }
2316     } // loop on sub-shapes of the FACE
2317
2318     if ( !isTooCurved ) continue;
2319
2320     _ConvexFace & convFace =
2321       data._convexFaces.insert( make_pair( faceID, cnvFace )).first->second;
2322
2323     convFace._face = F;
2324     convFace._normalsFixed = false;
2325
2326     // Fill _ConvexFace::_simplexTestEdges. These _LayerEdge's are used to detect
2327     // prism distortion.
2328     map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
2329     if ( id2end != convFace._subIdToEdgeEnd.end() )
2330     {
2331       // there are _LayerEdge's on the FACE it-self;
2332       // select _LayerEdge's near EDGEs
2333       data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2334       for ( ; iBeg < iEnd; ++iBeg )
2335       {
2336         _LayerEdge* ledge = data._edges[ iBeg ];
2337         for ( size_t j = 0; j < ledge->_simplices.size(); ++j )
2338           if ( ledge->_simplices[j]._nNext->GetPosition()->GetDim() < 2 )
2339           {
2340             convFace._simplexTestEdges.push_back( ledge );
2341             break;
2342           }
2343       }
2344     }
2345     else
2346     {
2347       // where there are no _LayerEdge's on a _ConvexFace,
2348       // as e.g. on a fillet surface with no internal nodes - issue 22580,
2349       // so that collision of viscous internal faces is not detected by check of
2350       // intersection of _LayerEdge's with the viscous internal faces.
2351
2352       set< const SMDS_MeshNode* > usedNodes;
2353
2354       // look for _LayerEdge's with null _sWOL
2355       map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
2356       for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
2357       {
2358         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
2359         if ( iBeg >= iEnd || !data._edges[ iBeg ]->_sWOL.IsNull() )
2360           continue;
2361         for ( ; iBeg < iEnd; ++iBeg )
2362         {
2363           _LayerEdge* ledge = data._edges[ iBeg ];
2364           const SMDS_MeshNode* srcNode = ledge->_nodes[0];
2365           if ( !usedNodes.insert( srcNode ).second ) continue;
2366
2367           _Simplex::GetSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
2368           for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
2369           {
2370             usedNodes.insert( ledge->_simplices[i]._nPrev );
2371             usedNodes.insert( ledge->_simplices[i]._nNext );
2372           }
2373           convFace._simplexTestEdges.push_back( ledge );
2374         }
2375       }
2376     }
2377   } // loop on FACEs of data._solid
2378 }
2379
2380 //================================================================================
2381 /*!
2382  * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
2383  */
2384 //================================================================================
2385
2386 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
2387                                  vector< vector<_LayerEdge*> >& edgesByGeom)
2388 {
2389   // define allowed thickness
2390   computeGeomSize( data ); // compute data._geomSize
2391
2392   data._maxThickness = 0;
2393   data._minThickness = 1e100;
2394   list< const StdMeshers_ViscousLayers* >::iterator hyp = data._hyps.begin();
2395   for ( ; hyp != data._hyps.end(); ++hyp )
2396   {
2397     data._maxThickness = Max( data._maxThickness, (*hyp)->GetTotalThickness() );
2398     data._minThickness = Min( data._minThickness, (*hyp)->GetTotalThickness() );
2399   }
2400   const double tgtThick = /*Min( 0.5 * data._geomSize, */data._maxThickness;
2401
2402   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
2403   // boundry inclined to the shape at a sharp angle
2404
2405   list< TGeomID > shapesToSmooth;
2406   TopTools_MapOfShape edgesOfSmooFaces;
2407
2408   SMESH_MesherHelper helper( *_mesh );
2409   bool ok = true;
2410
2411   for ( int isEdge = 0; isEdge < 2; ++isEdge ) // loop on [ FACEs, EDGEs ]
2412   {
2413     const int dim = isEdge ? 1 : 2;
2414
2415     for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2416     {
2417       vector<_LayerEdge*>& eS = edgesByGeom[iS];
2418       if ( eS.empty() ) continue;
2419       if ( eS[0]->_nodes[0]->GetPosition()->GetDim() != dim ) continue;
2420
2421       const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
2422       bool needSmooth = false;
2423       switch ( S.ShapeType() )
2424       {
2425       case TopAbs_EDGE: {
2426
2427         const TopoDS_Edge& E = TopoDS::Edge( S );
2428         if ( SMESH_Algo::isDegenerated( E ) || !edgesOfSmooFaces.Contains( E ))
2429           break;
2430
2431         TopoDS_Face F;
2432         if ( !eS[0]->_sWOL.IsNull() && eS[0]->_sWOL.ShapeType() == TopAbs_FACE )
2433           F = TopoDS::Face( eS[0]->_sWOL );
2434
2435         for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
2436         {
2437           TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
2438           vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
2439           if ( eV.empty() ) continue;
2440           gp_Vec  eDir = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
2441           double angle = eDir.Angle( eV[0]->_normal );
2442           double cosin = Cos( angle );
2443           double cosinAbs = Abs( cosin );
2444           if ( cosinAbs > theMinSmoothCosin )
2445           {
2446             // always smooth analytic EDGEs
2447             needSmooth = ! data.CurveForSmooth( E, 0, eS.size(), F, helper, &eS ).IsNull();
2448
2449             // compare tgtThick with the length of an end segment
2450             SMDS_ElemIteratorPtr eIt = eV[0]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Edge);
2451             while ( eIt->more() && !needSmooth )
2452             {
2453               const SMDS_MeshElement* endSeg = eIt->next();
2454               if ( endSeg->getshapeId() == iS )
2455               {
2456                 double segLen =
2457                   SMESH_TNodeXYZ( endSeg->GetNode(0) ).Distance( endSeg->GetNode(1 ));
2458                 needSmooth = needSmoothing( cosinAbs, tgtThick, segLen );
2459               }
2460             }
2461           }
2462         }
2463         break;
2464       }
2465       case TopAbs_FACE: {
2466
2467         for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
2468         {
2469           TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
2470           vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
2471           if ( eE.empty() ) continue;
2472           // TopLoc_Location loc;
2473           // Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face( S ), loc );
2474           // bool isPlane = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2475           //if ( eE[0]->_sWOL.IsNull() )
2476           {
2477             double faceSize;
2478             for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2479               if ( eE[i]->_cosin > theMinSmoothCosin )
2480               {
2481                 SMDS_ElemIteratorPtr fIt = eE[i]->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2482                 while ( fIt->more() && !needSmooth )
2483                 {
2484                   const SMDS_MeshElement* face = fIt->next();
2485                   if ( getDistFromEdge( face, eE[i]->_nodes[0], faceSize ))
2486                     needSmooth = needSmoothing( eE[i]->_cosin, tgtThick, faceSize );
2487                 }
2488               }
2489           }
2490           // else
2491           // {
2492           //   const TopoDS_Face& F1 = TopoDS::Face( S );
2493           //   const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
2494           //   const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
2495           //   for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
2496           //   {
2497           //     gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
2498           //     gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
2499           //     double angle = dir1.Angle(  );
2500           //     double cosin = cos( angle );
2501           //     needSmooth = ( cosin > theMinSmoothCosin );
2502           //   }
2503           // }
2504         }
2505         if ( needSmooth )
2506           for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More(); eExp.Next() )
2507             edgesOfSmooFaces.Add( eExp.Current() );
2508
2509         break;
2510       }
2511       case TopAbs_VERTEX:
2512         continue;
2513       default:;
2514       }
2515
2516       if ( needSmooth )
2517       {
2518         if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
2519         else                                shapesToSmooth.push_back ( iS );
2520
2521         // preparation for smoothing
2522         if ( S.ShapeType() == TopAbs_FACE )
2523         {
2524           data.PrepareEdgesToSmoothOnFace( & eS[0],
2525                                            & eS[0] + eS.size(),
2526                                            TopoDS::Face( S ),
2527                                            /*substituteSrcNodes=*/false);
2528         }
2529       }
2530
2531     } // loop on edgesByGeom
2532   } //  // loop on [ FACEs, EDGEs ]
2533
2534   data._edges.reserve( data._n2eMap.size() );
2535   data._endEdgeOnShape.clear();
2536
2537   // first we put _LayerEdge's on shapes to smooth
2538   data._nbShapesToSmooth = 0;
2539   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
2540   for ( ; gIt != shapesToSmooth.end(); ++gIt )
2541   {
2542     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
2543     if ( eVec.empty() ) continue;
2544     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2545     data._endEdgeOnShape.push_back( data._edges.size() );
2546     data._nbShapesToSmooth++;
2547     eVec.clear();
2548   }
2549
2550   // then the rest _LayerEdge's
2551   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
2552   {
2553     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
2554     if ( eVec.empty() ) continue;
2555     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
2556     data._endEdgeOnShape.push_back( data._edges.size() );
2557     //eVec.clear();
2558   }
2559
2560   // compute average StdMeshers_ViscousLayers parameters for each shape
2561
2562   data._hypOnShape.clear();
2563   if ( data._hyps.size() == 1 )
2564   {
2565     data._hypOnShape.resize( data._endEdgeOnShape.size(), AverageHyp( data._hyps.back() ));
2566   }
2567   else
2568   {
2569     data._hypOnShape.resize( data._endEdgeOnShape.size() );
2570     map< TGeomID, const StdMeshers_ViscousLayers* >::iterator f2hyp;
2571     for ( size_t i = 0; i < data._endEdgeOnShape.size(); ++i )
2572     {
2573       int       iEnd = data._endEdgeOnShape[i];
2574       _LayerEdge* LE = data._edges[ iEnd-1 ];
2575       TGeomID iShape = LE->_nodes[0]->getshapeId();
2576       const TopoDS_Shape& S = getMeshDS()->IndexToShape( iShape );
2577       if ( S.ShapeType() == TopAbs_FACE )
2578       {
2579         if (( f2hyp = data._face2hyp.find( iShape )) != data._face2hyp.end() )
2580         {
2581           data._hypOnShape[ i ].Add( f2hyp->second );
2582         }
2583       }
2584       else
2585       {
2586         PShapeIteratorPtr fIt = SMESH_MesherHelper::GetAncestors( S, *_mesh, TopAbs_FACE );
2587         while ( const TopoDS_Shape* face = fIt->next() )
2588         {
2589           TGeomID faceID = getMeshDS()->ShapeToIndex( *face );
2590           if (( f2hyp = data._face2hyp.find( faceID )) != data._face2hyp.end() )
2591           {
2592             data._hypOnShape[ i ].Add( f2hyp->second );
2593           }
2594         }
2595       }
2596     }
2597   }
2598
2599   return ok;
2600 }
2601
2602 //================================================================================
2603 /*!
2604  * \brief Set data of _LayerEdge needed for smoothing
2605  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
2606  */
2607 //================================================================================
2608
2609 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
2610                                   const set<TGeomID>& subIds,
2611                                   SMESH_MesherHelper& helper,
2612                                   _SolidData&         data)
2613 {
2614   SMESH_MeshEditor editor(_mesh);
2615
2616   const SMDS_MeshNode* node = edge._nodes[0]; // source node
2617   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
2618
2619   edge._len       = 0;
2620   edge._2neibors  = 0;
2621   edge._curvature = 0;
2622
2623   // --------------------------
2624   // Compute _normal and _cosin
2625   // --------------------------
2626
2627   edge._cosin = 0;
2628   edge._normal.SetCoord(0,0,0);
2629
2630   int totalNbFaces = 0;
2631   gp_Vec geomNorm;
2632   bool normOK = true;
2633
2634   const TGeomID shapeInd = node->getshapeId();
2635   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
2636   const bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
2637
2638   if ( onShrinkShape ) // one of faces the node is on has no layers
2639   {
2640     TopoDS_Shape vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
2641     if ( s2s->second.ShapeType() == TopAbs_EDGE )
2642     {
2643       // inflate from VERTEX along EDGE
2644       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
2645     }
2646     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
2647     {
2648       // inflate from VERTEX along FACE
2649       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
2650                                  node, helper, normOK, &edge._cosin);
2651     }
2652     else
2653     {
2654       // inflate from EDGE along FACE
2655       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
2656                                  node, helper, normOK);
2657     }
2658   }
2659   else // layers are on all faces of SOLID the node is on
2660   {
2661     // find indices of geom faces the node lies on
2662     set<TGeomID> faceIds;
2663     if  ( posType == SMDS_TOP_FACE )
2664     {
2665       faceIds.insert( node->getshapeId() );
2666     }
2667     else
2668     {
2669       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2670       while ( fIt->more() )
2671         faceIds.insert( editor.FindShape(fIt->next()));
2672     }
2673
2674     set<TGeomID>::iterator id = faceIds.begin();
2675     TopoDS_Face F;
2676     std::pair< TGeomID, gp_XYZ > id2Norm[20];
2677     for ( ; id != faceIds.end(); ++id )
2678     {
2679       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
2680       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
2681         continue;
2682       F = TopoDS::Face( s );
2683       geomNorm = getFaceNormal( node, F, helper, normOK );
2684       if ( !normOK ) continue;
2685
2686       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2687         geomNorm.Reverse();
2688       id2Norm[ totalNbFaces ].first  = *id;
2689       id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
2690       totalNbFaces++;
2691       edge._normal += geomNorm.XYZ();
2692     }
2693     if ( totalNbFaces == 0 )
2694       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
2695
2696     if ( normOK && edge._normal.Modulus() < 1e-3 && totalNbFaces > 1 )
2697     {
2698       // opposite normals, re-get normals at shifted positions (IPAL 52426)
2699       edge._normal.SetCoord( 0,0,0 );
2700       for ( int i = 0; i < totalNbFaces; ++i )
2701       {
2702         const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[i].first ));
2703         geomNorm = getFaceNormal( node, F, helper, normOK, /*shiftInside=*/true );
2704         if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
2705           geomNorm.Reverse();
2706         if ( normOK )
2707           id2Norm[ i ].second = geomNorm.XYZ();
2708         edge._normal += id2Norm[ i ].second;
2709       }
2710     }
2711
2712     if ( totalNbFaces < 3 )
2713     {
2714       //edge._normal /= totalNbFaces;
2715     }
2716     else
2717     {
2718       edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
2719     }
2720
2721     switch ( posType )
2722     {
2723     case SMDS_TOP_FACE:
2724       edge._cosin = 0; break;
2725
2726     case SMDS_TOP_EDGE: {
2727       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
2728       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK );
2729       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2730       edge._cosin = Cos( angle );
2731       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
2732       break;
2733     }
2734     case SMDS_TOP_VERTEX: {
2735       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2736       gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK );
2737       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
2738       edge._cosin = Cos( angle );
2739       if ( totalNbFaces > 2 || helper.IsSeamShape( node->getshapeId() ))
2740         for ( int iF = totalNbFaces-2; iF >=0; --iF )
2741         {
2742           F = TopoDS::Face( getMeshDS()->IndexToShape( id2Norm[ iF ].first ));
2743           inFaceDir = getFaceDir( F, V, node, helper, normOK );
2744           if ( normOK ) {
2745             double angle = inFaceDir.Angle( edge._normal );
2746             edge._cosin = Max( edge._cosin, Cos( angle ));
2747           }
2748         }
2749       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2750       break;
2751     }
2752     default:
2753       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2754     }
2755   } // case _sWOL.IsNull()
2756
2757   double normSize = edge._normal.SquareModulus();
2758   if ( normSize < numeric_limits<double>::min() )
2759     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2760
2761   edge._normal /= sqrt( normSize );
2762
2763   // TODO: if ( !normOK ) then get normal by mesh faces
2764
2765   // Set the rest data
2766   // --------------------
2767   if ( onShrinkShape )
2768   {
2769     edge._sWOL = (*s2s).second;
2770
2771     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2772     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2773       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2774
2775     // set initial position which is parameters on _sWOL in this case
2776     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2777     {
2778       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2779       edge._pos.push_back( gp_XYZ( u, 0, 0 ));
2780       if ( edge._nodes.size() > 1 )
2781         getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2782     }
2783     else // TopAbs_FACE
2784     {
2785       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2786       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2787       if ( edge._nodes.size() > 1 )
2788         getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2789     }
2790   }
2791   else
2792   {
2793     edge._pos.push_back( SMESH_TNodeXYZ( node ));
2794
2795     if ( posType == SMDS_TOP_FACE )
2796     {
2797       _Simplex::GetSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2798     }
2799   }
2800
2801   // Set neighbour nodes for a _LayerEdge based on EDGE
2802
2803   if ( posType == SMDS_TOP_EDGE /*||
2804        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2805   {
2806     edge._2neibors = new _2NearEdges;
2807     // target node instead of source ones will be set later
2808     // if ( ! findNeiborsOnEdge( &edge,
2809     //                           edge._2neibors->_nodes[0],
2810     //                           edge._2neibors->_nodes[1],
2811     //                           data))
2812     //   return false;
2813     // edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2814     //                          edge._2neibors->_nodes[1],
2815     //                          helper);
2816   }
2817
2818   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2819
2820   return true;
2821 }
2822
2823 //================================================================================
2824 /*!
2825  * \brief Return normal to a FACE at a node
2826  *  \param [in] n - node
2827  *  \param [in] face - FACE
2828  *  \param [in] helper - helper
2829  *  \param [out] isOK - true or false
2830  *  \param [in] shiftInside - to find normal at a position shifted inside the face
2831  *  \return gp_XYZ - normal
2832  */
2833 //================================================================================
2834
2835 gp_XYZ _ViscousBuilder::getFaceNormal(const SMDS_MeshNode* node,
2836                                       const TopoDS_Face&   face,
2837                                       SMESH_MesherHelper&  helper,
2838                                       bool&                isOK,
2839                                       bool                 shiftInside)
2840 {
2841   gp_XY uv;
2842   if ( shiftInside )
2843   {
2844     // get a shifted position
2845     gp_Pnt p = SMESH_TNodeXYZ( node );
2846     gp_XYZ shift( 0,0,0 );
2847     TopoDS_Shape S = helper.GetSubShapeByNode( node, helper.GetMeshDS() );
2848     switch ( S.ShapeType() ) {
2849     case TopAbs_VERTEX:
2850     {
2851       shift = getFaceDir( face, TopoDS::Vertex( S ), node, helper, isOK );
2852       break;
2853     }
2854     case TopAbs_EDGE:
2855     {
2856       shift = getFaceDir( face, TopoDS::Edge( S ), node, helper, isOK );
2857       break;
2858     }
2859     default:
2860       isOK = false;
2861     }
2862     if ( isOK )
2863       shift.Normalize();
2864     p.Translate( shift * 1e-5 );
2865
2866     TopLoc_Location loc;
2867     GeomAPI_ProjectPointOnSurf& projector = helper.GetProjector( face, loc, 1e-7 );
2868
2869     if ( !loc.IsIdentity() ) p.Transform( loc.Transformation().Inverted() );
2870     
2871     projector.Perform( p );
2872     if ( !projector.IsDone() || projector.NbPoints() < 1 )
2873     {
2874       isOK = false;
2875       return p.XYZ();
2876     }
2877     Quantity_Parameter U,V;
2878     projector.LowerDistanceParameters(U,V);
2879     uv.SetCoord( U,V );
2880   }
2881   else
2882   {
2883     uv = helper.GetNodeUV( face, node, 0, &isOK );
2884   }
2885
2886   gp_Dir normal;
2887   isOK = false;
2888
2889   Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
2890   int pointKind = GeomLib::NormEstim( surface, uv, 1e-5, normal );
2891   enum { REGULAR = 0, QUASYSINGULAR, CONICAL, IMPOSSIBLE };
2892
2893   if ( pointKind == IMPOSSIBLE &&
2894        node->GetPosition()->GetDim() == 2 ) // node inside the FACE
2895   {
2896     // probably NormEstim() failed due to a too high tolerance
2897     pointKind = GeomLib::NormEstim( surface, uv, 1e-20, normal );
2898     isOK = ( pointKind < IMPOSSIBLE );
2899   }
2900   if ( pointKind < IMPOSSIBLE )
2901   {
2902     if ( pointKind != REGULAR &&
2903          !shiftInside &&
2904          node->GetPosition()->GetDim() < 2 ) // FACE boundary
2905     {
2906       gp_XYZ normShift = getFaceNormal( node, face, helper, isOK, /*shiftInside=*/true );
2907       if ( normShift * normal.XYZ() < 0. )
2908         normal = normShift;
2909     }
2910     isOK = true;
2911   }
2912
2913   if ( !isOK ) // hard singularity, to call with shiftInside=true ?
2914   {
2915     const TGeomID faceID = helper.GetMeshDS()->ShapeToIndex( face );
2916
2917     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2918     while ( fIt->more() )
2919     {
2920       const SMDS_MeshElement* f = fIt->next();
2921       if ( f->getshapeId() == faceID )
2922       {
2923         isOK = SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) normal.XYZ(), /*normalized=*/true );
2924         if ( isOK )
2925         {
2926           TopoDS_Face ff = face;
2927           ff.Orientation( TopAbs_FORWARD );
2928           if ( helper.IsReversedSubMesh( ff ))
2929             normal.Reverse();
2930           break;
2931         }
2932       }
2933     }
2934   }
2935   return normal.XYZ();
2936 }
2937
2938 //================================================================================
2939 /*!
2940  * \brief Return a normal at a node weighted with angles taken by FACEs
2941  *  \param [in] n - the node
2942  *  \param [in] fId2Normal - FACE ids and normals
2943  *  \param [in] nbFaces - nb of FACEs meeting at the node
2944  *  \return gp_XYZ - computed normal
2945  */
2946 //================================================================================
2947
2948 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
2949                                            std::pair< TGeomID, gp_XYZ > fId2Normal[],
2950                                            int                          nbFaces )
2951 {
2952   gp_XYZ resNorm(0,0,0);
2953   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2954   if ( V.ShapeType() != TopAbs_VERTEX )
2955   {
2956     for ( int i = 0; i < nbFaces; ++i )
2957       resNorm += fId2Normal[i].second;
2958     return resNorm;
2959   }
2960
2961   // exclude equal normals
2962   int nbUniqNorms = nbFaces;
2963   for ( int i = 0; i < nbFaces; ++i )
2964     for ( int j = i+1; j < nbFaces; ++j )
2965       if ( fId2Normal[i].second.IsEqual( fId2Normal[j].second, 0.1 ))
2966       {
2967         fId2Normal[i].second.SetCoord( 0,0,0 );
2968         --nbUniqNorms;
2969         break;
2970       }
2971   //if ( nbUniqNorms < 3 )
2972   {
2973     for ( int i = 0; i < nbFaces; ++i )
2974       resNorm += fId2Normal[i].second;
2975     return resNorm;
2976   }
2977
2978   double angles[30];
2979   for ( int i = 0; i < nbFaces; ++i )
2980   {
2981     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2982
2983     // look for two EDGEs shared by F and other FACEs within fId2Normal
2984     TopoDS_Edge ee[2];
2985     int nbE = 0;
2986     PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2987     while ( const TopoDS_Shape* E = eIt->next() )
2988     {
2989       if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2990         continue;
2991       bool isSharedEdge = false;
2992       for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2993       {
2994         if ( i == j ) continue;
2995         const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2996         isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2997       }
2998       if ( !isSharedEdge )
2999         continue;
3000       ee[ nbE ] = TopoDS::Edge( *E );
3001       ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
3002       if ( ++nbE == 2 )
3003         break;
3004     }
3005
3006     // get an angle between the two EDGEs
3007     angles[i] = 0;
3008     if ( nbE < 1 ) continue;
3009     if ( nbE == 1 )
3010     {
3011       ee[ 1 ] == ee[ 0 ];
3012     }
3013     else
3014     {
3015       if ( !V.IsSame( SMESH_MesherHelper::IthVertex( 0, ee[ 1 ] )))
3016         std::swap( ee[0], ee[1] );
3017     }
3018     angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F, TopoDS::Vertex( V ));
3019   }
3020
3021   // compute a weighted normal
3022   double sumAngle = 0;
3023   for ( int i = 0; i < nbFaces; ++i )
3024   {
3025     angles[i] = ( angles[i] > 2*M_PI )  ?  0  :  M_PI - angles[i];
3026     sumAngle += angles[i];
3027   }
3028   for ( int i = 0; i < nbFaces; ++i )
3029     resNorm += angles[i] / sumAngle * fId2Normal[i].second;
3030
3031   return resNorm;
3032 }
3033
3034 //================================================================================
3035 /*!
3036  * \brief Find 2 neigbor nodes of a node on EDGE
3037  */
3038 //================================================================================
3039
3040 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
3041                                         const SMDS_MeshNode*& n1,
3042                                         const SMDS_MeshNode*& n2,
3043                                         _SolidData&           data)
3044 {
3045   const SMDS_MeshNode* node = edge->_nodes[0];
3046   const int        shapeInd = node->getshapeId();
3047   SMESHDS_SubMesh*   edgeSM = 0;
3048   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
3049   {
3050     edgeSM = getMeshDS()->MeshElements( shapeInd );
3051     if ( !edgeSM || edgeSM->NbElements() == 0 )
3052       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
3053   }
3054   int iN = 0;
3055   n2 = 0;
3056   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
3057   while ( eIt->more() && !n2 )
3058   {
3059     const SMDS_MeshElement* e = eIt->next();
3060     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
3061     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
3062     if ( edgeSM )
3063     {
3064       if (!edgeSM->Contains(e)) continue;
3065     }
3066     else
3067     {
3068       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
3069       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
3070     }
3071     ( iN++ ? n2 : n1 ) = nNeibor;
3072   }
3073   if ( !n2 )
3074     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
3075   return true;
3076 }
3077
3078 //================================================================================
3079 /*!
3080  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
3081  */
3082 //================================================================================
3083
3084 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
3085                                      const SMDS_MeshNode* n2,
3086                                      SMESH_MesherHelper&  helper)
3087 {
3088   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
3089     return;
3090
3091   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
3092   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
3093   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
3094
3095   // Set _curvature
3096
3097   double      sumLen = vec1.Modulus() + vec2.Modulus();
3098   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
3099   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
3100   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
3101   double      avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
3102   if ( _curvature ) delete _curvature;
3103   _curvature = _Curvature::New( avgNormProj, avgLen );
3104   // if ( _curvature )
3105   //   debugMsg( _nodes[0]->GetID()
3106   //             << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
3107   //             << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
3108   //             << _curvature->lenDelta(0) );
3109
3110   // Set _plnNorm
3111
3112   if ( _sWOL.IsNull() )
3113   {
3114     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
3115     TopoDS_Edge  E = TopoDS::Edge( S );
3116     // if ( SMESH_Algo::isDegenerated( E ))
3117     //   return;
3118     gp_XYZ dirE    = getEdgeDir( E, _nodes[0], helper );
3119     gp_XYZ plnNorm = dirE ^ _normal;
3120     double proj0   = plnNorm * vec1;
3121     double proj1   = plnNorm * vec2;
3122     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
3123     {
3124       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
3125       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
3126     }
3127   }
3128 }
3129
3130 //================================================================================
3131 /*!
3132  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
3133  * this and other _LayerEdge's are inflated along a FACE or an EDGE
3134  */
3135 //================================================================================
3136
3137 gp_XYZ _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
3138 {
3139   _nodes     = other._nodes;
3140   _normal    = other._normal;
3141   _len       = 0;
3142   _lenFactor = other._lenFactor;
3143   _cosin     = other._cosin;
3144   _sWOL      = other._sWOL;
3145   _2neibors  = other._2neibors;
3146   _curvature = 0; std::swap( _curvature, other._curvature );
3147   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
3148
3149   gp_XYZ lastPos( 0,0,0 );
3150   if ( _sWOL.ShapeType() == TopAbs_EDGE )
3151   {
3152     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
3153     _pos.push_back( gp_XYZ( u, 0, 0));
3154
3155     u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes.back() );
3156     lastPos.SetX( u );
3157   }
3158   else // TopAbs_FACE
3159   {
3160     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
3161     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
3162
3163     uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes.back() );
3164     lastPos.SetX( uv.X() );
3165     lastPos.SetY( uv.Y() );
3166   }
3167   return lastPos;
3168 }
3169
3170 //================================================================================
3171 /*!
3172  * \brief Set _cosin and _lenFactor
3173  */
3174 //================================================================================
3175
3176 void _LayerEdge::SetCosin( double cosin )
3177 {
3178   _cosin = cosin;
3179   cosin = Abs( _cosin );
3180   _lenFactor = ( /*0.1 < cosin &&*/ cosin < 1-1e-12 ) ?  1./sqrt(1-cosin*cosin) : 1.0;
3181 }
3182
3183 //================================================================================
3184 /*!
3185  * \brief Fills a vector<_Simplex > 
3186  */
3187 //================================================================================
3188
3189 void _Simplex::GetSimplices( const SMDS_MeshNode* node,
3190                              vector<_Simplex>&    simplices,
3191                              const set<TGeomID>&  ingnoreShapes,
3192                              const _SolidData*    dataToCheckOri,
3193                              const bool           toSort)
3194 {
3195   simplices.clear();
3196   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
3197   while ( fIt->more() )
3198   {
3199     const SMDS_MeshElement* f = fIt->next();
3200     const TGeomID    shapeInd = f->getshapeId();
3201     if ( ingnoreShapes.count( shapeInd )) continue;
3202     const int nbNodes = f->NbCornerNodes();
3203     const int  srcInd = f->GetNodeIndex( node );
3204     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
3205     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
3206     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
3207     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
3208       std::swap( nPrev, nNext );
3209     simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
3210   }
3211
3212   if ( toSort )
3213     SortSimplices( simplices );
3214 }
3215
3216 //================================================================================
3217 /*!
3218  * \brief Set neighbor simplices side by side
3219  */
3220 //================================================================================
3221
3222 void _Simplex::SortSimplices(vector<_Simplex>& simplices)
3223 {
3224   vector<_Simplex> sortedSimplices( simplices.size() );
3225   sortedSimplices[0] = simplices[0];
3226   int nbFound = 0;
3227   for ( size_t i = 1; i < simplices.size(); ++i )
3228   {
3229     for ( size_t j = 1; j < simplices.size(); ++j )
3230       if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
3231       {
3232         sortedSimplices[i] = simplices[j];
3233         nbFound++;
3234         break;
3235       }
3236   }
3237   if ( nbFound == simplices.size() - 1 )
3238     simplices.swap( sortedSimplices );
3239 }
3240
3241 //================================================================================
3242 /*!
3243  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
3244  */
3245 //================================================================================
3246
3247 void _ViscousBuilder::makeGroupOfLE()
3248 {
3249 #ifdef _DEBUG_
3250   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3251   {
3252     if ( _sdVec[i]._edges.empty() ) continue;
3253
3254     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
3255     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
3256     {
3257       _LayerEdge* le = _sdVec[i]._edges[j];
3258       for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
3259         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
3260                 << ", " << le->_nodes[iN]->GetID() <<"])");
3261     }
3262     dumpFunctionEnd();
3263
3264     dumpFunction( SMESH_Comment("makeNormals") << i );
3265     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
3266     {
3267       _LayerEdge& edge = *_sdVec[i]._edges[j];
3268       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
3269       nXYZ += edge._normal * _sdVec[i]._stepSize;
3270       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
3271               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
3272     }
3273     dumpFunctionEnd();
3274
3275     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
3276     dumpCmd( "faceId1 = mesh.NbElements()" );
3277     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
3278     for ( ; fExp.More(); fExp.Next() )
3279     {
3280       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
3281       {
3282         if ( sm->NbElements() == 0 ) continue;
3283         SMDS_ElemIteratorPtr fIt = sm->GetElements();
3284         while ( fIt->more())
3285         {
3286           const SMDS_MeshElement* e = fIt->next();
3287           SMESH_Comment cmd("mesh.AddFace([");
3288           for ( int j=0; j < e->NbCornerNodes(); ++j )
3289             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
3290           dumpCmd( cmd );
3291         }
3292       }
3293     }
3294     dumpCmd( "faceId2 = mesh.NbElements()" );
3295     dumpCmd( SMESH_Comment( "mesh.MakeGroup( 'tmpFaces_" ) << i << "',"
3296              << "SMESH.FACE, SMESH.FT_RangeOfIds,'=',"
3297              << "'%s-%s' % (faceId1+1, faceId2))");
3298     dumpFunctionEnd();
3299   }
3300 #endif
3301 }
3302
3303 //================================================================================
3304 /*!
3305  * \brief Find maximal _LayerEdge length (layer thickness) limited by geometry
3306  */
3307 //================================================================================
3308
3309 void _ViscousBuilder::computeGeomSize( _SolidData& data )
3310 {
3311   data._geomSize = Precision::Infinite();
3312   double intersecDist;
3313   auto_ptr<SMESH_ElementSearcher> searcher
3314     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3315                                            data._proxyMesh->GetFaces( data._solid )) );
3316
3317   TNode2Edge::iterator n2e = data._n2eMap.begin(), n2eEnd = data._n2eMap.end();
3318   for ( ; n2e != n2eEnd; ++n2e )
3319   {
3320     _LayerEdge* edge = n2e->second;
3321     if ( edge->IsOnEdge() ) continue;
3322     edge->FindIntersection( *searcher, intersecDist, data._epsilon );
3323     if ( data._geomSize > intersecDist && intersecDist > 0 )
3324       data._geomSize = intersecDist;
3325   }
3326 }
3327
3328 //================================================================================
3329 /*!
3330  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
3331  */
3332 //================================================================================
3333
3334 bool _ViscousBuilder::inflate(_SolidData& data)
3335 {
3336   SMESH_MesherHelper helper( *_mesh );
3337
3338   // Limit inflation step size by geometry size found by itersecting
3339   // normals of _LayerEdge's with mesh faces
3340   if ( data._stepSize > 0.3 * data._geomSize )
3341     limitStepSize( data, 0.3 * data._geomSize );
3342
3343   const double tgtThick = data._maxThickness;
3344   if ( data._stepSize > data._minThickness )
3345     limitStepSize( data, data._minThickness );
3346
3347   if ( data._stepSize < 1. )
3348     data._epsilon = data._stepSize * 1e-7;
3349
3350   debugMsg( "-- geomSize = " << data._geomSize << ", stepSize = " << data._stepSize );
3351
3352   const double safeFactor = ( 2*data._maxThickness < data._geomSize ) ? 1 : theThickToIntersection;
3353
3354   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
3355   int nbSteps = 0, nbRepeats = 0;
3356   int iBeg, iEnd, iS;
3357   while ( avgThick < 0.99 )
3358   {
3359     // new target length
3360     curThick += data._stepSize;
3361     if ( curThick > tgtThick )
3362     {
3363       curThick = tgtThick + tgtThick*( 1.-avgThick ) * nbRepeats;
3364       nbRepeats++;
3365     }
3366
3367     // Elongate _LayerEdge's
3368     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
3369     for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3370     {
3371       const double shapeCurThick = Min( curThick, data._hypOnShape[ iS ].GetTotalThickness() );
3372       for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
3373       {
3374         data._edges[iBeg]->SetNewLength( shapeCurThick, helper );
3375       }
3376     }
3377     dumpFunctionEnd();
3378
3379     if ( !updateNormals( data, helper, nbSteps ))
3380       return false;
3381
3382     // Improve and check quality
3383     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
3384     {
3385       if ( nbSteps > 0 )
3386       {
3387 #ifdef __NOT_INVALIDATE_BAD_SMOOTH
3388         debugMsg("NOT INVALIDATED STEP!");
3389         return error("Smoothing failed", data._index);
3390 #endif
3391         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
3392         for ( size_t i = 0; i < data._edges.size(); ++i )
3393         {
3394           data._edges[i]->InvalidateStep( nbSteps+1 );
3395         }
3396         dumpFunctionEnd();
3397       }
3398       break; // no more inflating possible
3399     }
3400     nbSteps++;
3401
3402     // Evaluate achieved thickness
3403     avgThick = 0;
3404     for ( iBeg = 0, iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3405     {
3406       const double shapeTgtThick = data._hypOnShape[ iS ].GetTotalThickness();
3407       for ( iEnd = data._endEdgeOnShape[ iS ]; iBeg < iEnd; ++iBeg )
3408       {
3409         avgThick += Min( 1., data._edges[iBeg]->_len / shapeTgtThick );
3410       }
3411     }
3412     avgThick /= data._edges.size();
3413     debugMsg( "-- Thickness " << curThick << " ("<< avgThick*100 << "%) reached" );
3414
3415     if ( distToIntersection < tgtThick * avgThick * safeFactor && avgThick < 0.9 )
3416     {
3417       debugMsg( "-- Stop inflation since "
3418                 << " distToIntersection( "<<distToIntersection<<" ) < avgThick( "
3419                 << tgtThick * avgThick << " ) * " << safeFactor );
3420       break;
3421     }
3422     // new step size
3423     limitStepSize( data, 0.25 * distToIntersection );
3424     if ( data._stepSizeNodes[0] )
3425       data._stepSize = data._stepSizeCoeff *
3426         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
3427
3428   } // while ( avgThick < 0.99 )
3429
3430   if (nbSteps == 0 )
3431     return error("failed at the very first inflation step", data._index);
3432
3433   if ( avgThick < 0.99 )
3434   {
3435     if ( !data._proxyMesh->_warning || data._proxyMesh->_warning->IsOK() )
3436     {
3437       data._proxyMesh->_warning.reset
3438         ( new SMESH_ComputeError (COMPERR_WARNING,
3439                                   SMESH_Comment("Thickness ") << tgtThick <<
3440                                   " of viscous layers not reached,"
3441                                   " average reached thickness is " << avgThick*tgtThick));
3442     }
3443   }
3444
3445   // Restore position of src nodes moved by infaltion on _noShrinkShapes
3446   dumpFunction(SMESH_Comment("restoNoShrink_So")<<data._index); // debug
3447   for ( iEnd = iS = 0; iS < data._endEdgeOnShape.size(); ++iS )
3448   {
3449     iBeg = iEnd;
3450     iEnd = data._endEdgeOnShape[ iS ];
3451     if ( data._edges[ iBeg ]->_nodes.size() == 1 )
3452       for ( ; iBeg < iEnd; ++iBeg )
3453       {
3454         restoreNoShrink( *data._edges[ iBeg ] );
3455       }
3456   }
3457   dumpFunctionEnd();
3458
3459   return true;
3460 }
3461
3462 //================================================================================
3463 /*!
3464  * \brief Improve quality of layer inner surface and check intersection
3465  */
3466 //================================================================================
3467
3468 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
3469                                      const int   nbSteps,
3470                                      double &    distToIntersection)
3471 {
3472   if ( data._nbShapesToSmooth == 0 )
3473     return true; // no shapes needing smoothing
3474
3475   bool moved, improved;
3476
3477   SMESH_MesherHelper helper(*_mesh);
3478   Handle(Geom_Surface) surface;
3479   TopoDS_Face F;
3480
3481   int iBeg, iEnd = 0;
3482   for ( int iS = 0; iS < data._nbShapesToSmooth; ++iS )
3483   {
3484     iBeg = iEnd;
3485     iEnd = data._endEdgeOnShape[ iS ];
3486
3487     // need to smooth this shape?
3488     bool toSmooth = ( data._hyps.front() == data._hyps.back() );
3489     for ( int i = iBeg; i < iEnd && !toSmooth; ++i )
3490       toSmooth = ( data._edges[ iBeg ]->NbSteps() >= nbSteps+1 );
3491     if ( !toSmooth )
3492     {
3493       if ( iS+1 == data._nbShapesToSmooth )
3494         data._nbShapesToSmooth--;
3495       continue; // target length reached some steps before
3496     }
3497
3498     // prepare data
3499     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
3500          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
3501     {
3502       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
3503         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
3504         helper.SetSubShape( F );
3505         surface = BRep_Tool::Surface( F );
3506       }
3507     }
3508     else
3509     {
3510       F.Nullify(); surface.Nullify();
3511     }
3512     const TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
3513
3514     // perform smoothing
3515
3516     if ( data._edges[ iBeg ]->IsOnEdge() )
3517     { 
3518       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
3519
3520       // try a simple solution on an analytic EDGE
3521       if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
3522       {
3523         // smooth on EDGE's
3524         int step = 0;
3525         do {
3526           moved = false;
3527           for ( int i = iBeg; i < iEnd; ++i )
3528           {
3529             moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
3530           }
3531           dumpCmd( SMESH_Comment("# end step ")<<step);
3532         }
3533         while ( moved && step++ < 5 );
3534       }
3535       dumpFunctionEnd();
3536     }
3537     else
3538     {
3539       // smooth on FACE's
3540
3541       const bool isConcaveFace = data._concaveFaces.count( sInd );
3542
3543       int step = 0, stepLimit = 5, badNb = 0; moved = true;
3544       while (( ++step <= stepLimit && moved ) || improved )
3545       {
3546         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
3547                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
3548         int oldBadNb = badNb;
3549         badNb = 0;
3550         moved = false;
3551         if ( step % 2 )
3552           for ( int i = iBeg; i < iEnd; ++i ) // iterate forward
3553             moved |= data._edges[i]->Smooth( badNb, step, isConcaveFace );
3554         else
3555           for ( int i = iEnd-1; i >= iBeg; --i ) // iterate backward
3556             moved |= data._edges[i]->Smooth( badNb, step, isConcaveFace );
3557         improved = ( badNb < oldBadNb );
3558
3559         // issue 22576 -- no bad faces but still there are intersections to fix
3560         // if ( improved && badNb == 0 )
3561         //   stepLimit = step + 3;
3562
3563         dumpFunctionEnd();
3564       }
3565       if ( badNb > 0 )
3566       {
3567 #ifdef __myDEBUG
3568         double vol = 0;
3569         for ( int i = iBeg; i < iEnd; ++i )
3570         {
3571           _LayerEdge* edge = data._edges[i];
3572           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
3573           for ( size_t j = 0; j < edge->_simplices.size(); ++j )
3574             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
3575             {
3576               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
3577                    << " "<< edge->_simplices[j]._nPrev->GetID()
3578                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
3579               return false;
3580             }
3581         }
3582 #endif
3583         return false;
3584       }
3585     }
3586   } // loop on shapes to smooth
3587
3588   // Check orientation of simplices of _ConvexFace::_simplexTestEdges
3589   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
3590   for ( ; id2face != data._convexFaces.end(); ++id2face )
3591   {
3592     _ConvexFace & convFace = (*id2face).second;
3593     if ( !convFace._simplexTestEdges.empty() &&
3594          convFace._simplexTestEdges[0]->_nodes[0]->GetPosition()->GetDim() == 2 )
3595       continue; // _simplexTestEdges are based on FACE -- already checked while smoothing
3596
3597     if ( !convFace.CheckPrisms() )
3598       return false;
3599   }
3600
3601   // Check if the last segments of _LayerEdge intersects 2D elements;
3602   // checked elements are either temporary faces or faces on surfaces w/o the layers
3603
3604   auto_ptr<SMESH_ElementSearcher> searcher
3605     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
3606                                            data._proxyMesh->GetFaces( data._solid )) );
3607
3608   distToIntersection = Precision::Infinite();
3609   double dist;
3610   const SMDS_MeshElement* intFace = 0;
3611   const SMDS_MeshElement* closestFace = 0;
3612   int iLE = 0;
3613   for ( size_t i = 0; i < data._edges.size(); ++i )
3614   {
3615     if ( !data._edges[i]->_sWOL.IsNull() )
3616       continue;
3617     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
3618       return false;
3619     if ( distToIntersection > dist )
3620     {
3621       // ignore intersection of a _LayerEdge based on a _ConvexFace with a face
3622       // lying on this _ConvexFace
3623       if ( _ConvexFace* convFace = data.GetConvexFace( intFace->getshapeId() ))
3624         if ( convFace->_subIdToEdgeEnd.count ( data._edges[i]->_nodes[0]->getshapeId() ))
3625           continue;
3626
3627       // ignore intersection of a _LayerEdge based on a FACE with an element on this FACE
3628       // ( avoid limiting the thickness on the case of issue 22576)
3629       if ( intFace->getshapeId() == data._edges[i]->_nodes[0]->getshapeId() )
3630         continue;
3631
3632       distToIntersection = dist;
3633       iLE = i;
3634       closestFace = intFace;
3635     }
3636   }
3637 #ifdef __myDEBUG
3638   if ( closestFace )
3639   {
3640     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
3641     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
3642          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
3643          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3644          << ") distance = " << distToIntersection<< endl;
3645   }
3646 #endif
3647
3648   return true;
3649 }
3650
3651 //================================================================================
3652 /*!
3653  * \brief Return a curve of the EDGE to be used for smoothing and arrange
3654  *        _LayerEdge's to be in a consequent order
3655  */
3656 //================================================================================
3657
3658 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
3659                                                const int             iFrom,
3660                                                const int             iTo,
3661                                                const TopoDS_Face&    F,
3662                                                SMESH_MesherHelper&   helper,
3663                                                vector<_LayerEdge* >* edges)
3664 {
3665   TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
3666
3667   map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
3668
3669   if ( i2curve == _edge2curve.end() )
3670   {
3671     if ( edges )
3672       _edges.swap( *edges );
3673
3674     // sort _LayerEdge's by position on the EDGE
3675     SortOnEdge( E, iFrom, iTo, helper );
3676
3677     SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
3678
3679     TopLoc_Location loc; double f,l;
3680
3681     Handle(Geom_Line)   line;
3682     Handle(Geom_Circle) circle;
3683     bool isLine, isCirc;
3684     if ( F.IsNull() ) // 3D case
3685     {
3686       // check if the EDGE is a line
3687       Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
3688       if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
3689         curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
3690
3691       line   = Handle(Geom_Line)::DownCast( curve );
3692       circle = Handle(Geom_Circle)::DownCast( curve );
3693       isLine = (!line.IsNull());
3694       isCirc = (!circle.IsNull());
3695
3696       if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
3697       {
3698         Bnd_B3d bndBox;
3699         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3700         while ( nIt->more() )
3701           bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
3702         gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
3703
3704         gp_Pnt p0, p1;
3705         if ( iTo-iFrom > 1 ) {
3706           p0 = SMESH_TNodeXYZ( _edges[iFrom]->_nodes[0] );
3707           p1 = SMESH_TNodeXYZ( _edges[iFrom+1]->_nodes[0] );
3708         }
3709         else {
3710           p0 = curve->Value( f );
3711           p1 = curve->Value( l );
3712         }
3713         const double lineTol = 1e-2 * p0.Distance( p1 );
3714         for ( int i = 0; i < 3 && !isLine; ++i )
3715           isLine = ( size.Coord( i+1 ) <= lineTol );
3716
3717         if ( isLine )
3718           line = new Geom_Line( gp::OX() ); // only type does matter
3719       }
3720       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3721       {
3722         // TODO
3723       }
3724     }
3725     else // 2D case
3726     {
3727       // check if the EDGE is a line
3728       Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
3729       if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
3730         curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
3731
3732       Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
3733       Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
3734       isLine = (!line2d.IsNull());
3735       isCirc = (!circle2d.IsNull());
3736
3737       if ( !isLine && !isCirc) // Check if the EDGE is close to a line
3738       {
3739         Bnd_B2d bndBox;
3740         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3741         while ( nIt->more() )
3742           bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
3743         gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
3744
3745         const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
3746         for ( int i = 0; i < 2 && !isLine; ++i )
3747           isLine = ( size.Coord( i+1 ) <= lineTol );
3748       }
3749       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
3750       {
3751         // TODO
3752       }
3753       if ( isLine )
3754       {
3755         line = new Geom_Line( gp::OX() ); // only type does matter
3756       }
3757       else if ( isCirc )
3758       {
3759         gp_Pnt2d p = circle2d->Location();
3760         gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
3761         circle = new Geom_Circle( ax, 1.); // only center position does matter
3762       }
3763     }
3764
3765     if ( edges )
3766       _edges.swap( *edges );
3767
3768     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
3769     if ( isLine )
3770       res = line;
3771     else if ( isCirc )
3772       res = circle;
3773
3774     return res;
3775   }
3776   return i2curve->second;
3777 }
3778
3779 //================================================================================
3780 /*!
3781  * \brief Sort _LayerEdge's by a parameter on a given EDGE
3782  */
3783 //================================================================================
3784
3785 void _SolidData::SortOnEdge( const TopoDS_Edge&  E,
3786                              const int           iFrom,
3787                              const int           iTo,
3788                              SMESH_MesherHelper& helper)
3789 {
3790   map< double, _LayerEdge* > u2edge;
3791   for ( int i = iFrom; i < iTo; ++i )
3792     u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
3793
3794   ASSERT( u2edge.size() == iTo - iFrom );
3795   map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
3796   for ( int i = iFrom; i < iTo; ++i, ++u2e )
3797     _edges[i] = u2e->second;
3798
3799   Sort2NeiborsOnEdge( iFrom, iTo );
3800 }
3801
3802 //================================================================================
3803 /*!
3804  * \brief Set _2neibors according to the order of _LayerEdge on EDGE
3805  */
3806 //================================================================================
3807
3808 void _SolidData::Sort2NeiborsOnEdge( const int iFrom, const int iTo)
3809 {
3810   for ( int i = iFrom; i < iTo-1; ++i )
3811     if ( _edges[i]->_2neibors->tgtNode(1) != _edges[i+1]->_nodes.back() )
3812       _edges[i]->_2neibors->reverse();
3813   if ( iTo - iFrom > 1 &&
3814        _edges[iTo-1]->_2neibors->tgtNode(0) != _edges[iTo-2]->_nodes.back() )
3815     _edges[iTo-1]->_2neibors->reverse();
3816 }
3817
3818 //================================================================================
3819 /*!
3820  * \brief Return index corresponding to the shape in _endEdgeOnShape
3821  */
3822 //================================================================================
3823
3824 bool _SolidData::GetShapeEdges(const TGeomID shapeID,
3825                                size_t &      iEdgesEnd,
3826                                int*          iBeg,
3827                                int*          iEnd ) const
3828 {
3829   int beg = 0, end = 0;
3830   for ( iEdgesEnd = 0; iEdgesEnd < _endEdgeOnShape.size(); ++iEdgesEnd )
3831   {
3832     end = _endEdgeOnShape[ iEdgesEnd ];
3833     TGeomID sID = _edges[ beg ]->_nodes[0]->getshapeId();
3834     if ( sID == shapeID )
3835     {
3836       if ( iBeg ) *iBeg = beg;
3837       if ( iEnd ) *iEnd = end;
3838       return true;
3839     }
3840     beg = end;
3841   }
3842   return false;
3843 }
3844
3845 //================================================================================
3846 /*!
3847  * \brief Prepare data of the _LayerEdge for smoothing on FACE
3848  */
3849 //================================================================================
3850
3851 void _SolidData::PrepareEdgesToSmoothOnFace( _LayerEdge**       edgeBeg,
3852                                              _LayerEdge**       edgeEnd,
3853                                              const TopoDS_Face& face,
3854                                              bool               substituteSrcNodes )
3855 {
3856   set< TGeomID > vertices;
3857   SMESH_MesherHelper helper( *_proxyMesh->GetMesh() );
3858   if ( isConcave( face, helper, &vertices ))
3859     _concaveFaces.insert( (*edgeBeg)->_nodes[0]->getshapeId() );
3860
3861   for ( _LayerEdge** edge = edgeBeg; edge != edgeEnd; ++edge )
3862     (*edge)->_smooFunction = 0;
3863
3864   for ( ; edgeBeg != edgeEnd; ++edgeBeg )
3865   {
3866     _LayerEdge* edge = *edgeBeg;
3867     _Simplex::GetSimplices
3868       ( edge->_nodes[0], edge->_simplices, _ignoreFaceIds, this, /*sort=*/true );
3869
3870     edge->ChooseSmooFunction( vertices, _n2eMap );
3871
3872     double avgNormProj = 0, avgLen = 0;
3873     for ( size_t i = 0; i < edge->_simplices.size(); ++i )
3874     {
3875       _Simplex& s = edge->_simplices[i];
3876
3877       gp_XYZ  vec = edge->_pos.back() - SMESH_TNodeXYZ( s._nPrev );
3878       avgNormProj += edge->_normal * vec;
3879       avgLen      += vec.Modulus();
3880       if ( substituteSrcNodes )
3881       {
3882         s._nNext = _n2eMap[ s._nNext ]->_nodes.back();
3883         s._nPrev = _n2eMap[ s._nPrev ]->_nodes.back();
3884       }
3885     }
3886     avgNormProj /= edge->_simplices.size();
3887     avgLen      /= edge->_simplices.size();
3888     edge->_curvature = _Curvature::New( avgNormProj, avgLen );
3889   }
3890 }
3891
3892 //================================================================================
3893 /*!
3894  * \brief Add faces for smoothing
3895  */
3896 //================================================================================
3897
3898 void _SolidData::AddShapesToSmooth( const set< TGeomID >& faceIDs )
3899 {
3900   // convert faceIDs to indices in _endEdgeOnShape
3901   set< size_t > iEnds;
3902   size_t end;
3903   set< TGeomID >::const_iterator fId = faceIDs.begin();
3904   for ( ; fId != faceIDs.end(); ++fId )
3905     if ( GetShapeEdges( *fId, end ) && end >= _nbShapesToSmooth )
3906       iEnds.insert( end );
3907
3908   set< size_t >::iterator endsIt = iEnds.begin();
3909
3910   // "add" by move of _nbShapesToSmooth
3911   int nbFacesToAdd = iEnds.size();
3912   while ( endsIt != iEnds.end() && *endsIt == _nbShapesToSmooth )
3913   {
3914     ++endsIt;
3915     ++_nbShapesToSmooth;
3916     --nbFacesToAdd;
3917   }
3918   if ( endsIt == iEnds.end() )
3919     return;
3920
3921   // Move _LayerEdge's on FACEs just after _nbShapesToSmooth
3922
3923   vector< _LayerEdge* > nonSmoothLE, smoothLE;
3924   size_t lastSmooth = *iEnds.rbegin();
3925   int iBeg, iEnd;
3926   for ( size_t i = _nbShapesToSmooth; i <= lastSmooth; ++i )
3927   {
3928     bool toSmooth = iEnds.count(i);
3929     vector< _LayerEdge* > & edgesVec = toSmooth ? smoothLE : nonSmoothLE;
3930     iBeg = i ? _endEdgeOnShape[ i-1 ] : 0;
3931     iEnd = _endEdgeOnShape[ i ];
3932     edgesVec.insert( edgesVec.end(), _edges.begin() + iBeg, _edges.begin() + iEnd );
3933
3934     // preparation for smoothing on FACE
3935     if ( toSmooth && _edges[iBeg]->_nodes[0]->GetPosition()->GetDim() == 2 )
3936     {
3937       TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( _edges[iBeg]->_nodes[0],
3938                                                               _proxyMesh->GetMeshDS() );
3939       if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
3940       {
3941         PrepareEdgesToSmoothOnFace( &_edges[ iBeg ],
3942                                     &_edges[ iEnd ],
3943                                     TopoDS::Face( S ),
3944                                     /*substituteSrcNodes=*/true );
3945       }
3946     }
3947   }
3948
3949   iBeg = _nbShapesToSmooth ? _endEdgeOnShape[ _nbShapesToSmooth-1 ] : 0;
3950   std::copy( smoothLE.begin(),    smoothLE.end(),    &_edges[ iBeg ] );
3951   std::copy( nonSmoothLE.begin(), nonSmoothLE.end(), &_edges[ iBeg + smoothLE.size()]);
3952
3953   // update _endEdgeOnShape
3954   for ( size_t i = _nbShapesToSmooth; i < _endEdgeOnShape.size(); ++i )
3955   {
3956     TGeomID curShape = _edges[ iBeg ]->_nodes[0]->getshapeId();
3957     while ( ++iBeg < _edges.size() &&
3958             curShape == _edges[ iBeg ]->_nodes[0]->getshapeId() );
3959
3960     _endEdgeOnShape[ i ] = iBeg;
3961   }
3962
3963   _nbShapesToSmooth += nbFacesToAdd;
3964 }
3965
3966 //================================================================================
3967 /*!
3968  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
3969  */
3970 //================================================================================
3971
3972 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
3973                                           const int             iFrom,
3974                                           const int             iTo,
3975                                           Handle(Geom_Surface)& surface,
3976                                           const TopoDS_Face&    F,
3977                                           SMESH_MesherHelper&   helper)
3978 {
3979   TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
3980                                              helper.GetMeshDS());
3981   TopoDS_Edge E = TopoDS::Edge( S );
3982
3983   Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, F, helper );
3984   if ( curve.IsNull() ) return false;
3985
3986   // compute a relative length of segments
3987   vector< double > len( iTo-iFrom+1 );
3988   {
3989     double curLen, prevLen = len[0] = 1.0;
3990     for ( int i = iFrom; i < iTo; ++i )
3991     {
3992       curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
3993       len[i-iFrom+1] = len[i-iFrom] + curLen;
3994       prevLen = curLen;
3995     }
3996   }
3997
3998   if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
3999   {
4000     if ( F.IsNull() ) // 3D
4001     {
4002       SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->tgtNode(0));
4003       SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->tgtNode(1));
4004       for ( int i = iFrom; i < iTo; ++i )
4005       {
4006         double r = len[i-iFrom] / len.back();
4007         gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
4008         data._edges[i]->_pos.back() = newPos;
4009         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4010         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4011         dumpMove( tgtNode );
4012       }
4013     }
4014     else
4015     {
4016       // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
4017       // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
4018       gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
4019       gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
4020       if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
4021            data._edges[iTo-1]->_2neibors->tgtNode(1) ) // closed edge
4022       {
4023         int iPeriodic = helper.GetPeriodicIndex();
4024         if ( iPeriodic == 1 || iPeriodic == 2 )
4025         {
4026           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
4027           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
4028             std::swap( uv0, uv1 );
4029         }
4030       }
4031       const gp_XY rangeUV = uv1 - uv0;
4032       for ( int i = iFrom; i < iTo; ++i )
4033       {
4034         double r = len[i-iFrom] / len.back();
4035         gp_XY newUV = uv0 + r * rangeUV;
4036         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4037
4038         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4039         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4040         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4041         dumpMove( tgtNode );
4042
4043         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4044         pos->SetUParameter( newUV.X() );
4045         pos->SetVParameter( newUV.Y() );
4046       }
4047     }
4048     return true;
4049   }
4050
4051   if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
4052   {
4053     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
4054     gp_Pnt center3D = circle->Location();
4055
4056     if ( F.IsNull() ) // 3D
4057     {
4058       if ( data._edges[iFrom]->_2neibors->tgtNode(0) ==
4059            data._edges[iTo-1]->_2neibors->tgtNode(1) )
4060         return true; // closed EDGE - nothing to do
4061
4062       return false; // TODO ???
4063     }
4064     else // 2D
4065     {
4066       const gp_XY center( center3D.X(), center3D.Y() );
4067
4068       gp_XY uv0 = data._edges[iFrom]->_2neibors->_edges[0]->LastUV( F );
4069       gp_XY uvM = data._edges[iFrom]->LastUV( F );
4070       gp_XY uv1 = data._edges[iTo-1]->_2neibors->_edges[1]->LastUV( F );
4071       // gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->tgtNode(0));
4072       // gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
4073       // gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->tgtNode(1));
4074       gp_Vec2d vec0( center, uv0 );
4075       gp_Vec2d vecM( center, uvM );
4076       gp_Vec2d vec1( center, uv1 );
4077       double uLast = vec0.Angle( vec1 ); // -PI - +PI
4078       double uMidl = vec0.Angle( vecM );
4079       if ( uLast * uMidl <= 0. )
4080         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
4081       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
4082
4083       gp_Ax2d   axis( center, vec0 );
4084       gp_Circ2d circ( axis, radius );
4085       for ( int i = iFrom; i < iTo; ++i )
4086       {
4087         double    newU = uLast * len[i-iFrom] / len.back();
4088         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
4089         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
4090
4091         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
4092         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
4093         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
4094         dumpMove( tgtNode );
4095
4096         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4097         pos->SetUParameter( newUV.X() );
4098         pos->SetVParameter( newUV.Y() );
4099       }
4100     }
4101     return true;
4102   }
4103
4104   return false;
4105 }
4106
4107 //================================================================================
4108 /*!
4109  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
4110  * _LayerEdge's on neighbor EDGE's
4111  */
4112 //================================================================================
4113
4114 bool _ViscousBuilder::updateNormals( _SolidData&         data,
4115                                      SMESH_MesherHelper& helper,
4116                                      int                 stepNb )
4117 {
4118   if ( stepNb > 0 )
4119     return updateNormalsOfConvexFaces( data, helper, stepNb );
4120
4121   // make temporary quadrangles got by extrusion of
4122   // mesh edges along _LayerEdge._normal's
4123
4124   vector< const SMDS_MeshElement* > tmpFaces;
4125   {
4126     set< SMESH_TLink > extrudedLinks; // contains target nodes
4127     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
4128
4129     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
4130     for ( size_t i = 0; i < data._edges.size(); ++i )
4131     {
4132       _LayerEdge* edge = data._edges[i];
4133       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
4134       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
4135       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
4136       {
4137         const SMDS_MeshNode* tgt2 = edge->_2neibors->tgtNode(j);
4138         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
4139           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
4140         if ( !link_isnew.second )
4141         {
4142           extrudedLinks.erase( link_isnew.first );
4143           continue; // already extruded and will no more encounter
4144         }
4145         // a _LayerEdge containg tgt2
4146         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
4147
4148         _TmpMeshFaceOnEdge* f = new _TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
4149         tmpFaces.push_back( f );
4150
4151         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
4152                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
4153                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
4154       }
4155     }
4156     dumpFunctionEnd();
4157   }
4158   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
4159   // Perform two loops on _LayerEdge on EDGE's:
4160   // 1) to find and fix intersection
4161   // 2) to check that no new intersection appears as result of 1)
4162
4163   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
4164                                                             tmpFaces.end()));
4165   auto_ptr<SMESH_ElementSearcher> searcher
4166     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
4167
4168   // 1) Find intersections
4169   double dist;
4170   const SMDS_MeshElement* face;
4171   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
4172   TLEdge2LEdgeSet edge2CloseEdge;
4173
4174   const double eps = data._epsilon * data._epsilon;
4175   for ( size_t i = 0; i < data._edges.size(); ++i )
4176   {
4177     _LayerEdge* edge = data._edges[i];
4178     if (( !edge->IsOnEdge() ) &&
4179         ( edge->_sWOL.IsNull() || edge->_sWOL.ShapeType() != TopAbs_FACE ))
4180       continue;
4181     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
4182     {
4183       const _TmpMeshFaceOnEdge* f = (const _TmpMeshFaceOnEdge*) face;
4184       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
4185       ee.insert( f->_le1 );
4186       ee.insert( f->_le2 );
4187       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
4188         edge2CloseEdge[ f->_le1 ].insert( edge );
4189       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
4190         edge2CloseEdge[ f->_le2 ].insert( edge );
4191     }
4192   }
4193
4194   // Set _LayerEdge._normal
4195
4196   if ( !edge2CloseEdge.empty() )
4197   {
4198     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
4199
4200     set< TGeomID > shapesToSmooth;
4201
4202     // vector to store new _normal and _cosin for each edge in edge2CloseEdge
4203     vector< pair< _LayerEdge*, _LayerEdge > > edge2newEdge( edge2CloseEdge.size() );
4204
4205     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
4206     for ( size_t iE = 0; e2ee != edge2CloseEdge.end(); ++e2ee, ++iE )
4207     {
4208       _LayerEdge* edge1 = e2ee->first;
4209       _LayerEdge* edge2 = 0;
4210       set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
4211
4212       edge2newEdge[ iE ].first = NULL;
4213
4214       // find EDGEs the edges reside
4215       // TopoDS_Edge E1, E2;
4216       // TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4217       // if ( S.ShapeType() != TopAbs_EDGE )
4218       //   continue; // TODO: find EDGE by VERTEX
4219       // E1 = TopoDS::Edge( S );
4220       set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
4221       for ( ; !edge2 && eIt != ee.end(); ++eIt )
4222       {
4223         if ( edge1->_sWOL == (*eIt)->_sWOL )
4224           edge2 = *eIt;
4225       }
4226       if ( !edge2 ) continue;
4227
4228       edge2newEdge[ iE ].first = edge1;
4229       _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4230       // while ( E2.IsNull() && eIt != ee.end())
4231       // {
4232       //   _LayerEdge* e2 = *eIt++;
4233       //   TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
4234       //   if ( S.ShapeType() == TopAbs_EDGE )
4235       //     E2 = TopoDS::Edge( S ), edge2 = e2;
4236       // }
4237       // if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
4238
4239       // find 3 FACEs sharing 2 EDGEs
4240
4241       // TopoDS_Face FF1[2], FF2[2];
4242       // PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
4243       // while ( fIt->more() && FF1[1].IsNull() )
4244       // {
4245       //   const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4246       //   if ( helper.IsSubShape( *F, data._solid))
4247       //     FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
4248       // }
4249       // fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
4250       // while ( fIt->more() && FF2[1].IsNull())
4251       // {
4252       //   const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
4253       //   if ( helper.IsSubShape( *F, data._solid))
4254       //     FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
4255       // }
4256       // // exclude a FACE common to E1 and E2 (put it to FFn[1] )
4257       // if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
4258       //   std::swap( FF1[0], FF1[1] );
4259       // if ( FF2[0].IsSame( FF1[0]) )
4260       //   std::swap( FF2[0], FF2[1] );
4261       // if ( FF1[0].IsNull() || FF2[0].IsNull() )
4262       //   continue;
4263
4264       // get a new normal for edge1
4265       //bool ok;
4266       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
4267       // if ( edge1->_cosin < 0 )
4268       //   dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
4269       // if ( edge2->_cosin < 0 )
4270       //   dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
4271
4272       double cos1 = Abs( edge1->_cosin ), cos2 = Abs( edge2->_cosin );
4273       double wgt1 = ( cos1 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4274       double wgt2 = ( cos2 + 0.001 ) / ( cos1 + cos2 + 0.002 );
4275       newEdge._normal = ( wgt1 * dir1 + wgt2 * dir2 ).XYZ();
4276       newEdge._normal.Normalize();
4277
4278       // cout << edge1->_nodes[0]->GetID() << " "
4279       //      << edge2->_nodes[0]->GetID() << " NORM: "
4280       //      << newEdge._normal.X() << ", " << newEdge._normal.Y() << ", " << newEdge._normal.Z() << endl;
4281
4282       // get new cosin
4283       if ( cos1 < theMinSmoothCosin )
4284       {
4285         newEdge._cosin = edge2->_cosin;
4286       }
4287       else if ( cos2 > theMinSmoothCosin ) // both cos1 and cos2 > theMinSmoothCosin
4288       {
4289         // gp_Vec dirInFace;
4290         // if ( edge1->_cosin < 0 )
4291         //   dirInFace = dir1;
4292         // else
4293         //   dirInFace = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
4294         // double angle = dirInFace.Angle( edge1->_normal ); // [0,PI]
4295         // edge1->SetCosin( Cos( angle ));
4296         //newEdge._cosin = 0; // ???????????
4297         newEdge._cosin = ( wgt1 * cos1 + wgt2 * cos2 ) * edge1->_cosin / cos1;
4298       }
4299       else
4300       {
4301         newEdge._cosin = edge1->_cosin;
4302       }
4303
4304       // find shapes that need smoothing due to change of _normal
4305       if ( edge1->_cosin  < theMinSmoothCosin &&
4306            newEdge._cosin > theMinSmoothCosin )
4307       {
4308         if ( edge1->_sWOL.IsNull() )
4309         {
4310           SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
4311           while ( fIt->more() )
4312             shapesToSmooth.insert( fIt->next()->getshapeId() );
4313           //limitStepSize( data, fIt->next(), edge1->_cosin ); // too late
4314         }
4315         else // edge1 inflates along a FACE
4316         {
4317           TopoDS_Shape V = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
4318           PShapeIteratorPtr eIt = helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
4319           while ( const TopoDS_Shape* E = eIt->next() )
4320           {
4321             if ( !helper.IsSubShape( *E, /*FACE=*/edge1->_sWOL ))
4322               continue;
4323             gp_Vec edgeDir = getEdgeDir( TopoDS::Edge( *E ), TopoDS::Vertex( V ));
4324             double   angle = edgeDir.Angle( newEdge._normal ); // [0,PI]
4325             if ( angle < M_PI / 2 )
4326               shapesToSmooth.insert( getMeshDS()->ShapeToIndex( *E ));
4327           }
4328         }
4329       }
4330     }
4331
4332     data.AddShapesToSmooth( shapesToSmooth );
4333
4334     // Update data of edges depending on a new _normal
4335
4336     for ( size_t iE = 0; iE < edge2newEdge.size(); ++iE )
4337     {
4338       _LayerEdge*   edge1 = edge2newEdge[ iE ].first;
4339       _LayerEdge& newEdge = edge2newEdge[ iE ].second;
4340       if ( !edge1 ) continue;
4341
4342       edge1->_normal = newEdge._normal;
4343       edge1->SetCosin( newEdge._cosin );
4344       edge1->InvalidateStep( 1 );
4345       edge1->_len = 0;
4346       edge1->SetNewLength( data._stepSize, helper );
4347       if ( edge1->IsOnEdge() )
4348       {
4349         const SMDS_MeshNode * n1 = edge1->_2neibors->srcNode(0);
4350         const SMDS_MeshNode * n2 = edge1->_2neibors->srcNode(1);
4351         edge1->SetDataByNeighbors( n1, n2, helper );
4352       }
4353
4354       // Update normals and other dependent data of not intersecting _LayerEdge's
4355       // neighboring the intersecting ones
4356
4357       if ( !edge1->_2neibors )
4358         continue;
4359       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
4360       {
4361         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
4362         if ( edge2CloseEdge.count ( neighbor ))
4363           continue; // j-th neighbor is also intersected
4364         _LayerEdge* prevEdge = edge1;
4365         const int nbSteps = 10;
4366         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
4367         {
4368           if ( !neighbor->_2neibors )
4369             break; // neighbor is on VERTEX
4370           int iNext = 0;
4371           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
4372           if ( nextEdge == prevEdge )
4373             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
4374           double r = double(step-1)/nbSteps;
4375           if ( !nextEdge->_2neibors )
4376             r = 0.5;
4377
4378           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
4379           newNorm.Normalize();
4380
4381           neighbor->_normal = newNorm;
4382           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
4383           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
4384
4385           neighbor->InvalidateStep( 1 );
4386           neighbor->_len = 0;
4387           neighbor->SetNewLength( data._stepSize, helper );
4388
4389           // goto the next neighbor
4390           prevEdge = neighbor;
4391           neighbor = nextEdge;
4392         }
4393       }
4394     }
4395     dumpFunctionEnd();
4396   }
4397   // 2) Check absence of intersections
4398   // TODO?
4399
4400   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
4401     delete tmpFaces[i];
4402
4403   return true;
4404 }
4405
4406 //================================================================================
4407 /*!
4408  * \brief Modify normals of _LayerEdge's on _ConvexFace's
4409  */
4410 //================================================================================
4411
4412 bool _ViscousBuilder::updateNormalsOfConvexFaces( _SolidData&         data,
4413                                                   SMESH_MesherHelper& helper,
4414                                                   int                 stepNb )
4415 {
4416   SMESHDS_Mesh* meshDS = helper.GetMeshDS();
4417   bool isOK;
4418
4419   map< TGeomID, _ConvexFace >::iterator id2face = data._convexFaces.begin();
4420   for ( ; id2face != data._convexFaces.end(); ++id2face )
4421   {
4422     _ConvexFace & convFace = (*id2face).second;
4423     if ( convFace._normalsFixed )
4424       continue; // already fixed
4425     if ( convFace.CheckPrisms() )
4426       continue; // nothing to fix
4427
4428     convFace._normalsFixed = true;
4429
4430     BRepAdaptor_Surface surface ( convFace._face, false );
4431     BRepLProp_SLProps   surfProp( surface, 2, 1e-6 );
4432
4433     // check if the convex FACE is of spherical shape
4434
4435     Bnd_B3d centersBox; // bbox of centers of curvature of _LayerEdge's on VERTEXes
4436     Bnd_B3d nodesBox;
4437     gp_Pnt  center;
4438     int     iBeg, iEnd;
4439
4440     map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.begin();
4441     for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4442     {
4443       data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4444
4445       if ( meshDS->IndexToShape( id2end->first ).ShapeType() == TopAbs_VERTEX )
4446       {
4447         _LayerEdge* ledge = data._edges[ iBeg ];
4448         if ( convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4449           centersBox.Add( center );
4450       }
4451       for ( ; iBeg < iEnd; ++iBeg )
4452         nodesBox.Add( SMESH_TNodeXYZ( data._edges[ iBeg ]->_nodes[0] ));
4453     }
4454     if ( centersBox.IsVoid() )
4455     {
4456       debugMsg( "Error: centersBox.IsVoid()" );
4457       return false;
4458     }
4459     const bool isSpherical =
4460       ( centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4461
4462     int nbEdges = helper.Count( convFace._face, TopAbs_EDGE, /*ignoreSame=*/false );
4463     vector < _CentralCurveOnEdge > centerCurves( nbEdges );
4464
4465     if ( isSpherical )
4466     {
4467       // set _LayerEdge::_normal as average of all normals
4468
4469       // WARNING: different density of nodes on EDGEs is not taken into account that
4470       // can lead to an improper new normal
4471
4472       gp_XYZ avgNormal( 0,0,0 );
4473       nbEdges = 0;
4474       id2end = convFace._subIdToEdgeEnd.begin();
4475       for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4476       {
4477         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4478         // set data of _CentralCurveOnEdge
4479         const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
4480         if ( S.ShapeType() == TopAbs_EDGE )
4481         {
4482           _CentralCurveOnEdge& ceCurve = centerCurves[ nbEdges++ ];
4483           ceCurve.SetShapes( TopoDS::Edge(S), convFace, data, helper );
4484           if ( !data._edges[ iBeg ]->_sWOL.IsNull() )
4485             ceCurve._adjFace.Nullify();
4486           else
4487             ceCurve._ledges.insert( ceCurve._ledges.end(),
4488                                     &data._edges[ iBeg ], &data._edges[ iEnd ]);
4489         }
4490         // summarize normals
4491         for ( ; iBeg < iEnd; ++iBeg )
4492           avgNormal += data._edges[ iBeg ]->_normal;
4493       }
4494       double normSize = avgNormal.SquareModulus();
4495       if ( normSize < 1e-200 )
4496       {
4497         debugMsg( "updateNormalsOfConvexFaces(): zero avgNormal" );
4498         return false;
4499       }
4500       avgNormal /= Sqrt( normSize );
4501
4502       // compute new _LayerEdge::_cosin on EDGEs
4503       double avgCosin = 0;
4504       int     nbCosin = 0;
4505       gp_Vec inFaceDir;
4506       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4507       {
4508         _CentralCurveOnEdge& ceCurve = centerCurves[ iE ];
4509         if ( ceCurve._adjFace.IsNull() )
4510           continue;
4511         for ( size_t iLE = 0; iLE < ceCurve._ledges.size(); ++iLE )
4512         {
4513           const SMDS_MeshNode* node = ceCurve._ledges[ iLE ]->_nodes[0];
4514           inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4515           if ( isOK )
4516           {
4517             double angle = inFaceDir.Angle( avgNormal ); // [0,PI]
4518             ceCurve._ledges[ iLE ]->_cosin = Cos( angle );
4519             avgCosin += ceCurve._ledges[ iLE ]->_cosin;
4520             nbCosin++;
4521           }
4522         }
4523       }
4524       if ( nbCosin > 0 )
4525         avgCosin /= nbCosin;
4526
4527       // set _LayerEdge::_normal = avgNormal
4528       id2end = convFace._subIdToEdgeEnd.begin();
4529       for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4530       {
4531         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4532         const TopoDS_Shape& S = meshDS->IndexToShape( id2end->first );
4533         if ( S.ShapeType() != TopAbs_EDGE )
4534           for ( int i = iBeg; i < iEnd; ++i )
4535             data._edges[ i ]->_cosin = avgCosin;
4536
4537         for ( ; iBeg < iEnd; ++iBeg )
4538           data._edges[ iBeg ]->_normal = avgNormal;
4539       }
4540     }
4541     else // if ( isSpherical )
4542     {
4543       // We suppose that centers of curvature at all points of the FACE
4544       // lie on some curve, let's call it "central curve". For all _LayerEdge's
4545       // having a common center of curvature we define the same new normal
4546       // as a sum of normals of _LayerEdge's on EDGEs among them.
4547
4548       // get all centers of curvature for each EDGE
4549
4550       helper.SetSubShape( convFace._face );
4551       _LayerEdge* vertexLEdges[2], **edgeLEdge, **edgeLEdgeEnd;
4552
4553       TopExp_Explorer edgeExp( convFace._face, TopAbs_EDGE );
4554       for ( int iE = 0; edgeExp.More(); edgeExp.Next(), ++iE )
4555       {
4556         const TopoDS_Edge& edge = TopoDS::Edge( edgeExp.Current() );
4557
4558         // set adjacent FACE
4559         centerCurves[ iE ].SetShapes( edge, convFace, data, helper );
4560
4561         // get _LayerEdge's of the EDGE
4562         TGeomID edgeID = meshDS->ShapeToIndex( edge );
4563         id2end = convFace._subIdToEdgeEnd.find( edgeID );
4564         if ( id2end == convFace._subIdToEdgeEnd.end() )
4565         {
4566           // no _LayerEdge's on EDGE, use _LayerEdge's on VERTEXes
4567           for ( int iV = 0; iV < 2; ++iV )
4568           {
4569             TopoDS_Vertex v = helper.IthVertex( iV, edge );
4570             TGeomID     vID = meshDS->ShapeToIndex( v );
4571             int  end = convFace._subIdToEdgeEnd[ vID ];
4572             int iBeg = end > 0 ? data._endEdgeOnShape[ end-1 ] : 0;
4573             vertexLEdges[ iV ] = data._edges[ iBeg ];
4574           }
4575           edgeLEdge    = &vertexLEdges[0];
4576           edgeLEdgeEnd = edgeLEdge + 2;
4577
4578           centerCurves[ iE ]._adjFace.Nullify();
4579         }
4580         else
4581         {
4582           data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4583           if ( id2end->second >= data._nbShapesToSmooth )
4584             data.SortOnEdge( edge, iBeg, iEnd, helper );
4585           edgeLEdge    = &data._edges[ iBeg ];
4586           edgeLEdgeEnd = edgeLEdge + iEnd - iBeg;
4587           vertexLEdges[0] = data._edges[ iBeg   ]->_2neibors->_edges[0];
4588           vertexLEdges[1] = data._edges[ iEnd-1 ]->_2neibors->_edges[1];
4589
4590           if ( ! data._edges[ iBeg ]->_sWOL.IsNull() )
4591             centerCurves[ iE ]._adjFace.Nullify();
4592         }
4593
4594         // Get curvature centers
4595
4596         centersBox.Clear();
4597
4598         if ( edgeLEdge[0]->IsOnEdge() &&
4599              convFace.GetCenterOfCurvature( vertexLEdges[0], surfProp, helper, center ))
4600         { // 1st VERTEX
4601           centerCurves[ iE ].Append( center, vertexLEdges[0] );
4602           centersBox.Add( center );
4603         }
4604         for ( ; edgeLEdge < edgeLEdgeEnd; ++edgeLEdge )
4605           if ( convFace.GetCenterOfCurvature( *edgeLEdge, surfProp, helper, center ))
4606           { // EDGE or VERTEXes
4607             centerCurves[ iE ].Append( center, *edgeLEdge );
4608             centersBox.Add( center );
4609           }
4610         if ( edgeLEdge[-1]->IsOnEdge() &&
4611              convFace.GetCenterOfCurvature( vertexLEdges[1], surfProp, helper, center ))
4612         { // 2nd VERTEX
4613           centerCurves[ iE ].Append( center, vertexLEdges[1] );
4614           centersBox.Add( center );
4615         }
4616         centerCurves[ iE ]._isDegenerated =
4617           ( centersBox.IsVoid() || centersBox.SquareExtent() < 1e-6 * nodesBox.SquareExtent() );
4618
4619       } // loop on EDGES of convFace._face to set up data of centerCurves
4620
4621       // Compute new normals for _LayerEdge's on EDGEs
4622
4623       double avgCosin = 0;
4624       int     nbCosin = 0;
4625       gp_Vec inFaceDir;
4626       for ( size_t iE1 = 0; iE1 < centerCurves.size(); ++iE1 )
4627       {
4628         _CentralCurveOnEdge& ceCurve = centerCurves[ iE1 ];
4629         if ( ceCurve._isDegenerated )
4630           continue;
4631         const vector< gp_Pnt >& centers = ceCurve._curvaCenters;
4632         vector< gp_XYZ > &   newNormals = ceCurve._normals;
4633         for ( size_t iC1 = 0; iC1 < centers.size(); ++iC1 )
4634         {
4635           isOK = false;
4636           for ( size_t iE2 = 0; iE2 < centerCurves.size() && !isOK; ++iE2 )
4637           {
4638             if ( iE1 != iE2 )
4639               isOK = centerCurves[ iE2 ].FindNewNormal( centers[ iC1 ], newNormals[ iC1 ]);
4640           }
4641           if ( isOK && !ceCurve._adjFace.IsNull() )
4642           {
4643             // compute new _LayerEdge::_cosin
4644             const SMDS_MeshNode* node = ceCurve._ledges[ iC1 ]->_nodes[0];
4645             inFaceDir = getFaceDir( ceCurve._adjFace, ceCurve._edge, node, helper, isOK );
4646             if ( isOK )
4647             {
4648               double angle = inFaceDir.Angle( newNormals[ iC1 ] ); // [0,PI]
4649               ceCurve._ledges[ iC1 ]->_cosin = Cos( angle );
4650               avgCosin += ceCurve._ledges[ iC1 ]->_cosin;
4651               nbCosin++;
4652             }
4653           }
4654         }
4655       }
4656       // set new normals to _LayerEdge's of NOT degenerated central curves
4657       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4658       {
4659         if ( centerCurves[ iE ]._isDegenerated )
4660           continue;
4661         for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4662           centerCurves[ iE ]._ledges[ iLE ]->_normal = centerCurves[ iE ]._normals[ iLE ];
4663       }
4664       // set new normals to _LayerEdge's of     degenerated central curves
4665       for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4666       {
4667         if ( !centerCurves[ iE ]._isDegenerated ||
4668              centerCurves[ iE ]._ledges.size() < 3 )
4669           continue;
4670         // new normal is an average of new normals at VERTEXes that
4671         // was computed on non-degenerated _CentralCurveOnEdge's
4672         gp_XYZ newNorm = ( centerCurves[ iE ]._ledges.front()->_normal +
4673                            centerCurves[ iE ]._ledges.back ()->_normal );
4674         double sz = newNorm.Modulus();
4675         if ( sz < 1e-200 )
4676           continue;
4677         newNorm /= sz;
4678         double newCosin = ( 0.5 * centerCurves[ iE ]._ledges.front()->_cosin +
4679                             0.5 * centerCurves[ iE ]._ledges.back ()->_cosin );
4680         for ( size_t iLE = 1, nb = centerCurves[ iE ]._ledges.size() - 1; iLE < nb; ++iLE )
4681         {
4682           centerCurves[ iE ]._ledges[ iLE ]->_normal = newNorm;
4683           centerCurves[ iE ]._ledges[ iLE ]->_cosin  = newCosin;
4684         }
4685       }
4686
4687       // Find new normals for _LayerEdge's based on FACE
4688
4689       if ( nbCosin > 0 )
4690         avgCosin /= nbCosin;
4691       const TGeomID faceID = meshDS->ShapeToIndex( convFace._face );
4692       map< TGeomID, int >::iterator id2end = convFace._subIdToEdgeEnd.find( faceID );
4693       if ( id2end != convFace._subIdToEdgeEnd.end() )
4694       {
4695         int iE = 0;
4696         gp_XYZ newNorm;
4697         data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4698         for ( ; iBeg < iEnd; ++iBeg )
4699         {
4700           _LayerEdge* ledge = data._edges[ iBeg ];
4701           if ( !convFace.GetCenterOfCurvature( ledge, surfProp, helper, center ))
4702             continue;
4703           for ( size_t i = 0; i < centerCurves.size(); ++i, ++iE )
4704           {
4705             iE = iE % centerCurves.size();
4706             if ( centerCurves[ iE ]._isDegenerated )
4707               continue;
4708             newNorm.SetCoord( 0,0,0 );
4709             if ( centerCurves[ iE ].FindNewNormal( center, newNorm ))
4710             {
4711               ledge->_normal = newNorm;
4712               ledge->_cosin  = avgCosin;
4713               break;
4714             }
4715           }
4716         }
4717       }
4718
4719     } // not a quasi-spherical FACE
4720
4721     // Update _LayerEdge's data according to a new normal
4722
4723     dumpFunction(SMESH_Comment("updateNormalsOfConvexFaces")<<data._index
4724                  <<"_F"<<meshDS->ShapeToIndex( convFace._face ));
4725
4726     id2end = convFace._subIdToEdgeEnd.begin();
4727     for ( ; id2end != convFace._subIdToEdgeEnd.end(); ++id2end )
4728     {
4729       data.GetEdgesOnShape( id2end->second, iBeg, iEnd );
4730       for ( ; iBeg < iEnd; ++iBeg )
4731       {
4732         _LayerEdge* & ledge = data._edges[ iBeg ];
4733         double len = ledge->_len;
4734         ledge->InvalidateStep( stepNb + 1, /*restoreLength=*/true );
4735         ledge->SetCosin( ledge->_cosin );
4736         ledge->SetNewLength( len, helper );
4737       }
4738
4739     } // loop on sub-shapes of convFace._face
4740
4741     // Find FACEs adjacent to convFace._face that got necessity to smooth
4742     // as a result of normals modification
4743
4744     set< TGeomID > adjFacesToSmooth;
4745     for ( size_t iE = 0; iE < centerCurves.size(); ++iE )
4746     {
4747       if ( centerCurves[ iE ]._adjFace.IsNull() ||
4748            centerCurves[ iE ]._adjFaceToSmooth )
4749         continue;
4750       for ( size_t iLE = 0; iLE < centerCurves[ iE ]._ledges.size(); ++iLE )
4751       {
4752         if ( centerCurves[ iE ]._ledges[ iLE ]->_cosin > theMinSmoothCosin )
4753         {
4754           adjFacesToSmooth.insert( meshDS->ShapeToIndex( centerCurves[ iE ]._adjFace ));
4755           break;
4756         }
4757       }
4758     }
4759     data.AddShapesToSmooth( adjFacesToSmooth );
4760
4761     dumpFunctionEnd();
4762
4763
4764   } // loop on data._convexFaces
4765
4766   return true;
4767 }
4768
4769 //================================================================================
4770 /*!
4771  * \brief Finds a center of curvature of a surface at a _LayerEdge
4772  */
4773 //================================================================================
4774
4775 bool _ConvexFace::GetCenterOfCurvature( _LayerEdge*         ledge,
4776                                         BRepLProp_SLProps&  surfProp,
4777                                         SMESH_MesherHelper& helper,
4778                                         gp_Pnt &            center ) const
4779 {
4780   gp_XY uv = helper.GetNodeUV( _face, ledge->_nodes[0] );
4781   surfProp.SetParameters( uv.X(), uv.Y() );
4782   if ( !surfProp.IsCurvatureDefined() )
4783     return false;
4784
4785   const double oriFactor = ( _face.Orientation() == TopAbs_REVERSED ? +1. : -1. );
4786   double surfCurvatureMax = surfProp.MaxCurvature() * oriFactor;
4787   double surfCurvatureMin = surfProp.MinCurvature() * oriFactor;
4788   if ( surfCurvatureMin > surfCurvatureMax )
4789     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMin * oriFactor );
4790   else
4791     center = surfProp.Value().Translated( surfProp.Normal().XYZ() / surfCurvatureMax * oriFactor );
4792
4793   return true;
4794 }
4795
4796 //================================================================================
4797 /*!
4798  * \brief Check that prisms are not distorted
4799  */
4800 //================================================================================
4801
4802 bool _ConvexFace::CheckPrisms() const
4803 {
4804   double vol = 0;
4805   for ( size_t i = 0; i < _simplexTestEdges.size(); ++i )
4806   {
4807     const _LayerEdge* edge = _simplexTestEdges[i];
4808     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
4809     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
4810       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ, vol ))
4811       {
4812         debugMsg( "Bad simplex of _simplexTestEdges ("
4813                   << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
4814                   << " "<< edge->_simplices[j]._nPrev->GetID()
4815                   << " "<< edge->_simplices[j]._nNext->GetID() << " )" );
4816         return false;
4817       }
4818   }
4819   return true;
4820 }
4821
4822 //================================================================================
4823 /*!
4824  * \brief Try to compute a new normal by interpolating normals of _LayerEdge's
4825  *        stored in this _CentralCurveOnEdge.
4826  *  \param [in] center - curvature center of a point of another _CentralCurveOnEdge.
4827  *  \param [in,out] newNormal - current normal at this point, to be redefined
4828  *  \return bool - true if succeeded.
4829  */
4830 //================================================================================
4831
4832 bool _CentralCurveOnEdge::FindNewNormal( const gp_Pnt& center, gp_XYZ& newNormal )
4833 {
4834   if ( this->_isDegenerated )
4835     return false;
4836
4837   // find two centers the given one lies between
4838
4839   for ( size_t i = 0, nb = _curvaCenters.size()-1;  i < nb;  ++i )
4840   {
4841     double sl2 = 1.001 * _segLength2[ i ];
4842
4843     double d1 = center.SquareDistance( _curvaCenters[ i ]);
4844     if ( d1 > sl2 )
4845       continue;
4846     
4847     double d2 = center.SquareDistance( _curvaCenters[ i+1 ]);
4848     if ( d2 > sl2 || d2 + d1 < 1e-100 )
4849       continue;
4850
4851     d1 = Sqrt( d1 );
4852     d2 = Sqrt( d2 );
4853     double r = d1 / ( d1 + d2 );
4854     gp_XYZ norm = (( 1. - r ) * _ledges[ i   ]->_normal +
4855                    (      r ) * _ledges[ i+1 ]->_normal );
4856     norm.Normalize();
4857
4858     newNormal += norm;
4859     double sz = newNormal.Modulus();
4860     if ( sz < 1e-200 )
4861       break;
4862     newNormal /= sz;
4863     return true;
4864   }
4865   return false;
4866 }
4867
4868 //================================================================================
4869 /*!
4870  * \brief Set shape members
4871  */
4872 //================================================================================
4873
4874 void _CentralCurveOnEdge::SetShapes( const TopoDS_Edge&  edge,
4875                                      const _ConvexFace&  convFace,
4876                                      const _SolidData&   data,
4877                                      SMESH_MesherHelper& helper)
4878 {
4879   _edge = edge;
4880
4881   PShapeIteratorPtr fIt = helper.GetAncestors( edge, *helper.GetMesh(), TopAbs_FACE );
4882   while ( const TopoDS_Shape* F = fIt->next())
4883     if ( !convFace._face.IsSame( *F ))
4884     {
4885       _adjFace = TopoDS::Face( *F );
4886       _adjFaceToSmooth = false;
4887       // _adjFace already in a smoothing queue ?
4888       size_t end;
4889       TGeomID adjFaceID = helper.GetMeshDS()->ShapeToIndex( *F );
4890       if ( data.GetShapeEdges( adjFaceID, end ))
4891         _adjFaceToSmooth = ( end < data._nbShapesToSmooth );
4892       break;
4893     }
4894 }
4895
4896 //================================================================================
4897 /*!
4898  * \brief Looks for intersection of it's last segment with faces
4899  *  \param distance - returns shortest distance from the last node to intersection
4900  */
4901 //================================================================================
4902
4903 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
4904                                    double &                 distance,
4905                                    const double&            epsilon,
4906                                    const SMDS_MeshElement** face)
4907 {
4908   vector< const SMDS_MeshElement* > suspectFaces;
4909   double segLen;
4910   gp_Ax1 lastSegment = LastSegment(segLen);
4911   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
4912
4913   bool segmentIntersected = false;
4914   distance = Precision::Infinite();
4915   int iFace = -1; // intersected face
4916   for ( size_t j = 0 ; j < suspectFaces.size() /*&& !segmentIntersected*/; ++j )
4917   {
4918     const SMDS_MeshElement* face = suspectFaces[j];
4919     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
4920          face->GetNodeIndex( _nodes[0]     ) >= 0 )
4921       continue; // face sharing _LayerEdge node
4922     const int nbNodes = face->NbCornerNodes();
4923     bool intFound = false;
4924     double dist;
4925     SMDS_MeshElement::iterator nIt = face->begin_nodes();
4926     if ( nbNodes == 3 )
4927     {
4928       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
4929     }
4930     else
4931     {
4932       const SMDS_MeshNode* tria[3];
4933       tria[0] = *nIt++;
4934       tria[1] = *nIt++;
4935       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
4936       {
4937         tria[2] = *nIt++;
4938         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
4939         tria[1] = tria[2];
4940       }
4941     }
4942     if ( intFound )
4943     {
4944       if ( dist < segLen*(1.01) && dist > -(_len*_lenFactor-segLen) )
4945         segmentIntersected = true;
4946       if ( distance > dist )
4947         distance = dist, iFace = j;
4948     }
4949   }
4950   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
4951
4952   if ( segmentIntersected )
4953   {
4954 #ifdef __myDEBUG
4955     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
4956     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
4957     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
4958          << ", intersection with face ("
4959          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
4960          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
4961          << ") distance = " << distance - segLen<< endl;
4962 #endif
4963   }
4964
4965   distance -= segLen;
4966
4967   return segmentIntersected;
4968 }
4969
4970 //================================================================================
4971 /*!
4972  * \brief Returns size and direction of the last segment
4973  */
4974 //================================================================================
4975
4976 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
4977 {
4978   // find two non-coincident positions
4979   gp_XYZ orig = _pos.back();
4980   gp_XYZ dir;
4981   int iPrev = _pos.size() - 2;
4982   const double tol = ( _len > 0 ) ? 0.3*_len : 1e-100; // adjusted for IPAL52478 + PAL22576
4983   while ( iPrev >= 0 )
4984   {
4985     dir = orig - _pos[iPrev];
4986     if ( dir.SquareModulus() > tol*tol )
4987       break;
4988     else
4989       iPrev--;
4990   }
4991
4992   // make gp_Ax1
4993   gp_Ax1 segDir;
4994   if ( iPrev < 0 )
4995   {
4996     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
4997     segDir.SetDirection( _normal );
4998     segLen = 0;
4999   }
5000   else
5001   {
5002     gp_Pnt pPrev = _pos[ iPrev ];
5003     if ( !_sWOL.IsNull() )
5004     {
5005       TopLoc_Location loc;
5006       if ( _sWOL.ShapeType() == TopAbs_EDGE )
5007       {
5008         double f,l;
5009         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
5010         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
5011       }
5012       else
5013       {
5014         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
5015         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
5016       }
5017       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
5018     }
5019     segDir.SetLocation( pPrev );
5020     segDir.SetDirection( dir );
5021     segLen = dir.Modulus();
5022   }
5023
5024   return segDir;
5025 }
5026
5027 //================================================================================
5028 /*!
5029  * \brief Return the last position of the target node on a FACE. 
5030  *  \param [in] F - the FACE this _LayerEdge is inflated along
5031  *  \return gp_XY - result UV
5032  */
5033 //================================================================================
5034
5035 gp_XY _LayerEdge::LastUV( const TopoDS_Face& F ) const
5036 {
5037   if ( F.IsSame( _sWOL )) // F is my FACE
5038     return gp_XY( _pos.back().X(), _pos.back().Y() );
5039
5040   if ( _sWOL.IsNull() || _sWOL.ShapeType() != TopAbs_EDGE ) // wrong call
5041     return gp_XY( 1e100, 1e100 );
5042
5043   // _sWOL is EDGE of F; _pos.back().X() is the last U on the EDGE
5044   double f, l, u = _pos.back().X();
5045   Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge(_sWOL), F, f,l);
5046   if ( !C2d.IsNull() && f <= u && u <= l )
5047     return C2d->Value( u ).XY();
5048
5049   return gp_XY( 1e100, 1e100 );
5050 }
5051
5052 //================================================================================
5053 /*!
5054  * \brief Test intersection of the last segment with a given triangle
5055  *   using Moller-Trumbore algorithm
5056  * Intersection is detected if distance to intersection is less than _LayerEdge._len
5057  */
5058 //================================================================================
5059
5060 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
5061                                const SMDS_MeshNode* n0,
5062                                const SMDS_MeshNode* n1,
5063                                const SMDS_MeshNode* n2,
5064                                double&              t,
5065                                const double&        EPSILON) const
5066 {
5067   //const double EPSILON = 1e-6;
5068
5069   const gp_Pnt& orig = lastSegment.Location();
5070   const gp_Dir& dir  = lastSegment.Direction();
5071
5072   SMESH_TNodeXYZ vert0( n0 );
5073   SMESH_TNodeXYZ vert1( n1 );
5074   SMESH_TNodeXYZ vert2( n2 );
5075
5076   /* calculate distance from vert0 to ray origin */
5077   gp_XYZ tvec = orig.XYZ() - vert0;
5078
5079   //if ( tvec * dir > EPSILON )
5080     // intersected face is at back side of the temporary face this _LayerEdge belongs to
5081     //return false;
5082
5083   gp_XYZ edge1 = vert1 - vert0;
5084   gp_XYZ edge2 = vert2 - vert0;
5085
5086   /* begin calculating determinant - also used to calculate U parameter */
5087   gp_XYZ pvec = dir.XYZ() ^ edge2;
5088
5089   /* if determinant is near zero, ray lies in plane of triangle */
5090   double det = edge1 * pvec;
5091
5092   if (det > -EPSILON && det < EPSILON)
5093     return false;
5094
5095   /* calculate U parameter and test bounds */
5096   double u = ( tvec * pvec ) / det;
5097   //if (u < 0.0 || u > 1.0)
5098   if (u < -EPSILON || u > 1.0 + EPSILON)
5099     return false;
5100
5101   /* prepare to test V parameter */
5102   gp_XYZ qvec = tvec ^ edge1;
5103
5104   /* calculate V parameter and test bounds */
5105   double v = (dir.XYZ() * qvec) / det;
5106   //if ( v < 0.0 || u + v > 1.0 )
5107   if ( v < -EPSILON || u + v > 1.0 + EPSILON)
5108     return false;
5109
5110   /* calculate t, ray intersects triangle */
5111   t = (edge2 * qvec) / det;
5112
5113   //return true;
5114   return t > 0.;
5115 }
5116
5117 //================================================================================
5118 /*!
5119  * \brief Perform smooth of _LayerEdge's based on EDGE's
5120  *  \retval bool - true if node has been moved
5121  */
5122 //================================================================================
5123
5124 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
5125                               const TopoDS_Face&    F,
5126                               SMESH_MesherHelper&   helper)
5127 {
5128   ASSERT( IsOnEdge() );
5129
5130   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
5131   SMESH_TNodeXYZ oldPos( tgtNode );
5132   double dist01, distNewOld;
5133   
5134   SMESH_TNodeXYZ p0( _2neibors->tgtNode(0));
5135   SMESH_TNodeXYZ p1( _2neibors->tgtNode(1));
5136   dist01 = p0.Distance( _2neibors->tgtNode(1) );
5137
5138   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
5139   double lenDelta = 0;
5140   if ( _curvature )
5141   {
5142     //lenDelta = _curvature->lenDelta( _len );
5143     lenDelta = _curvature->lenDeltaByDist( dist01 );
5144     newPos.ChangeCoord() += _normal * lenDelta;
5145   }
5146
5147   distNewOld = newPos.Distance( oldPos );
5148
5149   if ( F.IsNull() )
5150   {
5151     if ( _2neibors->_plnNorm )
5152     {
5153       // put newPos on the plane defined by source node and _plnNorm
5154       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
5155       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
5156       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
5157     }
5158     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5159     _pos.back() = newPos.XYZ();
5160   }
5161   else
5162   {
5163     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5164     gp_XY uv( Precision::Infinite(), 0 );
5165     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
5166     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5167
5168     newPos = surface->Value( uv.X(), uv.Y() );
5169     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
5170   }
5171
5172   // commented for IPAL0052478
5173   // if ( _curvature && lenDelta < 0 )
5174   // {
5175   //   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
5176   //   _len -= prevPos.Distance( oldPos );
5177   //   _len += prevPos.Distance( newPos );
5178   // }
5179   bool moved = distNewOld > dist01/50;
5180   //if ( moved )
5181   dumpMove( tgtNode ); // debug
5182
5183   return moved;
5184 }
5185
5186 //================================================================================
5187 /*!
5188  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
5189  *  \retval bool - true if _tgtNode has been moved
5190  */
5191 //================================================================================
5192
5193 bool _LayerEdge::Smooth(int& badNb, const int step, const bool isConcaveFace )
5194 {
5195   bool moved = false;
5196   if ( _simplices.size() < 2 )
5197     return moved; // _LayerEdge inflated along EDGE or FACE
5198
5199   const gp_XYZ& curPos ( _pos.back() );
5200   const gp_XYZ& prevPos( _pos[ _pos.size()-2 ]);
5201
5202   // quality metrics (orientation) of tetras around _tgtNode
5203   int nbOkBefore = 0;
5204   double vol, minVolBefore = 1e100;
5205   for ( size_t i = 0; i < _simplices.size(); ++i )
5206   {
5207     nbOkBefore += _simplices[i].IsForward( _nodes[0], &curPos, vol );
5208     minVolBefore = Min( minVolBefore, vol );
5209   }
5210   int nbBad = _simplices.size() - nbOkBefore;
5211
5212   // compute new position for the last _pos using different _funs
5213   gp_XYZ newPos, bestNewPos;
5214   for ( int iFun = -1; iFun < theNbSmooFuns; ++iFun )
5215   {
5216     if ( iFun < 0 )
5217       newPos = (this->*_smooFunction)(); // fun chosen by ChooseSmooFunction()
5218     else if ( _funs[ iFun ] == _smooFunction )
5219       continue; // _smooFunction again
5220     else if ( step > 0 )
5221       newPos = (this->*_funs[ iFun ])(); // try other smoothing fun
5222     else
5223       break; // let "easy" functions improve elements around distorted ones
5224
5225     if ( _curvature )
5226     {
5227       double delta  = _curvature->lenDelta( _len );
5228       if ( delta > 0 )
5229         newPos += _normal * delta;
5230       else
5231       {
5232         double segLen = _normal * ( newPos - prevPos );
5233         if ( segLen + delta > 0 )
5234           newPos += _normal * delta;
5235       }
5236       // double segLenChange = _normal * ( curPos - newPos );
5237       // newPos += 0.5 * _normal * segLenChange;
5238     }
5239
5240     int nbOkAfter = 0;
5241     double minVolAfter = 1e100;
5242     for ( size_t i = 0; i < _simplices.size(); ++i )
5243     {
5244       nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos, vol );
5245       minVolAfter = Min( minVolAfter, vol );
5246     }
5247     // get worse?
5248     if ( nbOkAfter < nbOkBefore )
5249       continue;
5250     if (( isConcaveFace ) &&
5251         ( nbOkAfter == nbOkBefore ) &&
5252         //( iFun > -1 || nbOkAfter < _simplices.size() ) &&
5253         ( minVolAfter <= minVolBefore ))
5254       continue;
5255
5256     SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
5257
5258     // commented for IPAL0052478
5259     // _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
5260     // _len += prevPos.Distance(newPos);
5261
5262     n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
5263     _pos.back() = newPos;
5264     moved = true;
5265     dumpMoveComm( n, _funNames[ iFun < 0 ? smooFunID() : iFun ]);
5266
5267     nbBad = _simplices.size() - nbOkAfter;
5268
5269     if ( iFun > -1 )
5270     {
5271       //_smooFunction = _funs[ iFun ];
5272       // cout << "# " << _funNames[ iFun ] << "\t N:" << _nodes.back()->GetID()
5273       // << "\t nbBad: " << _simplices.size() - nbOkAfter
5274       // << " minVol: " << minVolAfter
5275       // << " " << newPos.X() << " " << newPos.Y() << " " << newPos.Z()
5276       // << endl;
5277       minVolBefore = minVolAfter;
5278       nbOkBefore = nbOkAfter;
5279       continue; // look for a better function
5280     }
5281
5282     break;
5283
5284   } // loop on smoothing functions
5285
5286   badNb += nbBad;
5287   return moved;
5288 }
5289
5290 //================================================================================
5291 /*!
5292  * \brief Chooses a smoothing technic giving a position most close to an initial one.
5293  *        For a correct result, _simplices must contain nodes lying on geometry.
5294  */
5295 //================================================================================
5296
5297 void _LayerEdge::ChooseSmooFunction( const set< TGeomID >& concaveVertices,
5298                                      const TNode2Edge&     n2eMap)
5299 {
5300   if ( _smooFunction ) return;
5301
5302   // use smoothNefPolygon() near concaveVertices
5303   if ( !concaveVertices.empty() )
5304   {
5305     for ( size_t i = 0; i < _simplices.size(); ++i )
5306     {
5307       if ( concaveVertices.count( _simplices[i]._nPrev->getshapeId() ))
5308       {
5309         _smooFunction = _funs[ FUN_NEFPOLY ];
5310
5311         // set FUN_CENTROIDAL to neighbor edges
5312         TNode2Edge::const_iterator n2e;
5313         for ( i = 0; i < _simplices.size(); ++i )
5314         {
5315           if (( _simplices[i]._nPrev->GetPosition()->GetDim() == 2 ) &&
5316               (( n2e = n2eMap.find( _simplices[i]._nPrev )) != n2eMap.end() ))
5317           {
5318             n2e->second->_smooFunction = _funs[ FUN_CENTROIDAL ];
5319           }
5320         }
5321         return;
5322       }
5323     }
5324     //}
5325
5326     // this coice is done only if ( !concaveVertices.empty() ) for Grids/smesh/bugs_19/X1
5327     // where the nodes are smoothed too far along a sphere thus creating
5328     // inverted _simplices
5329     double dist[theNbSmooFuns];
5330     //double coef[theNbSmooFuns] = { 1., 1.2, 1.4, 1.4 };
5331     double coef[theNbSmooFuns] = { 1., 1., 1., 1. };
5332
5333     double minDist = Precision::Infinite();
5334     gp_Pnt p = SMESH_TNodeXYZ( _nodes[0] );
5335     for ( int i = 0; i < FUN_NEFPOLY; ++i )
5336     {
5337       gp_Pnt newP = (this->*_funs[i])();
5338       dist[i] = p.SquareDistance( newP );
5339       if ( dist[i]*coef[i] < minDist )
5340       {
5341         _smooFunction = _funs[i];
5342         minDist = dist[i]*coef[i];
5343       }
5344     }
5345   }
5346   else
5347   {
5348     _smooFunction = _funs[ FUN_LAPLACIAN ];
5349   }
5350   // int minDim = 3;
5351   // for ( size_t i = 0; i < _simplices.size(); ++i )
5352   //   minDim = Min( minDim, _simplices[i]._nPrev->GetPosition()->GetDim() );
5353   // if ( minDim == 0 )
5354   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
5355   // else if ( minDim == 1 )
5356   //   _smooFunction = _funs[ FUN_CENTROIDAL ];
5357
5358
5359   // int iMin;
5360   // for ( int i = 0; i < FUN_NB; ++i )
5361   // {
5362   //   //cout << dist[i] << " ";
5363   //   if ( _smooFunction == _funs[i] ) {
5364   //     iMin = i;
5365   //     //debugMsg( fNames[i] );
5366   //     break;
5367   //   }
5368   // }
5369   // cout << _funNames[ iMin ] << "\t N:" << _nodes.back()->GetID() << endl;
5370 }
5371
5372 //================================================================================
5373 /*!
5374  * \brief Returns a name of _SmooFunction
5375  */
5376 //================================================================================
5377
5378 int _LayerEdge::smooFunID( _LayerEdge::PSmooFun fun) const
5379 {
5380   if ( !fun )
5381     fun = _smooFunction;
5382   for ( int i = 0; i < theNbSmooFuns; ++i )
5383     if ( fun == _funs[i] )
5384       return i;
5385
5386   return theNbSmooFuns;
5387 }
5388
5389 //================================================================================
5390 /*!
5391  * \brief Computes a new node position using Laplacian smoothing
5392  */
5393 //================================================================================
5394
5395 gp_XYZ _LayerEdge::smoothLaplacian()
5396 {
5397   gp_XYZ newPos (0,0,0);
5398   for ( size_t i = 0; i < _simplices.size(); ++i )
5399     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5400   newPos /= _simplices.size();
5401
5402   return newPos;
5403 }
5404
5405 //================================================================================
5406 /*!
5407  * \brief Computes a new node position using angular-based smoothing
5408  */
5409 //================================================================================
5410
5411 gp_XYZ _LayerEdge::smoothAngular()
5412 {
5413   vector< gp_Vec > edgeDir;  edgeDir. reserve( _simplices.size() + 1);
5414   vector< double > edgeSize; edgeSize.reserve( _simplices.size() );
5415   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
5416
5417   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5418   gp_XYZ pN( 0,0,0 );
5419   for ( size_t i = 0; i < _simplices.size(); ++i )
5420   {
5421     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5422     edgeDir.push_back( p - pPrev );
5423     edgeSize.push_back( edgeDir.back().Magnitude() );
5424     //double edgeSize = edgeDir.back().Magnitude();
5425     if ( edgeSize.back() < numeric_limits<double>::min() )
5426     {
5427       edgeDir.pop_back();
5428       edgeSize.pop_back();
5429     }
5430     else
5431     {
5432       edgeDir.back() /= edgeSize.back();
5433       points.push_back( p );
5434       pN += p;
5435     }
5436     pPrev = p;
5437   }
5438   edgeDir.push_back ( edgeDir[0] );
5439   edgeSize.push_back( edgeSize[0] );
5440   pN /= points.size();
5441
5442   gp_XYZ newPos(0,0,0);
5443   //gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5444   double sumSize = 0;
5445   for ( size_t i = 0; i < points.size(); ++i )
5446   {
5447     gp_Vec toN( pN - points[i]);
5448     double toNLen = toN.Magnitude();
5449     if ( toNLen < numeric_limits<double>::min() )
5450     {
5451       newPos += pN;
5452       continue;
5453     }
5454     gp_Vec bisec = edgeDir[i] + edgeDir[i+1];
5455     double bisecLen = bisec.SquareMagnitude();
5456     if ( bisecLen < numeric_limits<double>::min() )
5457     {
5458       gp_Vec norm = edgeDir[i] ^ toN;
5459       bisec = norm ^ edgeDir[i];
5460       bisecLen = bisec.SquareMagnitude();
5461     }
5462     bisecLen = Sqrt( bisecLen );
5463     bisec /= bisecLen;
5464
5465 #if 1
5466     //bisecLen = 1.;
5467     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * bisecLen;
5468     sumSize += bisecLen;
5469 #else
5470     gp_XYZ pNew = ( points[i] + bisec.XYZ() * toNLen ) * ( edgeSize[i] + edgeSize[i+1] );
5471     sumSize += ( edgeSize[i] + edgeSize[i+1] );
5472 #endif
5473     newPos += pNew;
5474   }
5475   newPos /= sumSize;
5476
5477   return newPos;
5478 }
5479
5480 //================================================================================
5481 /*!
5482  * \brief Computes a new node position using weigthed node positions
5483  */
5484 //================================================================================
5485
5486 gp_XYZ _LayerEdge::smoothLengthWeighted()
5487 {
5488   vector< double > edgeSize; edgeSize.reserve( _simplices.size() + 1);
5489   vector< gp_XYZ > points;   points.  reserve( _simplices.size() );
5490
5491   gp_XYZ pPrev = SMESH_TNodeXYZ( _simplices.back()._nPrev );
5492   for ( size_t i = 0; i < _simplices.size(); ++i )
5493   {
5494     gp_XYZ p = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5495     edgeSize.push_back( ( p - pPrev ).Modulus() );
5496     if ( edgeSize.back() < numeric_limits<double>::min() )
5497     {
5498       edgeSize.pop_back();
5499     }
5500     else
5501     {
5502       points.push_back( p );
5503     }
5504     pPrev = p;
5505   }
5506   edgeSize.push_back( edgeSize[0] );
5507
5508   gp_XYZ newPos(0,0,0);
5509   double sumSize = 0;
5510   for ( size_t i = 0; i < points.size(); ++i )
5511   {
5512     newPos += points[i] * ( edgeSize[i] + edgeSize[i+1] );
5513     sumSize += edgeSize[i] + edgeSize[i+1];
5514   }
5515   newPos /= sumSize;
5516   return newPos;
5517 }
5518
5519 //================================================================================
5520 /*!
5521  * \brief Computes a new node position using angular-based smoothing
5522  */
5523 //================================================================================
5524
5525 gp_XYZ _LayerEdge::smoothCentroidal()
5526 {
5527   gp_XYZ newPos(0,0,0);
5528   gp_XYZ pN = SMESH_TNodeXYZ( _nodes.back() );
5529   double sumSize = 0;
5530   for ( size_t i = 0; i < _simplices.size(); ++i )
5531   {
5532     gp_XYZ p1 = SMESH_TNodeXYZ( _simplices[i]._nPrev );
5533     gp_XYZ p2 = SMESH_TNodeXYZ( _simplices[i]._nNext );
5534     gp_XYZ gc = ( pN + p1 + p2 ) / 3.;
5535     double size = (( p1 - pN ) ^ ( p2 - pN )).Modulus();
5536
5537     sumSize += size;
5538     newPos += gc * size;
5539   }
5540   newPos /= sumSize;
5541
5542   return newPos;
5543 }
5544
5545 //================================================================================
5546 /*!
5547  * \brief Computes a new node position located inside a Nef polygon
5548  */
5549 //================================================================================
5550
5551 gp_XYZ _LayerEdge::smoothNefPolygon()
5552 {
5553   gp_XYZ newPos(0,0,0);
5554
5555   // get a plane to seach a solution on
5556
5557   vector< gp_XYZ > vecs( _simplices.size() + 1 );
5558   size_t i;
5559   const double tol = numeric_limits<double>::min();
5560   gp_XYZ center(0,0,0);
5561   for ( i = 0; i < _simplices.size(); ++i )
5562   {
5563     vecs[i] = ( SMESH_TNodeXYZ( _simplices[i]._nNext ) -
5564                 SMESH_TNodeXYZ( _simplices[i]._nPrev ));
5565     center += SMESH_TNodeXYZ( _simplices[i]._nPrev );
5566   }
5567   vecs.back() = vecs[0];
5568   center /= _simplices.size();
5569
5570   gp_XYZ zAxis(0,0,0);
5571   for ( i = 0; i < _simplices.size(); ++i )
5572     zAxis += vecs[i] ^ vecs[i+1];
5573
5574   gp_XYZ yAxis;
5575   for ( i = 0; i < _simplices.size(); ++i )
5576   {
5577     yAxis = vecs[i];
5578     if ( yAxis.SquareModulus() > tol )
5579       break;
5580   }
5581   gp_XYZ xAxis = yAxis ^ zAxis;
5582   // SMESH_TNodeXYZ p0( _simplices[0]._nPrev );
5583   // const double tol = 1e-6 * ( p0.Distance( _simplices[1]._nPrev ) +
5584   //                             p0.Distance( _simplices[2]._nPrev ));
5585   // gp_XYZ center = smoothLaplacian();
5586   // gp_XYZ xAxis, yAxis, zAxis;
5587   // for ( i = 0; i < _simplices.size(); ++i )
5588   // {
5589   //   xAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5590   //   if ( xAxis.SquareModulus() > tol*tol )
5591   //     break;
5592   // }
5593   // for ( i = 1; i < _simplices.size(); ++i )
5594   // {
5595   //   yAxis = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5596   //   zAxis = xAxis ^ yAxis;
5597   //   if ( zAxis.SquareModulus() > tol*tol )
5598   //     break;
5599   // }
5600   // if ( i == _simplices.size() ) return newPos;
5601
5602   yAxis = zAxis ^ xAxis;
5603   xAxis /= xAxis.Modulus();
5604   yAxis /= yAxis.Modulus();
5605
5606   // get half-planes of _simplices
5607
5608   vector< _halfPlane > halfPlns( _simplices.size() );
5609   int nbHP = 0;
5610   for ( size_t i = 0; i < _simplices.size(); ++i )
5611   {
5612     gp_XYZ OP1 = SMESH_TNodeXYZ( _simplices[i]._nPrev ) - center;
5613     gp_XYZ OP2 = SMESH_TNodeXYZ( _simplices[i]._nNext ) - center;
5614     gp_XY  p1( OP1 * xAxis, OP1 * yAxis );
5615     gp_XY  p2( OP2 * xAxis, OP2 * yAxis );
5616     gp_XY  vec12 = p2 - p1;
5617     double dist12 = vec12.Modulus();
5618     if ( dist12 < tol )
5619       continue;
5620     vec12 /= dist12;
5621     halfPlns[ nbHP ]._pos = p1;
5622     halfPlns[ nbHP ]._dir = vec12;
5623     halfPlns[ nbHP ]._inNorm.SetCoord( -vec12.Y(), vec12.X() );
5624     ++nbHP;
5625   }
5626
5627   // intersect boundaries of half-planes, define state of intersection points
5628   // in relation to all half-planes and calculate internal point of a 2D polygon
5629
5630   double sumLen = 0;
5631   gp_XY newPos2D (0,0);
5632
5633   enum { UNDEF = -1, NOT_OUT, IS_OUT, NO_INT };
5634   typedef std::pair< gp_XY, int > TIntPntState; // coord and isOut state
5635   TIntPntState undefIPS( gp_XY(1e100,1e100), UNDEF );
5636
5637   vector< vector< TIntPntState > > allIntPnts( nbHP );
5638   for ( int iHP1 = 0; iHP1 < nbHP; ++iHP1 )
5639   {
5640     vector< TIntPntState > & intPnts1 = allIntPnts[ iHP1 ];
5641     if ( intPnts1.empty() ) intPnts1.resize( nbHP, undefIPS );
5642
5643     int iPrev = SMESH_MesherHelper::WrapIndex( iHP1 - 1, nbHP );
5644     int iNext = SMESH_MesherHelper::WrapIndex( iHP1 + 1, nbHP );
5645
5646     int nbNotOut = 0;
5647     const gp_XY* segEnds[2] = { 0, 0 }; // NOT_OUT points
5648
5649     for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5650     {
5651       if ( iHP1 == iHP2 ) continue;
5652
5653       TIntPntState & ips1 = intPnts1[ iHP2 ];
5654       if ( ips1.second == UNDEF )
5655       {
5656         // find an intersection point of boundaries of iHP1 and iHP2
5657
5658         if ( iHP2 == iPrev ) // intersection with neighbors is known
5659           ips1.first = halfPlns[ iHP1 ]._pos;
5660         else if ( iHP2 == iNext )
5661           ips1.first = halfPlns[ iHP2 ]._pos;
5662         else if ( !halfPlns[ iHP1 ].FindInterestion( halfPlns[ iHP2 ], ips1.first ))
5663           ips1.second = NO_INT;
5664
5665         // classify the found intersection point
5666         if ( ips1.second != NO_INT )
5667         {
5668           ips1.second = NOT_OUT;
5669           for ( int i = 0; i < nbHP && ips1.second == NOT_OUT; ++i )
5670             if ( i != iHP1 && i != iHP2 &&
5671                  halfPlns[ i ].IsOut( ips1.first, tol ))
5672               ips1.second = IS_OUT;
5673         }
5674         vector< TIntPntState > & intPnts2 = allIntPnts[ iHP2 ];
5675         if ( intPnts2.empty() ) intPnts2.resize( nbHP, undefIPS );
5676         TIntPntState & ips2 = intPnts2[ iHP1 ];
5677         ips2 = ips1;
5678       }
5679       if ( ips1.second == NOT_OUT )
5680       {
5681         ++nbNotOut;
5682         segEnds[ bool(segEnds[0]) ] = & ips1.first;
5683       }
5684     }
5685
5686     // find a NOT_OUT segment of boundary which is located between
5687     // two NOT_OUT int points
5688
5689     if ( nbNotOut < 2 )
5690       continue; // no such a segment
5691
5692     if ( nbNotOut > 2 )
5693     {
5694       // sort points along the boundary
5695       map< double, TIntPntState* > ipsByParam;
5696       for ( int iHP2 = 0; iHP2 < nbHP; ++iHP2 )
5697       {
5698         TIntPntState & ips1 = intPnts1[ iHP2 ];
5699         if ( ips1.second != NO_INT )
5700         {
5701           gp_XY     op = ips1.first - halfPlns[ iHP1 ]._pos;
5702           double param = op * halfPlns[ iHP1 ]._dir;
5703           ipsByParam.insert( make_pair( param, & ips1 ));
5704         }
5705       }
5706       // look for two neighboring NOT_OUT points
5707       nbNotOut = 0;
5708       map< double, TIntPntState* >::iterator u2ips = ipsByParam.begin();
5709       for ( ; u2ips != ipsByParam.end(); ++u2ips )
5710       {
5711         TIntPntState & ips1 = *(u2ips->second);
5712         if ( ips1.second == NOT_OUT )
5713           segEnds[ bool( nbNotOut++ ) ] = & ips1.first;
5714         else if ( nbNotOut >= 2 )
5715           break;
5716         else
5717           nbNotOut = 0;
5718       }
5719     }
5720
5721     if ( nbNotOut >= 2 )
5722     {
5723       double len = ( *segEnds[0] - *segEnds[1] ).Modulus();
5724       sumLen += len;
5725
5726       newPos2D += 0.5 * len * ( *segEnds[0] + *segEnds[1] );
5727     }
5728   }
5729
5730   if ( sumLen > 0 )
5731   {
5732     newPos2D /= sumLen;
5733     newPos = center + xAxis * newPos2D.X() + yAxis * newPos2D.Y();
5734   }
5735   else
5736   {
5737     newPos = center;
5738   }
5739
5740   return newPos;
5741 }
5742
5743 //================================================================================
5744 /*!
5745  * \brief Add a new segment to _LayerEdge during inflation
5746  */
5747 //================================================================================
5748
5749 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
5750 {
5751   if ( _len - len > -1e-6 )
5752   {
5753     //_pos.push_back( _pos.back() );
5754     return;
5755   }
5756
5757   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
5758   SMESH_TNodeXYZ oldXYZ( n );
5759   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
5760   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
5761
5762   _pos.push_back( nXYZ );
5763   _len = len;
5764   if ( !_sWOL.IsNull() )
5765   {
5766     double distXYZ[4];
5767     if ( _sWOL.ShapeType() == TopAbs_EDGE )
5768     {
5769       double u = Precision::Infinite(); // to force projection w/o distance check
5770       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
5771       _pos.back().SetCoord( u, 0, 0 );
5772       if ( _nodes.size() > 1 )
5773       {
5774         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
5775         pos->SetUParameter( u );
5776       }
5777     }
5778     else //  TopAbs_FACE
5779     {
5780       gp_XY uv( Precision::Infinite(), 0 );
5781       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
5782       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
5783       if ( _nodes.size() > 1 )
5784       {
5785         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
5786         pos->SetUParameter( uv.X() );
5787         pos->SetVParameter( uv.Y() );
5788       }
5789     }
5790     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
5791   }
5792   dumpMove( n ); //debug
5793 }
5794
5795 //================================================================================
5796 /*!
5797  * \brief Remove last inflation step
5798  */
5799 //================================================================================
5800
5801 void _LayerEdge::InvalidateStep( int curStep, bool restoreLength )
5802 {
5803   if ( _pos.size() > curStep )
5804   {
5805     if ( restoreLength )
5806       _len -= ( _pos[ curStep-1 ] - _pos.back() ).Modulus();
5807
5808     _pos.resize( curStep );
5809     gp_Pnt nXYZ = _pos.back();
5810     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
5811     if ( !_sWOL.IsNull() )
5812     {
5813       TopLoc_Location loc;
5814       if ( _sWOL.ShapeType() == TopAbs_EDGE )
5815       {
5816         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
5817         pos->SetUParameter( nXYZ.X() );
5818         double f,l;
5819         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
5820         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
5821       }
5822       else
5823       {
5824         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
5825         pos->SetUParameter( nXYZ.X() );
5826         pos->SetVParameter( nXYZ.Y() );
5827         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
5828         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
5829       }
5830     }
5831     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
5832     dumpMove( n );
5833   }
5834 }
5835
5836 //================================================================================
5837 /*!
5838  * \brief Create layers of prisms
5839  */
5840 //================================================================================
5841
5842 bool _ViscousBuilder::refine(_SolidData& data)
5843 {
5844   SMESH_MesherHelper helper( *_mesh );
5845   helper.SetSubShape( data._solid );
5846   helper.SetElementsOnShape(false);
5847
5848   Handle(Geom_Curve) curve;
5849   Handle(Geom_Surface) surface;
5850   TopoDS_Edge geomEdge;
5851   TopoDS_Face geomFace;
5852   TopoDS_Shape prevSWOL;
5853   TopLoc_Location loc;
5854   double f,l, u;
5855   gp_XY uv;
5856   bool isOnEdge;
5857   TGeomID prevBaseId = -1;
5858   TNode2Edge* n2eMap = 0;
5859   TNode2Edge::iterator n2e;
5860
5861   // Create intermediate nodes on each _LayerEdge
5862
5863   int iS = 0, iEnd = data._endEdgeOnShape[ iS ];
5864
5865   for ( size_t i = 0; i < data._edges.size(); ++i )
5866   {
5867     _LayerEdge& edge = *data._edges[i];
5868
5869     if ( edge._nodes.size() < 2 )
5870       continue; // on _noShrinkShapes
5871
5872     // get parameters of layers for the edge
5873     if ( i == iEnd )
5874       iEnd = data._endEdgeOnShape[ ++iS ];
5875     const AverageHyp& hyp = data._hypOnShape[ iS ];
5876
5877     // get accumulated length of segments
5878     vector< double > segLen( edge._pos.size() );
5879     segLen[0] = 0.0;
5880     for ( size_t j = 1; j < edge._pos.size(); ++j )
5881       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
5882
5883     // allocate memory for new nodes if it is not yet refined
5884     const SMDS_MeshNode* tgtNode = edge._nodes.back();
5885     if ( edge._nodes.size() == 2 )
5886     {
5887       edge._nodes.resize( hyp.GetNumberLayers() + 1, 0 );
5888       edge._nodes[1] = 0;
5889       edge._nodes.back() = tgtNode;
5890     }
5891     // get data of a shrink shape
5892     if ( !edge._sWOL.IsNull() && edge._sWOL != prevSWOL )
5893     {
5894       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
5895       if ( isOnEdge )
5896       {
5897         geomEdge = TopoDS::Edge( edge._sWOL );
5898         curve    = BRep_Tool::Curve( geomEdge, loc, f,l);
5899       }
5900       else
5901       {
5902         geomFace = TopoDS::Face( edge._sWOL );
5903         surface  = BRep_Tool::Surface( geomFace, loc );
5904       }
5905       prevSWOL = edge._sWOL;
5906     }
5907     // restore shapePos of the last node by already treated _LayerEdge of another _SolidData
5908     const TGeomID baseShapeId = edge._nodes[0]->getshapeId();
5909     if ( baseShapeId != prevBaseId )
5910     {
5911       map< TGeomID, TNode2Edge* >::iterator s2ne = data._s2neMap.find( baseShapeId );
5912       n2eMap = ( s2ne == data._s2neMap.end() ) ? 0 : n2eMap = s2ne->second;
5913       prevBaseId = baseShapeId;
5914     }
5915     _LayerEdge* edgeOnSameNode = 0;
5916     if ( n2eMap && (( n2e = n2eMap->find( edge._nodes[0] )) != n2eMap->end() ))
5917     {
5918       edgeOnSameNode = n2e->second;
5919       const gp_XYZ& otherTgtPos = edgeOnSameNode->_pos.back();
5920       SMDS_PositionPtr  lastPos = tgtNode->GetPosition();
5921       if ( isOnEdge )
5922       {
5923         SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( lastPos );
5924         epos->SetUParameter( otherTgtPos.X() );
5925       }
5926       else
5927       {
5928         SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( lastPos );
5929         fpos->SetUParameter( otherTgtPos.X() );
5930         fpos->SetVParameter( otherTgtPos.Y() );
5931       }
5932     }
5933     // calculate height of the first layer
5934     double h0;
5935     const double T = segLen.back(); //data._hyp.GetTotalThickness();
5936     const double f = hyp.GetStretchFactor();
5937     const int    N = hyp.GetNumberLayers();
5938     const double fPowN = pow( f, N );
5939     if ( fPowN - 1 <= numeric_limits<double>::min() )
5940       h0 = T / N;
5941     else
5942       h0 = T * ( f - 1 )/( fPowN - 1 );
5943
5944     const double zeroLen = std::numeric_limits<double>::min();
5945
5946     // create intermediate nodes
5947     double hSum = 0, hi = h0/f;
5948     size_t iSeg = 1;
5949     for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
5950     {
5951       // compute an intermediate position
5952       hi *= f;
5953       hSum += hi;
5954       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
5955         ++iSeg;
5956       int iPrevSeg = iSeg-1;
5957       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
5958         --iPrevSeg;
5959       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
5960       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
5961
5962       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >( edge._nodes[ iStep ]);
5963       if ( !edge._sWOL.IsNull() )
5964       {
5965         // compute XYZ by parameters <pos>
5966         if ( isOnEdge )
5967         {
5968           u = pos.X();
5969           if ( !node )
5970             pos = curve->Value( u ).Transformed(loc);
5971         }
5972         else
5973         {
5974           uv.SetCoord( pos.X(), pos.Y() );
5975           if ( !node )
5976             pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
5977         }
5978       }
5979       // create or update the node
5980       if ( !node )
5981       {
5982         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
5983         if ( !edge._sWOL.IsNull() )
5984         {
5985           if ( isOnEdge )
5986             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
5987           else
5988             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
5989         }
5990         else
5991         {
5992           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
5993         }
5994       }
5995       else
5996       {
5997         if ( !edge._sWOL.IsNull() )
5998         {
5999           // make average pos from new and current parameters
6000           if ( isOnEdge )
6001           {
6002             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
6003             pos = curve->Value( u ).Transformed(loc);
6004
6005             SMDS_EdgePosition* epos = static_cast<SMDS_EdgePosition*>( node->GetPosition() );
6006             epos->SetUParameter( u );
6007           }
6008           else
6009           {
6010             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
6011             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
6012
6013             SMDS_FacePosition* fpos = static_cast<SMDS_FacePosition*>( node->GetPosition() );
6014             fpos->SetUParameter( uv.X() );
6015             fpos->SetVParameter( uv.Y() );
6016           }
6017         }
6018         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
6019       }
6020     } // loop on edge._nodes
6021
6022     if ( !edge._sWOL.IsNull() ) // prepare for shrink()
6023     {
6024       if ( isOnEdge )
6025         edge._pos.back().SetCoord( u, 0,0);
6026       else
6027         edge._pos.back().SetCoord( uv.X(), uv.Y() ,0);
6028
6029       if ( edgeOnSameNode )
6030         edgeOnSameNode->_pos.back() = edge._pos.back();
6031     }
6032
6033   } // loop on data._edges to create nodes
6034
6035   if ( !getMeshDS()->IsEmbeddedMode() )
6036     // Log node movement
6037     for ( size_t i = 0; i < data._edges.size(); ++i )
6038     {
6039       _LayerEdge& edge = *data._edges[i];
6040       SMESH_TNodeXYZ p ( edge._nodes.back() );
6041       getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
6042     }
6043
6044   // Create volumes
6045
6046   helper.SetElementsOnShape(true);
6047
6048   vector< vector<const SMDS_MeshNode*>* > nnVec;
6049   set< vector<const SMDS_MeshNode*>* >    nnSet;
6050   set< int > degenEdgeInd;
6051   vector<const SMDS_MeshElement*> degenVols;
6052
6053   TopExp_Explorer exp( data._solid, TopAbs_FACE );
6054   for ( ; exp.More(); exp.Next() )
6055   {
6056     const TGeomID faceID = getMeshDS()->ShapeToIndex( exp.Current() );
6057     if ( data._ignoreFaceIds.count( faceID ))
6058       continue;
6059     const bool isReversedFace = data._reversedFaceIds.count( faceID );
6060     SMESHDS_SubMesh*    fSubM = getMeshDS()->MeshElements( exp.Current() );
6061     SMDS_ElemIteratorPtr  fIt = fSubM->GetElements();
6062     while ( fIt->more() )
6063     {
6064       const SMDS_MeshElement* face = fIt->next();
6065       const int            nbNodes = face->NbCornerNodes();
6066       nnVec.resize( nbNodes );
6067       nnSet.clear();
6068       degenEdgeInd.clear();
6069       int nbZ = 0;
6070       SMDS_NodeIteratorPtr nIt = face->nodeIterator();
6071       for ( int iN = 0; iN < nbNodes; ++iN )
6072       {
6073         const SMDS_MeshNode* n = nIt->next();
6074         const int i = isReversedFace ? nbNodes-1-iN : iN;
6075         nnVec[ i ] = & data._n2eMap[ n ]->_nodes;
6076         if ( nnVec[ i ]->size() < 2 )
6077           degenEdgeInd.insert( iN );
6078         else
6079           nbZ = nnVec[ i ]->size();
6080
6081         if ( helper.HasDegeneratedEdges() )
6082           nnSet.insert( nnVec[ i ]);
6083       }
6084       if ( nbZ == 0 )
6085         continue;
6086       if ( 0 < nnSet.size() && nnSet.size() < 3 )
6087         continue;
6088
6089       switch ( nbNodes )
6090       {
6091       case 3:
6092         switch ( degenEdgeInd.size() )
6093         {
6094         case 0: // PENTA
6095         {
6096           for ( int iZ = 1; iZ < nbZ; ++iZ )
6097             helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6098                               (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
6099           break;
6100         }
6101         case 1: // PYRAM
6102         {
6103           int i2 = *degenEdgeInd.begin();
6104           int i0 = helper.WrapIndex( i2 - 1, nbNodes );
6105           int i1 = helper.WrapIndex( i2 + 1, nbNodes );
6106           for ( int iZ = 1; iZ < nbZ; ++iZ )
6107             helper.AddVolume( (*nnVec[i0])[iZ-1], (*nnVec[i1])[iZ-1],
6108                               (*nnVec[i1])[iZ],   (*nnVec[i0])[iZ],   (*nnVec[i2])[0]);
6109           break;
6110         }
6111         case 2: // TETRA
6112         {
6113           int i3 = !degenEdgeInd.count(0) ? 0 : !degenEdgeInd.count(1) ? 1 : 2;
6114           for ( int iZ = 1; iZ < nbZ; ++iZ )
6115             helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
6116                               (*nnVec[i3])[iZ]);
6117           break;
6118         }
6119         }
6120         break;
6121
6122       case 4:
6123         switch ( degenEdgeInd.size() )
6124         {
6125         case 0: // HEX
6126         {
6127           for ( int iZ = 1; iZ < nbZ; ++iZ )
6128             helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
6129                               (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
6130                               (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
6131                               (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
6132           break;
6133         }
6134         case 2: // PENTA?
6135         {
6136           int i2 = *degenEdgeInd.begin();
6137           int i3 = *degenEdgeInd.rbegin();
6138           bool ok = ( i3 - i2 == 1 );
6139           if ( i2 == 0 && i3 == 3 ) { i2 = 3; i3 = 0; ok = true; }
6140           int i0 = helper.WrapIndex( i3 + 1, nbNodes );
6141           int i1 = helper.WrapIndex( i0 + 1, nbNodes );
6142           for ( int iZ = 1; iZ < nbZ; ++iZ )
6143           {
6144             const SMDS_MeshElement* vol =
6145               helper.AddVolume( (*nnVec[i3])[0], (*nnVec[i0])[iZ], (*nnVec[i0])[iZ-1],
6146                                 (*nnVec[i2])[0], (*nnVec[i1])[iZ], (*nnVec[i1])[iZ-1]);
6147             if ( !ok && vol )
6148               degenVols.push_back( vol );
6149           }
6150           break;
6151         }
6152         case 3: // degen HEX
6153         {
6154           const SMDS_MeshNode* nn[8];
6155           for ( int iZ = 1; iZ < nbZ; ++iZ )
6156           {
6157             const SMDS_MeshElement* vol =
6158               helper.AddVolume( nnVec[0]->size() > 1 ? (*nnVec[0])[iZ-1] : (*nnVec[0])[0],
6159                                 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ-1] : (*nnVec[1])[0],
6160                                 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ-1] : (*nnVec[2])[0],
6161                                 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ-1] : (*nnVec[3])[0],
6162                                 nnVec[0]->size() > 1 ? (*nnVec[0])[iZ]   : (*nnVec[0])[0],
6163                                 nnVec[1]->size() > 1 ? (*nnVec[1])[iZ]   : (*nnVec[1])[0],
6164                                 nnVec[2]->size() > 1 ? (*nnVec[2])[iZ]   : (*nnVec[2])[0],
6165                                 nnVec[3]->size() > 1 ? (*nnVec[3])[iZ]   : (*nnVec[3])[0]);
6166             degenVols.push_back( vol );
6167           }
6168         }
6169         break;
6170         }
6171         break;
6172
6173       default:
6174         return error("Not supported type of element", data._index);
6175
6176       } // switch ( nbNodes )
6177     } // while ( fIt->more() )
6178   } // loop on FACEs
6179
6180   if ( !degenVols.empty() )
6181   {
6182     SMESH_ComputeErrorPtr& err = _mesh->GetSubMesh( data._solid )->GetComputeError();
6183     if ( !err || err->IsOK() )
6184     {
6185       err.reset( new SMESH_ComputeError( COMPERR_WARNING,
6186                                          "Degenerated volumes created" ));
6187       err->myBadElements.insert( err->myBadElements.end(),
6188                                  degenVols.begin(),degenVols.end() );
6189     }
6190   }
6191
6192   return true;
6193 }
6194
6195 //================================================================================
6196 /*!
6197  * \brief Shrink 2D mesh on faces to let space for inflated layers
6198  */
6199 //================================================================================
6200
6201 bool _ViscousBuilder::shrink()
6202 {
6203   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
6204   // inflated along FACE or EDGE)
6205   map< TGeomID, _SolidData* > f2sdMap;
6206   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
6207   {
6208     _SolidData& data = _sdVec[i];
6209     TopTools_MapOfShape FFMap;
6210     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
6211     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
6212       if ( s2s->second.ShapeType() == TopAbs_FACE )
6213       {
6214         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
6215
6216         if ( FFMap.Add( (*s2s).second ))
6217           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
6218           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
6219           // by StdMeshers_QuadToTriaAdaptor
6220           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
6221           {
6222             SMESH_ProxyMesh::SubMesh* proxySub =
6223               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
6224             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6225             while ( fIt->more() )
6226               proxySub->AddElement( fIt->next() );
6227             // as a result 3D algo will use elements from proxySub and not from smDS
6228           }
6229       }
6230   }
6231
6232   SMESH_MesherHelper helper( *_mesh );
6233   helper.ToFixNodeParameters( true );
6234
6235   // EDGE's to shrink
6236   map< TGeomID, _Shrinker1D > e2shrMap;
6237   vector< _LayerEdge* > lEdges;
6238
6239   // loop on FACES to srink mesh on
6240   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
6241   for ( ; f2sd != f2sdMap.end(); ++f2sd )
6242   {
6243     _SolidData&      data = *f2sd->second;
6244     const TopoDS_Face&  F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
6245     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
6246     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
6247
6248     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
6249
6250     helper.SetSubShape(F);
6251
6252     // ===========================
6253     // Prepare data for shrinking
6254     // ===========================
6255
6256     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
6257     // and thus all nodes on a FACE connected to 2d elements are to be smoothed
6258     vector < const SMDS_MeshNode* > smoothNodes;
6259     {
6260       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
6261       while ( nIt->more() )
6262       {
6263         const SMDS_MeshNode* n = nIt->next();
6264         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
6265           smoothNodes.push_back( n );
6266       }
6267     }
6268     // Find out face orientation
6269     double refSign = 1;
6270     const set<TGeomID> ignoreShapes;
6271     bool isOkUV;
6272     if ( !smoothNodes.empty() )
6273     {
6274       vector<_Simplex> simplices;
6275       _Simplex::GetSimplices( smoothNodes[0], simplices, ignoreShapes );
6276       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
6277       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
6278       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
6279       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
6280         refSign = -1;
6281     }
6282
6283     // Find _LayerEdge's inflated along F
6284     lEdges.clear();
6285     {
6286       set< TGeomID > subIDs;
6287       SMESH_subMeshIteratorPtr subIt = sm->getDependsOnIterator(/*includeSelf=*/false);
6288       while ( subIt->more() )
6289         subIDs.insert( subIt->next()->GetId() );
6290
6291       int iBeg, iEnd = 0;
6292       for ( int iS = 0; iS < data._endEdgeOnShape.size() && !subIDs.empty(); ++iS )
6293       {
6294         iBeg = iEnd;
6295         iEnd = data._endEdgeOnShape[ iS ];
6296         TGeomID shapeID = data._edges[ iBeg ]->_nodes[0]->getshapeId();
6297         set< TGeomID >::iterator idIt = subIDs.find( shapeID );
6298         if ( idIt == subIDs.end() ||
6299              data._edges[ iBeg ]->_sWOL.IsNull() ) continue;
6300         subIDs.erase( idIt );
6301
6302         if ( !data._noShrinkShapes.count( shapeID ))
6303           for ( ; iBeg < iEnd; ++iBeg )
6304           {
6305             lEdges.push_back( data._edges[ iBeg ] );
6306             prepareEdgeToShrink( *data._edges[ iBeg ], F, helper, smDS );
6307           }
6308       }
6309     }
6310
6311     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
6312     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6313     while ( fIt->more() )
6314       if ( const SMDS_MeshElement* f = fIt->next() )
6315         dumpChangeNodes( f );
6316     dumpFunctionEnd();
6317
6318     // Replace source nodes by target nodes in mesh faces to shrink
6319     dumpFunction(SMESH_Comment("replNodesOnFace")<<f2sd->first); // debug
6320     const SMDS_MeshNode* nodes[20];
6321     for ( size_t i = 0; i < lEdges.size(); ++i )
6322     {
6323       _LayerEdge& edge = *lEdges[i];
6324       const SMDS_MeshNode* srcNode = edge._nodes[0];
6325       const SMDS_MeshNode* tgtNode = edge._nodes.back();
6326       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
6327       while ( fIt->more() )
6328       {
6329         const SMDS_MeshElement* f = fIt->next();
6330         if ( !smDS->Contains( f ))
6331           continue;
6332         SMDS_NodeIteratorPtr nIt = f->nodeIterator();
6333         for ( int iN = 0; nIt->more(); ++iN )
6334         {
6335           const SMDS_MeshNode* n = nIt->next();
6336           nodes[iN] = ( n == srcNode ? tgtNode : n );
6337         }
6338         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
6339         dumpChangeNodes( f );
6340       }
6341     }
6342     dumpFunctionEnd();
6343
6344     // find out if a FACE is concave
6345     const bool isConcaveFace = isConcave( F, helper );
6346
6347     // Create _SmoothNode's on face F
6348     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
6349     {
6350       dumpFunction(SMESH_Comment("fixUVOnFace")<<f2sd->first); // debug
6351       const bool sortSimplices = isConcaveFace;
6352       for ( size_t i = 0; i < smoothNodes.size(); ++i )
6353       {
6354         const SMDS_MeshNode* n = smoothNodes[i];
6355         nodesToSmooth[ i ]._node = n;
6356         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
6357         _Simplex::GetSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, 0, sortSimplices);
6358         // fix up incorrect uv of nodes on the FACE
6359         helper.GetNodeUV( F, n, 0, &isOkUV);
6360         dumpMove( n );
6361       }
6362       dumpFunctionEnd();
6363     }
6364     //if ( nodesToSmooth.empty() ) continue;
6365
6366     // Find EDGE's to shrink and set simpices to LayerEdge's
6367     set< _Shrinker1D* > eShri1D;
6368     {
6369       for ( size_t i = 0; i < lEdges.size(); ++i )
6370       {
6371         _LayerEdge* edge = lEdges[i];
6372         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
6373         {
6374           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
6375           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
6376           eShri1D.insert( & srinker );
6377           srinker.AddEdge( edge, helper );
6378           VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
6379           // restore params of nodes on EGDE if the EDGE has been already
6380           // srinked while srinking another FACE
6381           srinker.RestoreParams();
6382         }
6383         _Simplex::GetSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
6384       }
6385     }
6386
6387     bool toFixTria = false; // to improve quality of trias by diagonal swap
6388     if ( isConcaveFace )
6389     {
6390       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
6391       if ( hasTria != hasQuad ) {
6392         toFixTria = hasTria;
6393       }
6394       else {
6395         set<int> nbNodesSet;
6396         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
6397         while ( fIt->more() && nbNodesSet.size() < 2 )
6398           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
6399         toFixTria = ( *nbNodesSet.begin() == 3 );
6400       }
6401     }
6402
6403     // ==================
6404     // Perform shrinking
6405     // ==================
6406
6407     bool shrinked = true;
6408     int badNb, shriStep=0, smooStep=0;
6409     _SmoothNode::SmoothType smoothType
6410       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
6411     while ( shrinked )
6412     {
6413       shriStep++;
6414       // Move boundary nodes (actually just set new UV)
6415       // -----------------------------------------------
6416       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
6417       shrinked = false;
6418       for ( size_t i = 0; i < lEdges.size(); ++i )
6419       {
6420         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
6421       }
6422       dumpFunctionEnd();
6423
6424       // Move nodes on EDGE's
6425       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
6426       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
6427       for ( ; shr != eShri1D.end(); ++shr )
6428         (*shr)->Compute( /*set3D=*/false, helper );
6429
6430       // Smoothing in 2D
6431       // -----------------
6432       int nbNoImpSteps = 0;
6433       bool       moved = true;
6434       badNb = 1;
6435       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
6436       {
6437         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6438
6439         int oldBadNb = badNb;
6440         badNb = 0;
6441         moved = false;
6442         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6443         {
6444           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6445                                             smoothType, /*set3D=*/isConcaveFace);
6446         }
6447         if ( badNb < oldBadNb )
6448           nbNoImpSteps = 0;
6449         else
6450           nbNoImpSteps++;
6451
6452         dumpFunctionEnd();
6453       }
6454       if ( badNb > 0 )
6455         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
6456       if ( shriStep > 200 )
6457         return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
6458
6459       // Fix narrow triangles by swapping diagonals
6460       // ---------------------------------------
6461       if ( toFixTria )
6462       {
6463         set<const SMDS_MeshNode*> usedNodes;
6464         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
6465
6466         // update working data
6467         set<const SMDS_MeshNode*>::iterator n;
6468         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
6469         {
6470           n = usedNodes.find( nodesToSmooth[ i ]._node );
6471           if ( n != usedNodes.end())
6472           {
6473             _Simplex::GetSimplices( nodesToSmooth[ i ]._node,
6474                                     nodesToSmooth[ i ]._simplices,
6475                                     ignoreShapes, NULL,
6476                                     /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
6477             usedNodes.erase( n );
6478           }
6479         }
6480         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
6481         {
6482           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
6483           if ( n != usedNodes.end())
6484           {
6485             _Simplex::GetSimplices( lEdges[i]->_nodes.back(),
6486                                     lEdges[i]->_simplices,
6487                                     ignoreShapes );
6488             usedNodes.erase( n );
6489           }
6490         }
6491       }
6492       // TODO: check effect of this additional smooth
6493       // additional laplacian smooth to increase allowed shrink step
6494       // for ( int st = 1; st; --st )
6495       // {
6496       //   dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6497       //   for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6498       //   {
6499       //     nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6500       //                              _SmoothNode::LAPLACIAN,/*set3D=*/false);
6501       //   }
6502       // }
6503     } // while ( shrinked )
6504
6505     // No wrongly shaped faces remain; final smooth. Set node XYZ.
6506     bool isStructuredFixed = false;
6507     if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
6508       isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
6509     if ( !isStructuredFixed )
6510     {
6511       if ( isConcaveFace ) // fix narrow faces by swapping diagonals
6512         fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
6513
6514       for ( int st = 3; st; --st )
6515       {
6516         switch( st ) {
6517         case 1: smoothType = _SmoothNode::LAPLACIAN; break;
6518         case 2: smoothType = _SmoothNode::LAPLACIAN; break;
6519         case 3: smoothType = _SmoothNode::ANGULAR; break;
6520         }
6521         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
6522         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6523         {
6524           nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
6525                                    smoothType,/*set3D=*/st==1 );
6526         }
6527         dumpFunctionEnd();
6528       }
6529     }
6530     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
6531     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
6532
6533     if ( !getMeshDS()->IsEmbeddedMode() )
6534       // Log node movement
6535       for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
6536       {
6537         SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
6538         getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
6539       }
6540
6541   } // loop on FACES to srink mesh on
6542
6543
6544   // Replace source nodes by target nodes in shrinked mesh edges
6545
6546   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
6547   for ( ; e2shr != e2shrMap.end(); ++e2shr )
6548     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
6549
6550   return true;
6551 }
6552
6553 //================================================================================
6554 /*!
6555  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
6556  */
6557 //================================================================================
6558
6559 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
6560                                            const TopoDS_Face&     F,
6561                                            SMESH_MesherHelper&    helper,
6562                                            const SMESHDS_SubMesh* faceSubMesh)
6563 {
6564   const SMDS_MeshNode* srcNode = edge._nodes[0];
6565   const SMDS_MeshNode* tgtNode = edge._nodes.back();
6566
6567   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
6568   {
6569     gp_XY srcUV( edge._pos[0].X(), edge._pos[0].Y() );//helper.GetNodeUV( F, srcNode );
6570     gp_XY tgtUV = edge.LastUV( F );                   //helper.GetNodeUV( F, tgtNode );
6571     gp_Vec2d uvDir( srcUV, tgtUV );
6572     double uvLen = uvDir.Magnitude();
6573     uvDir /= uvLen;
6574     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0 );
6575     edge._len = uvLen;
6576
6577     edge._pos.resize(1);
6578     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
6579
6580     // set UV of source node to target node
6581     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
6582     pos->SetUParameter( srcUV.X() );
6583     pos->SetVParameter( srcUV.Y() );
6584   }
6585   else // _sWOL is TopAbs_EDGE
6586   {
6587     const TopoDS_Edge&    E = TopoDS::Edge( edge._sWOL );
6588     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
6589     if ( !edgeSM || edgeSM->NbElements() == 0 )
6590       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6591
6592     const SMDS_MeshNode* n2 = 0;
6593     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
6594     while ( eIt->more() && !n2 )
6595     {
6596       const SMDS_MeshElement* e = eIt->next();
6597       if ( !edgeSM->Contains(e)) continue;
6598       n2 = e->GetNode( 0 );
6599       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
6600     }
6601     if ( !n2 )
6602       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
6603
6604     double uSrc = helper.GetNodeU( E, srcNode, n2 );
6605     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
6606     double u2   = helper.GetNodeU( E, n2, srcNode );
6607
6608     edge._pos.clear();
6609
6610     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
6611     {
6612       // tgtNode is located so that it does not make faces with wrong orientation
6613       return true;
6614     }
6615     edge._pos.resize(1);
6616     edge._pos[0].SetCoord( U_TGT, uTgt );
6617     edge._pos[0].SetCoord( U_SRC, uSrc );
6618     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
6619
6620     edge._simplices.resize( 1 );
6621     edge._simplices[0]._nPrev = n2;
6622
6623     // set U of source node to the target node
6624     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
6625     pos->SetUParameter( uSrc );
6626   }
6627   return true;
6628 }
6629
6630 //================================================================================
6631 /*!
6632  * \brief Restore position of a sole node of a _LayerEdge based on _noShrinkShapes
6633  */
6634 //================================================================================
6635
6636 void _ViscousBuilder::restoreNoShrink( _LayerEdge& edge ) const
6637 {
6638   if ( edge._nodes.size() == 1 )
6639   {
6640     edge._pos.clear();
6641     edge._len = 0;
6642
6643     const SMDS_MeshNode* srcNode = edge._nodes[0];
6644     TopoDS_Shape S = SMESH_MesherHelper::GetSubShapeByNode( srcNode, getMeshDS() );
6645     if ( S.IsNull() ) return;
6646
6647     gp_Pnt p;
6648
6649     switch ( S.ShapeType() )
6650     {
6651     case TopAbs_EDGE:
6652     {
6653       double f,l;
6654       TopLoc_Location loc;
6655       Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( S ), loc, f, l );
6656       if ( curve.IsNull() ) return;
6657       SMDS_EdgePosition* ePos = static_cast<SMDS_EdgePosition*>( srcNode->GetPosition() );
6658       p = curve->Value( ePos->GetUParameter() );
6659       break;
6660     }
6661     case TopAbs_VERTEX:
6662     {
6663       p = BRep_Tool::Pnt( TopoDS::Vertex( S ));
6664       break;
6665     }
6666     default: return;
6667     }
6668     getMeshDS()->MoveNode( srcNode, p.X(), p.Y(), p.Z() );
6669     dumpMove( srcNode );
6670   }
6671 }
6672
6673 //================================================================================
6674 /*!
6675  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
6676  */
6677 //================================================================================
6678
6679 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
6680                                   SMESH_MesherHelper&         helper,
6681                                   const bool                  is2D,
6682                                   const int                   step,
6683                                   set<const SMDS_MeshNode*> * involvedNodes)
6684 {
6685   SMESH::Controls::AspectRatio qualifier;
6686   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
6687   const double maxAspectRatio = is2D ? 4. : 2;
6688   _NodeCoordHelper xyz( F, helper, is2D );
6689
6690   // find bad triangles
6691
6692   vector< const SMDS_MeshElement* > badTrias;
6693   vector< double >                  badAspects;
6694   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
6695   SMDS_ElemIteratorPtr fIt = sm->GetElements();
6696   while ( fIt->more() )
6697   {
6698     const SMDS_MeshElement * f = fIt->next();
6699     if ( f->NbCornerNodes() != 3 ) continue;
6700     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
6701     double aspect = qualifier.GetValue( points );
6702     if ( aspect > maxAspectRatio )
6703     {
6704       badTrias.push_back( f );
6705       badAspects.push_back( aspect );
6706     }
6707   }
6708   if ( step == 1 )
6709   {
6710     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
6711     SMDS_ElemIteratorPtr fIt = sm->GetElements();
6712     while ( fIt->more() )
6713     {
6714       const SMDS_MeshElement * f = fIt->next();
6715       if ( f->NbCornerNodes() == 3 )
6716         dumpChangeNodes( f );
6717     }
6718     dumpFunctionEnd();
6719   }
6720   if ( badTrias.empty() )
6721     return;
6722
6723   // find couples of faces to swap diagonal
6724
6725   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
6726   vector< T2Trias > triaCouples; 
6727
6728   TIDSortedElemSet involvedFaces, emptySet;
6729   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
6730   {
6731     T2Trias trias    [3];
6732     double  aspRatio [3];
6733     int i1, i2, i3;
6734
6735     if ( !involvedFaces.insert( badTrias[iTia] ).second )
6736       continue;
6737     for ( int iP = 0; iP < 3; ++iP )
6738       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
6739
6740     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
6741     int bestCouple = -1;
6742     for ( int iSide = 0; iSide < 3; ++iSide )
6743     {
6744       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
6745       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
6746       trias [iSide].first  = badTrias[iTia];
6747       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
6748                                                              & i1, & i2 );
6749       if (( ! trias[iSide].second ) ||
6750           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
6751           ( ! sm->Contains( trias[iSide].second )))
6752         continue;
6753
6754       // aspect ratio of an adjacent tria
6755       for ( int iP = 0; iP < 3; ++iP )
6756         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
6757       double aspectInit = qualifier.GetValue( points2 );
6758
6759       // arrange nodes as after diag-swaping
6760       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
6761         i3 = helper.WrapIndex( i1-1, 3 );
6762       else
6763         i3 = helper.WrapIndex( i1+1, 3 );
6764       points1 = points;
6765       points1( 1+ iSide ) = points2( 1+ i3 );
6766       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
6767
6768       // aspect ratio after diag-swaping
6769       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
6770       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
6771         continue;
6772
6773       // prevent inversion of a triangle
6774       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
6775       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
6776       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
6777         continue;
6778
6779       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
6780         bestCouple = iSide;
6781     }
6782
6783     if ( bestCouple >= 0 )
6784     {
6785       triaCouples.push_back( trias[bestCouple] );
6786       involvedFaces.insert ( trias[bestCouple].second );
6787     }
6788     else
6789     {
6790       involvedFaces.erase( badTrias[iTia] );
6791     }
6792   }
6793   if ( triaCouples.empty() )
6794     return;
6795
6796   // swap diagonals
6797
6798   SMESH_MeshEditor editor( helper.GetMesh() );
6799   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
6800   for ( size_t i = 0; i < triaCouples.size(); ++i )
6801   {
6802     dumpChangeNodes( triaCouples[i].first );
6803     dumpChangeNodes( triaCouples[i].second );
6804     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
6805   }
6806
6807   if ( involvedNodes )
6808     for ( size_t i = 0; i < triaCouples.size(); ++i )
6809     {
6810       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
6811                              triaCouples[i].first->end_nodes() );
6812       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
6813                              triaCouples[i].second->end_nodes() );
6814     }
6815
6816   // just for debug dump resulting triangles
6817   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
6818   for ( size_t i = 0; i < triaCouples.size(); ++i )
6819   {
6820     dumpChangeNodes( triaCouples[i].first );
6821     dumpChangeNodes( triaCouples[i].second );
6822   }
6823 }
6824
6825 //================================================================================
6826 /*!
6827  * \brief Move target node to it's final position on the FACE during shrinking
6828  */
6829 //================================================================================
6830
6831 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
6832                                  const TopoDS_Face&    F,
6833                                  SMESH_MesherHelper&   helper )
6834 {
6835   if ( _pos.empty() )
6836     return false; // already at the target position
6837
6838   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
6839
6840   if ( _sWOL.ShapeType() == TopAbs_FACE )
6841   {
6842     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
6843     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
6844     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
6845     const double uvLen = tgtUV.Distance( curUV );
6846     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
6847
6848     // Select shrinking step such that not to make faces with wrong orientation.
6849     double stepSize = 1e100;
6850     for ( size_t i = 0; i < _simplices.size(); ++i )
6851     {
6852       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
6853       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
6854       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
6855       gp_XY dirN = uvN2 - uvN1;
6856       double det = uvDir.Crossed( dirN );
6857       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
6858       gp_XY dirN2Cur = curUV - uvN1;
6859       double step = dirN.Crossed( dirN2Cur ) / det;
6860       if ( step > 0 )
6861         stepSize = Min( step, stepSize );
6862     }
6863     gp_Pnt2d newUV;
6864     if ( uvLen <= stepSize )
6865     {
6866       newUV = tgtUV;
6867       _pos.clear();
6868     }
6869     else if ( stepSize > 0 )
6870     {
6871       newUV = curUV + uvDir.XY() * stepSize * kSafe;
6872     }
6873     else
6874     {
6875       return true;
6876     }
6877     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
6878     pos->SetUParameter( newUV.X() );
6879     pos->SetVParameter( newUV.Y() );
6880
6881 #ifdef __myDEBUG
6882     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
6883     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6884     dumpMove( tgtNode );
6885 #endif
6886   }
6887   else // _sWOL is TopAbs_EDGE
6888   {
6889     const TopoDS_Edge&      E = TopoDS::Edge( _sWOL );
6890     const SMDS_MeshNode*   n2 = _simplices[0]._nPrev;
6891     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
6892
6893     const double u2     = helper.GetNodeU( E, n2, tgtNode );
6894     const double uSrc   = _pos[0].Coord( U_SRC );
6895     const double lenTgt = _pos[0].Coord( LEN_TGT );
6896
6897     double newU = _pos[0].Coord( U_TGT );
6898     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
6899     {
6900       _pos.clear();
6901     }
6902     else
6903     {
6904       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
6905     }
6906     tgtPos->SetUParameter( newU );
6907 #ifdef __myDEBUG
6908     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
6909     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
6910     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
6911     dumpMove( tgtNode );
6912 #endif
6913   }
6914   return true;
6915 }
6916
6917 //================================================================================
6918 /*!
6919  * \brief Perform smooth on the FACE
6920  *  \retval bool - true if the node has been moved
6921  */
6922 //================================================================================
6923
6924 bool _SmoothNode::Smooth(int&                  badNb,
6925                          Handle(Geom_Surface)& surface,
6926                          SMESH_MesherHelper&   helper,
6927                          const double          refSign,
6928                          SmoothType            how,
6929                          bool                  set3D)
6930 {
6931   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
6932
6933   // get uv of surrounding nodes
6934   vector<gp_XY> uv( _simplices.size() );
6935   for ( size_t i = 0; i < _simplices.size(); ++i )
6936     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
6937
6938   // compute new UV for the node
6939   gp_XY newPos (0,0);
6940   if ( how == TFI && _simplices.size() == 4 )
6941   {
6942     gp_XY corners[4];
6943     for ( size_t i = 0; i < _simplices.size(); ++i )
6944       if ( _simplices[i]._nOpp )
6945         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
6946       else
6947         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
6948
6949     newPos = helper.calcTFI ( 0.5, 0.5,
6950                               corners[0], corners[1], corners[2], corners[3],
6951                               uv[1], uv[2], uv[3], uv[0] );
6952   }
6953   else if ( how == ANGULAR )
6954   {
6955     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
6956   }
6957   else if ( how == CENTROIDAL && _simplices.size() > 3 )
6958   {
6959     // average centers of diagonals wieghted with their reciprocal lengths
6960     if ( _simplices.size() == 4 )
6961     {
6962       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
6963       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
6964       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
6965     }
6966     else
6967     {
6968       double sumWeight = 0;
6969       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
6970       for ( int i = 0; i < nb; ++i )
6971       {
6972         int iFrom = i + 2;
6973         int iTo   = i + _simplices.size() - 1;
6974         for ( int j = iFrom; j < iTo; ++j )
6975         {
6976           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
6977           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
6978           sumWeight += w;
6979           newPos += w * ( uv[i]+uv[i2] );
6980         }
6981       }
6982       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
6983     }
6984   }
6985   else
6986   {
6987     // Laplacian smooth
6988     for ( size_t i = 0; i < _simplices.size(); ++i )
6989       newPos += uv[i];
6990     newPos /= _simplices.size();
6991   }
6992
6993   // count quality metrics (orientation) of triangles around the node
6994   int nbOkBefore = 0;
6995   gp_XY tgtUV = helper.GetNodeUV( face, _node );
6996   for ( size_t i = 0; i < _simplices.size(); ++i )
6997     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
6998
6999   int nbOkAfter = 0;
7000   for ( size_t i = 0; i < _simplices.size(); ++i )
7001     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
7002
7003   if ( nbOkAfter < nbOkBefore )
7004   {
7005     badNb += _simplices.size() - nbOkBefore;
7006     return false;
7007   }
7008
7009   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
7010   pos->SetUParameter( newPos.X() );
7011   pos->SetVParameter( newPos.Y() );
7012
7013 #ifdef __myDEBUG
7014   set3D = true;
7015 #endif
7016   if ( set3D )
7017   {
7018     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
7019     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
7020     dumpMove( _node );
7021   }
7022
7023   badNb += _simplices.size() - nbOkAfter;
7024   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
7025 }
7026
7027 //================================================================================
7028 /*!
7029  * \brief Computes new UV using angle based smoothing technic
7030  */
7031 //================================================================================
7032
7033 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
7034                                      const gp_XY&   uvToFix,
7035                                      const double   refSign)
7036 {
7037   uv.push_back( uv.front() );
7038
7039   vector< gp_XY >  edgeDir ( uv.size() );
7040   vector< double > edgeSize( uv.size() );
7041   for ( size_t i = 1; i < edgeDir.size(); ++i )
7042   {
7043     edgeDir [i-1] = uv[i] - uv[i-1];
7044     edgeSize[i-1] = edgeDir[i-1].Modulus();
7045     if ( edgeSize[i-1] < numeric_limits<double>::min() )
7046       edgeDir[i-1].SetX( 100 );
7047     else
7048       edgeDir[i-1] /= edgeSize[i-1] * refSign;
7049   }
7050   edgeDir.back()  = edgeDir.front();
7051   edgeSize.back() = edgeSize.front();
7052
7053   gp_XY  newPos(0,0);
7054   //int    nbEdges = 0;
7055   double sumSize = 0;
7056   for ( size_t i = 1; i < edgeDir.size(); ++i )
7057   {
7058     if ( edgeDir[i-1].X() > 1. ) continue;
7059     int i1 = i-1;
7060     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
7061     if ( i == edgeDir.size() ) break;
7062     gp_XY p = uv[i];
7063     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
7064     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
7065     gp_XY bisec = norm1 + norm2;
7066     double bisecSize = bisec.Modulus();
7067     if ( bisecSize < numeric_limits<double>::min() )
7068     {
7069       bisec = -edgeDir[i1] + edgeDir[i];
7070       bisecSize = bisec.Modulus();
7071     }
7072     bisec /= bisecSize;
7073
7074     gp_XY  dirToN  = uvToFix - p;
7075     double distToN = dirToN.Modulus();
7076     if ( bisec * dirToN < 0 )
7077       distToN = -distToN;
7078
7079     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
7080     //++nbEdges;
7081     sumSize += edgeSize[i1] + edgeSize[i];
7082   }
7083   newPos /= /*nbEdges * */sumSize;
7084   return newPos;
7085 }
7086
7087 //================================================================================
7088 /*!
7089  * \brief Delete _SolidData
7090  */
7091 //================================================================================
7092
7093 _SolidData::~_SolidData()
7094 {
7095   for ( size_t i = 0; i < _edges.size(); ++i )
7096   {
7097     if ( _edges[i] && _edges[i]->_2neibors )
7098       delete _edges[i]->_2neibors;
7099     delete _edges[i];
7100   }
7101   _edges.clear();
7102 }
7103 //================================================================================
7104 /*!
7105  * \brief Add a _LayerEdge inflated along the EDGE
7106  */
7107 //================================================================================
7108
7109 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
7110 {
7111   // init
7112   if ( _nodes.empty() )
7113   {
7114     _edges[0] = _edges[1] = 0;
7115     _done = false;
7116   }
7117   // check _LayerEdge
7118   if ( e == _edges[0] || e == _edges[1] )
7119     return;
7120   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
7121     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7122   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
7123     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
7124
7125   // store _LayerEdge
7126   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
7127   double f,l;
7128   BRep_Tool::Range( E, f,l );
7129   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
7130   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
7131
7132   // Update _nodes
7133
7134   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
7135   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
7136
7137   if ( _nodes.empty() )
7138   {
7139     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
7140     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
7141       return;
7142     TopLoc_Location loc;
7143     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
7144     GeomAdaptor_Curve aCurve(C, f,l);
7145     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
7146
7147     int nbExpectNodes = eSubMesh->NbNodes();
7148     _initU  .reserve( nbExpectNodes );
7149     _normPar.reserve( nbExpectNodes );
7150     _nodes  .reserve( nbExpectNodes );
7151     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
7152     while ( nIt->more() )
7153     {
7154       const SMDS_MeshNode* node = nIt->next();
7155       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
7156            node == tgtNode0 || node == tgtNode1 )
7157         continue; // refinement nodes
7158       _nodes.push_back( node );
7159       _initU.push_back( helper.GetNodeU( E, node ));
7160       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
7161       _normPar.push_back(  len / totLen );
7162     }
7163   }
7164   else
7165   {
7166     // remove target node of the _LayerEdge from _nodes
7167     int nbFound = 0;
7168     for ( size_t i = 0; i < _nodes.size(); ++i )
7169       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
7170         _nodes[i] = 0, nbFound++;
7171     if ( nbFound == _nodes.size() )
7172       _nodes.clear();
7173   }
7174 }
7175
7176 //================================================================================
7177 /*!
7178  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
7179  */
7180 //================================================================================
7181
7182 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
7183 {
7184   if ( _done || _nodes.empty())
7185     return;
7186   const _LayerEdge* e = _edges[0];
7187   if ( !e ) e = _edges[1];
7188   if ( !e ) return;
7189
7190   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
7191             ( !_edges[1] || _edges[1]->_pos.empty() ));
7192
7193   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
7194   double f,l;
7195   if ( set3D || _done )
7196   {
7197     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
7198     GeomAdaptor_Curve aCurve(C, f,l);
7199
7200     if ( _edges[0] )
7201       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
7202     if ( _edges[1] )
7203       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
7204     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
7205
7206     for ( size_t i = 0; i < _nodes.size(); ++i )
7207     {
7208       if ( !_nodes[i] ) continue;
7209       double len = totLen * _normPar[i];
7210       GCPnts_AbscissaPoint discret( aCurve, len, f );
7211       if ( !discret.IsDone() )
7212         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
7213       double u = discret.Parameter();
7214       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7215       pos->SetUParameter( u );
7216       gp_Pnt p = C->Value( u );
7217       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
7218     }
7219   }
7220   else
7221   {
7222     BRep_Tool::Range( E, f,l );
7223     if ( _edges[0] )
7224       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
7225     if ( _edges[1] )
7226       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
7227     
7228     for ( size_t i = 0; i < _nodes.size(); ++i )
7229     {
7230       if ( !_nodes[i] ) continue;
7231       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
7232       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7233       pos->SetUParameter( u );
7234     }
7235   }
7236 }
7237
7238 //================================================================================
7239 /*!
7240  * \brief Restore initial parameters of nodes on EDGE
7241  */
7242 //================================================================================
7243
7244 void _Shrinker1D::RestoreParams()
7245 {
7246   if ( _done )
7247     for ( size_t i = 0; i < _nodes.size(); ++i )
7248     {
7249       if ( !_nodes[i] ) continue;
7250       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
7251       pos->SetUParameter( _initU[i] );
7252     }
7253   _done = false;
7254 }
7255
7256 //================================================================================
7257 /*!
7258  * \brief Replace source nodes by target nodes in shrinked mesh edges
7259  */
7260 //================================================================================
7261
7262 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
7263 {
7264   const SMDS_MeshNode* nodes[3];
7265   for ( int i = 0; i < 2; ++i )
7266   {
7267     if ( !_edges[i] ) continue;
7268
7269     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
7270     if ( !eSubMesh ) return;
7271     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
7272     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
7273     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
7274     while ( eIt->more() )
7275     {
7276       const SMDS_MeshElement* e = eIt->next();
7277       if ( !eSubMesh->Contains( e ))
7278           continue;
7279       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7280       for ( int iN = 0; iN < e->NbNodes(); ++iN )
7281       {
7282         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
7283         nodes[iN] = ( n == srcNode ? tgtNode : n );
7284       }
7285       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
7286     }
7287   }
7288 }
7289
7290 //================================================================================
7291 /*!
7292  * \brief Creates 2D and 1D elements on boundaries of new prisms
7293  */
7294 //================================================================================
7295
7296 bool _ViscousBuilder::addBoundaryElements()
7297 {
7298   SMESH_MesherHelper helper( *_mesh );
7299
7300   vector< const SMDS_MeshNode* > faceNodes;
7301
7302   for ( size_t i = 0; i < _sdVec.size(); ++i )
7303   {
7304     _SolidData& data = _sdVec[i];
7305     TopTools_IndexedMapOfShape geomEdges;
7306     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
7307     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
7308     {
7309       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
7310       if ( data._noShrinkShapes.count( getMeshDS()->ShapeToIndex( E )))
7311         continue;
7312
7313       // Get _LayerEdge's based on E
7314
7315       map< double, const SMDS_MeshNode* > u2nodes;
7316       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
7317         continue;
7318
7319       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
7320       TNode2Edge & n2eMap = data._n2eMap;
7321       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
7322       {
7323         //check if 2D elements are needed on E
7324         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
7325         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
7326         ledges.push_back( n2e->second );
7327         u2n++;
7328         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
7329           continue; // no layers on E
7330         ledges.push_back( n2eMap[ u2n->second ]);
7331
7332         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
7333         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
7334         int nbSharedPyram = 0;
7335         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
7336         while ( vIt->more() )
7337         {
7338           const SMDS_MeshElement* v = vIt->next();
7339           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
7340         }
7341         if ( nbSharedPyram > 1 )
7342           continue; // not free border of the pyramid
7343
7344         faceNodes.clear();
7345         faceNodes.push_back( ledges[0]->_nodes[0] );
7346         faceNodes.push_back( ledges[1]->_nodes[0] );
7347         if ( ledges[0]->_nodes.size() > 1 ) faceNodes.push_back( ledges[0]->_nodes[1] );
7348         if ( ledges[1]->_nodes.size() > 1 ) faceNodes.push_back( ledges[1]->_nodes[1] );
7349
7350         if ( getMeshDS()->FindElement( faceNodes, SMDSAbs_Face, /*noMedium=*/true))
7351           continue; // faces already created
7352       }
7353       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
7354         ledges.push_back( n2eMap[ u2n->second ]);
7355
7356       // Find out orientation and type of face to create
7357
7358       bool reverse = false, isOnFace;
7359       
7360       map< TGeomID, TopoDS_Shape >::iterator e2f =
7361         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
7362       TopoDS_Shape F;
7363       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
7364       {
7365         F = e2f->second.Oriented( TopAbs_FORWARD );
7366         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
7367         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
7368           reverse = !reverse, F.Reverse();
7369         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
7370           reverse = !reverse;
7371       }
7372       else
7373       {
7374         // find FACE with layers sharing E
7375         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
7376         while ( fIt->more() && F.IsNull() )
7377         {
7378           const TopoDS_Shape* pF = fIt->next();
7379           if ( helper.IsSubShape( *pF, data._solid) &&
7380                !data._ignoreFaceIds.count( e2f->first ))
7381             F = *pF;
7382         }
7383       }
7384       // Find the sub-mesh to add new faces
7385       SMESHDS_SubMesh* sm = 0;
7386       if ( isOnFace )
7387         sm = getMeshDS()->MeshElements( F );
7388       else
7389         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
7390       if ( !sm )
7391         return error("error in addBoundaryElements()", data._index);
7392
7393       // Make faces
7394       const int dj1 = reverse ? 0 : 1;
7395       const int dj2 = reverse ? 1 : 0;
7396       for ( size_t j = 1; j < ledges.size(); ++j )
7397       {
7398         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
7399         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
7400         if ( nn1.size() == nn2.size() )
7401         {
7402           if ( isOnFace )
7403             for ( size_t z = 1; z < nn1.size(); ++z )
7404               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7405           else
7406             for ( size_t z = 1; z < nn1.size(); ++z )
7407               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
7408         }
7409         else if ( nn1.size() == 1 )
7410         {
7411           if ( isOnFace )
7412             for ( size_t z = 1; z < nn2.size(); ++z )
7413               sm->AddElement( getMeshDS()->AddFace( nn1[0], nn2[z-1], nn2[z] ));
7414           else
7415             for ( size_t z = 1; z < nn2.size(); ++z )
7416               sm->AddElement( new SMDS_FaceOfNodes( nn1[0], nn2[z-1], nn2[z] ));
7417         }
7418         else
7419         {
7420           if ( isOnFace )
7421             for ( size_t z = 1; z < nn1.size(); ++z )
7422               sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[0], nn1[z] ));
7423           else
7424             for ( size_t z = 1; z < nn1.size(); ++z )
7425               sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[0], nn2[z] ));
7426         }
7427       }
7428
7429       // Make edges
7430       for ( int isFirst = 0; isFirst < 2; ++isFirst )
7431       {
7432         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
7433         if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
7434         {
7435           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
7436           if ( nn.size() < 2 || nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
7437             continue;
7438           helper.SetSubShape( edge->_sWOL );
7439           helper.SetElementsOnShape( true );
7440           for ( size_t z = 1; z < nn.size(); ++z )
7441             helper.AddEdge( nn[z-1], nn[z] );
7442         }
7443       }
7444     }
7445   }
7446
7447   return true;
7448 }