Salome HOME
604149f8f667781ffc5c39c3a52556999b3a6053
[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 //#define __myDEBUG
87
88 using namespace std;
89
90 //================================================================================
91 namespace VISCOUS_3D
92 {
93   typedef int TGeomID;
94
95   enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
96
97   /*!
98    * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
99    * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
100    */
101   struct _MeshOfSolid : public SMESH_ProxyMesh,
102                         public SMESH_subMeshEventListenerData
103   {
104     bool _n2nMapComputed;
105
106     _MeshOfSolid( SMESH_Mesh* mesh)
107       :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
108     {
109       SMESH_ProxyMesh::setMesh( *mesh );
110     }
111
112     // returns submesh for a geom face
113     SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
114     {
115       TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
116       return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
117     }
118     void setNode2Node(const SMDS_MeshNode*                 srcNode,
119                       const SMDS_MeshNode*                 proxyNode,
120                       const SMESH_ProxyMesh::SubMesh* subMesh)
121     {
122       SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
123     }
124   };
125   //--------------------------------------------------------------------------------
126   /*!
127    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
128    * It is used to clear an inferior dim sub-meshes modified by viscous layers
129    */
130   class _ShrinkShapeListener : SMESH_subMeshEventListener
131   {
132     _ShrinkShapeListener()
133       : SMESH_subMeshEventListener(/*isDeletable=*/false,
134                                    "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
135   public:
136     static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
137     virtual void ProcessEvent(const int                       event,
138                               const int                       eventType,
139                               SMESH_subMesh*                  solidSM,
140                               SMESH_subMeshEventListenerData* data,
141                               const SMESH_Hypothesis*         hyp)
142     {
143       if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
144       {
145         SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
146       }
147     }
148   };
149   //--------------------------------------------------------------------------------
150   /*!
151    * \brief Listener of events of 3D sub-meshes computed with viscous layers.
152    * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
153    * delete the data as soon as it has been used
154    */
155   class _ViscousListener : SMESH_subMeshEventListener
156   {
157     _ViscousListener():
158       SMESH_subMeshEventListener(/*isDeletable=*/false,
159                                  "StdMeshers_ViscousLayers::_ViscousListener") {}
160     static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
161   public:
162     virtual void ProcessEvent(const int                       event,
163                               const int                       eventType,
164                               SMESH_subMesh*                  subMesh,
165                               SMESH_subMeshEventListenerData* data,
166                               const SMESH_Hypothesis*         hyp)
167     {
168       if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
169       {
170         // delete SMESH_ProxyMesh containing temporary faces
171         subMesh->DeleteEventListener( this );
172       }
173     }
174     // Finds or creates proxy mesh of the solid
175     static _MeshOfSolid* GetSolidMesh(SMESH_Mesh*         mesh,
176                                       const TopoDS_Shape& solid,
177                                       bool                toCreate=false)
178     {
179       if ( !mesh ) return 0;
180       SMESH_subMesh* sm = mesh->GetSubMesh(solid);
181       _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
182       if ( !data && toCreate )
183       {
184         data = new _MeshOfSolid(mesh);
185         data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
186         sm->SetEventListener( Get(), data, sm );
187       }
188       return data;
189     }
190     // Removes proxy mesh of the solid
191     static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
192     {
193       mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
194     }
195   };
196   
197   //================================================================================
198   /*!
199    * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
200    * the main shape when sub-mesh of the main shape is cleared,
201    * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
202    * is cleared
203    */
204   //================================================================================
205
206   void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
207   {
208     SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
209     SMESH_subMeshEventListenerData* data =
210       mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
211     if ( data )
212     {
213       if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
214            data->mySubMeshes.end())
215         data->mySubMeshes.push_back( sub );
216     }
217     else
218     {
219       data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
220       sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
221     }
222   }
223   //--------------------------------------------------------------------------------
224   /*!
225    * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
226    * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
227    * The class is used to check validity of face or volumes around a smoothed node;
228    * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
229    */
230   struct _Simplex
231   {
232     const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
233     const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
234     _Simplex(const SMDS_MeshNode* nPrev=0,
235              const SMDS_MeshNode* nNext=0,
236              const SMDS_MeshNode* nOpp=0)
237       : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
238     bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
239     {
240       const double M[3][3] =
241         {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
242          { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
243          { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
244       double determinant = ( + M[0][0]*M[1][1]*M[2][2]
245                              + M[0][1]*M[1][2]*M[2][0]
246                              + M[0][2]*M[1][0]*M[2][1]
247                              - M[0][0]*M[1][2]*M[2][1]
248                              - M[0][1]*M[1][0]*M[2][2]
249                              - M[0][2]*M[1][1]*M[2][0]);
250       return determinant > 1e-100;
251     }
252     bool IsForward(const gp_XY&         tgtUV,
253                    const SMDS_MeshNode* smoothedNode,
254                    const TopoDS_Face&   face,
255                    SMESH_MesherHelper&  helper,
256                    const double         refSign) const
257     {
258       gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
259       gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
260       gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
261       double d = v1 ^ v2;
262       return d*refSign > 1e-100;
263     }
264     bool IsNeighbour(const _Simplex& other) const
265     {
266       return _nPrev == other._nNext || _nNext == other._nPrev;
267     }
268   };
269   //--------------------------------------------------------------------------------
270   /*!
271    * Structure used to take into account surface curvature while smoothing
272    */
273   struct _Curvature
274   {
275     double _r; // radius
276     double _k; // factor to correct node smoothed position
277     double _h2lenRatio; // avgNormProj / (2*avgDist)
278   public:
279     static _Curvature* New( double avgNormProj, double avgDist )
280     {
281       _Curvature* c = 0;
282       if ( fabs( avgNormProj / avgDist ) > 1./200 )
283       {
284         c = new _Curvature;
285         c->_r = avgDist * avgDist / avgNormProj;
286         c->_k = avgDist * avgDist / c->_r / c->_r;
287         c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
288         c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
289       }
290       return c;
291     }
292     double lenDelta(double len) const { return _k * ( _r + len ); }
293     double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
294   };
295   struct _LayerEdge;
296   //--------------------------------------------------------------------------------
297   /*!
298    * Structure used to smooth a _LayerEdge (master) based on an EDGE.
299    */
300   struct _2NearEdges
301   {
302     // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
303     const SMDS_MeshNode* _nodes[2];
304     // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
305     //gp_XYZ               _vec[2];
306     double               _wgt[2]; // weights of _nodes
307     _LayerEdge*          _edges[2];
308
309      // normal to plane passing through _LayerEdge._normal and tangent of EDGE
310     gp_XYZ*              _plnNorm;
311
312     _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
313     void reverse() {
314       std::swap( _nodes[0], _nodes[1] );
315       std::swap( _wgt[0], _wgt[1] );
316     }
317   };
318   //--------------------------------------------------------------------------------
319   /*!
320    * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
321    * and a node of the most internal layer (_nodes.back())
322    */
323   struct _LayerEdge
324   {
325     vector< const SMDS_MeshNode*> _nodes;
326
327     gp_XYZ              _normal; // to solid surface
328     vector<gp_XYZ>      _pos; // points computed during inflation
329     double              _len; // length achived with the last step
330     double              _cosin; // of angle (_normal ^ surface)
331     double              _lenFactor; // to compute _len taking _cosin into account
332
333     // face or edge w/o layer along or near which _LayerEdge is inflated
334     TopoDS_Shape        _sWOL;
335     // simplices connected to the source node (_nodes[0]);
336     // used for smoothing and quality check of _LayerEdge's based on the FACE
337     vector<_Simplex>    _simplices;
338     // data for smoothing of _LayerEdge's based on the EDGE
339     _2NearEdges*        _2neibors;
340
341     _Curvature*         _curvature;
342     // TODO:: detele _Curvature, _plnNorm
343
344     void SetNewLength( double len, SMESH_MesherHelper& helper );
345     bool SetNewLength2d( Handle(Geom_Surface)& surface,
346                          const TopoDS_Face&    F,
347                          SMESH_MesherHelper&   helper );
348     void SetDataByNeighbors( const SMDS_MeshNode* n1,
349                              const SMDS_MeshNode* n2,
350                              SMESH_MesherHelper&  helper);
351     void InvalidateStep( int curStep );
352     bool Smooth(int& badNb);
353     bool SmoothOnEdge(Handle(Geom_Surface)& surface,
354                       const TopoDS_Face&    F,
355                       SMESH_MesherHelper&   helper);
356     bool FindIntersection( SMESH_ElementSearcher&   searcher,
357                            double &                 distance,
358                            const double&            epsilon,
359                            const SMDS_MeshElement** face = 0);
360     bool SegTriaInter( const gp_Ax1&        lastSegment,
361                        const SMDS_MeshNode* n0,
362                        const SMDS_MeshNode* n1,
363                        const SMDS_MeshNode* n2,
364                        double&              dist,
365                        const double&        epsilon) const;
366     gp_Ax1 LastSegment(double& segLen) const;
367     bool IsOnEdge() const { return _2neibors; }
368     void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
369     void SetCosin( double cosin );
370   };
371   struct _LayerEdgeCmp
372   {
373     bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
374     {
375       const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
376       return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
377     }
378   };
379   //--------------------------------------------------------------------------------
380
381   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
382   
383   //--------------------------------------------------------------------------------
384   /*!
385    * \brief Data of a SOLID
386    */
387   struct _SolidData
388   {
389     TopoDS_Shape                    _solid;
390     const StdMeshers_ViscousLayers* _hyp;
391     TopoDS_Shape                    _hypShape;
392     _MeshOfSolid*                   _proxyMesh;
393     set<TGeomID>                    _reversedFaceIds;
394     set<TGeomID>                    _ignoreFaceIds;
395
396     double                          _stepSize, _stepSizeCoeff;
397     const SMDS_MeshNode*            _stepSizeNodes[2];
398
399     TNode2Edge                      _n2eMap;
400     // edges of _n2eMap. We keep same data in two containers because
401     // iteration over the map is 5 time longer than over the vector
402     vector< _LayerEdge* >           _edges;
403     // edges on EDGE's with null _sWOL, whose _simplices are used to stop inflation
404     vector< _LayerEdge* >           _simplexTestEdges;
405
406     // key:   an id of shape (EDGE or VERTEX) shared by a FACE with
407     //        layers and a FACE w/o layers
408     // value: the shape (FACE or EDGE) to shrink mesh on.
409     //       _LayerEdge's basing on nodes on key shape are inflated along the value shape
410     map< TGeomID, TopoDS_Shape >     _shrinkShape2Shape;
411
412     // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
413     set< TGeomID >                   _noShrinkFaces;
414
415     // <EDGE to smooth on> to <it's curve>
416     map< TGeomID,Handle(Geom_Curve)> _edge2curve;
417
418     // end indices in _edges of _LayerEdge on one shape to smooth
419     vector< int >                    _endEdgeToSmooth;
420
421     double                           _epsilon; // precision for SegTriaInter()
422
423     int                              _index; // for debug
424
425     _SolidData(const TopoDS_Shape&             s=TopoDS_Shape(),
426                const StdMeshers_ViscousLayers* h=0,
427                const TopoDS_Shape&             hs=TopoDS_Shape(),
428                _MeshOfSolid*                   m=0)
429       :_solid(s), _hyp(h), _hypShape(hs), _proxyMesh(m) {}
430     ~_SolidData();
431
432     Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge&    E,
433                                        const int             iFrom,
434                                        const int             iTo,
435                                        Handle(Geom_Surface)& surface,
436                                        const TopoDS_Face&    F,
437                                        SMESH_MesherHelper&   helper);
438   };
439   //--------------------------------------------------------------------------------
440   /*!
441    * \brief Data of node on a shrinked FACE
442    */
443   struct _SmoothNode
444   {
445     const SMDS_MeshNode*         _node;
446     //vector<const SMDS_MeshNode*> _nodesAround;
447     vector<_Simplex>             _simplices; // for quality check
448
449     enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR, TFI };
450
451     bool Smooth(int&                  badNb,
452                 Handle(Geom_Surface)& surface,
453                 SMESH_MesherHelper&   helper,
454                 const double          refSign,
455                 SmoothType            how,
456                 bool                  set3D);
457
458     gp_XY computeAngularPos(vector<gp_XY>& uv,
459                             const gp_XY&   uvToFix,
460                             const double   refSign );
461   };
462   //--------------------------------------------------------------------------------
463   /*!
464    * \brief Builder of viscous layers
465    */
466   class _ViscousBuilder
467   {
468   public:
469     _ViscousBuilder();
470     // does it's job
471     SMESH_ComputeErrorPtr Compute(SMESH_Mesh&         mesh,
472                                   const TopoDS_Shape& shape);
473
474     // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
475     void RestoreListeners();
476
477     // computes SMESH_ProxyMesh::SubMesh::_n2n;
478     bool MakeN2NMap( _MeshOfSolid* pm );
479
480   private:
481
482     bool findSolidsWithLayers();
483     bool findFacesWithLayers();
484     bool makeLayer(_SolidData& data);
485     bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
486                      SMESH_MesherHelper& helper, _SolidData& data);
487     gp_XYZ getWeigthedNormal( const SMDS_MeshNode*         n,
488                               std::pair< TGeomID, gp_XYZ > fId2Normal[],
489                               const int                    nbFaces );
490     bool findNeiborsOnEdge(const _LayerEdge*     edge,
491                            const SMDS_MeshNode*& n1,
492                            const SMDS_MeshNode*& n2,
493                            _SolidData&           data);
494     void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
495                        const set<TGeomID>& ingnoreShapes,
496                        const _SolidData*   dataToCheckOri = 0,
497                        const bool          toSort = false);
498     void findSimplexTestEdges( _SolidData&                    data,
499                                vector< vector<_LayerEdge*> >& edgesByGeom);
500     bool sortEdges( _SolidData&                    data,
501                     vector< vector<_LayerEdge*> >& edgesByGeom);
502     void limitStepSize( _SolidData&             data,
503                         const SMDS_MeshElement* face,
504                         const double            cosin);
505     void limitStepSize( _SolidData& data, const double minSize);
506     bool inflate(_SolidData& data);
507     bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
508     bool smoothAnalyticEdge( _SolidData&           data,
509                              const int             iFrom,
510                              const int             iTo,
511                              Handle(Geom_Surface)& surface,
512                              const TopoDS_Face&    F,
513                              SMESH_MesherHelper&   helper);
514     bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
515     bool refine(_SolidData& data);
516     bool shrink();
517     bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
518                               SMESH_MesherHelper& helper,
519                               const SMESHDS_SubMesh* faceSubMesh );
520     void fixBadFaces(const TopoDS_Face&          F,
521                      SMESH_MesherHelper&         helper,
522                      const bool                  is2D,
523                      const int                   step,
524                      set<const SMDS_MeshNode*> * involvedNodes=NULL);
525     bool addBoundaryElements();
526
527     bool error( const string& text, int solidID=-1 );
528     SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
529
530     // debug
531     void makeGroupOfLE();
532
533     SMESH_Mesh*           _mesh;
534     SMESH_ComputeErrorPtr _error;
535
536     vector< _SolidData >  _sdVec;
537     int                   _tmpFaceID;
538   };
539   //--------------------------------------------------------------------------------
540   /*!
541    * \brief Shrinker of nodes on the EDGE
542    */
543   class _Shrinker1D
544   {
545     vector<double>                _initU;
546     vector<double>                _normPar;
547     vector<const SMDS_MeshNode*>  _nodes;
548     const _LayerEdge*             _edges[2];
549     bool                          _done;
550   public:
551     void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
552     void Compute(bool set3D, SMESH_MesherHelper& helper);
553     void RestoreParams();
554     void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
555   };
556   //--------------------------------------------------------------------------------
557   /*!
558    * \brief Class of temporary mesh face.
559    * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
560    * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
561    */
562   struct TmpMeshFace : public SMDS_MeshElement
563   {
564     vector<const SMDS_MeshNode* > _nn;
565     TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
566       SMDS_MeshElement(id), _nn(nodes) {}
567     virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
568     virtual SMDSAbs_ElementType  GetType() const              { return SMDSAbs_Face; }
569     virtual vtkIdType GetVtkType() const                      { return -1; }
570     virtual SMDSAbs_EntityType   GetEntityType() const        { return SMDSEntity_Last; }
571     virtual SMDSAbs_GeometryType GetGeomType() const          { return SMDSGeom_TRIANGLE; }
572     virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType) const
573     { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
574   };
575   //--------------------------------------------------------------------------------
576   /*!
577    * \brief Class of temporary mesh face storing _LayerEdge it's based on
578    */
579   struct TmpMeshFaceOnEdge : public TmpMeshFace
580   {
581     _LayerEdge *_le1, *_le2;
582     TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
583       TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
584     {
585       _nn[0]=_le1->_nodes[0];
586       _nn[1]=_le1->_nodes.back();
587       _nn[2]=_le2->_nodes.back();
588       _nn[3]=_le2->_nodes[0];
589     }
590   };
591   //--------------------------------------------------------------------------------
592   /*!
593    * \brief Retriever of node coordinates either directly of from a surface by node UV.
594    * \warning Location of a surface is ignored
595    */
596   struct NodeCoordHelper
597   {
598     SMESH_MesherHelper&        _helper;
599     const TopoDS_Face&         _face;
600     Handle(Geom_Surface)       _surface;
601     gp_XYZ (NodeCoordHelper::* _fun)(const SMDS_MeshNode* n) const;
602
603     NodeCoordHelper(const TopoDS_Face& F, SMESH_MesherHelper& helper, bool is2D)
604       : _helper( helper ), _face( F )
605     {
606       if ( is2D )
607       {
608         TopLoc_Location loc;
609         _surface = BRep_Tool::Surface( _face, loc );
610       }
611       if ( _surface.IsNull() )
612         _fun = & NodeCoordHelper::direct;
613       else
614         _fun = & NodeCoordHelper::byUV;
615     }
616     gp_XYZ operator()(const SMDS_MeshNode* n) const { return (this->*_fun)( n ); }
617
618   private:
619     gp_XYZ direct(const SMDS_MeshNode* n) const
620     {
621       return SMESH_TNodeXYZ( n );
622     }
623     gp_XYZ byUV  (const SMDS_MeshNode* n) const
624     {
625       gp_XY uv = _helper.GetNodeUV( _face, n );
626       return _surface->Value( uv.X(), uv.Y() ).XYZ();
627     }
628   };
629 } // namespace VISCOUS_3D
630
631 //================================================================================
632 // StdMeshers_ViscousLayers hypothesis
633 //
634 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
635   :SMESH_Hypothesis(hypId, studyId, gen),
636    _isToIgnoreShapes(1), _nbLayers(1), _thickness(1), _stretchFactor(1)
637 {
638   _name = StdMeshers_ViscousLayers::GetHypType();
639   _param_algo_dim = -3; // auxiliary hyp used by 3D algos
640 } // --------------------------------------------------------------------------------
641 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
642 {
643   if ( faceIds != _shapeIds )
644     _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
645   if ( _isToIgnoreShapes != toIgnore )
646     _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
647 } // --------------------------------------------------------------------------------
648 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
649 {
650   if ( thickness != _thickness )
651     _thickness = thickness, NotifySubMeshesHypothesisModification();
652 } // --------------------------------------------------------------------------------
653 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
654 {
655   if ( _nbLayers != nb )
656     _nbLayers = nb, NotifySubMeshesHypothesisModification();
657 } // --------------------------------------------------------------------------------
658 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
659 {
660   if ( _stretchFactor != factor )
661     _stretchFactor = factor, NotifySubMeshesHypothesisModification();
662 } // --------------------------------------------------------------------------------
663 SMESH_ProxyMesh::Ptr
664 StdMeshers_ViscousLayers::Compute(SMESH_Mesh&         theMesh,
665                                   const TopoDS_Shape& theShape,
666                                   const bool          toMakeN2NMap) const
667 {
668   using namespace VISCOUS_3D;
669   _ViscousBuilder bulder;
670   SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
671   if ( err && !err->IsOK() )
672     return SMESH_ProxyMesh::Ptr();
673
674   vector<SMESH_ProxyMesh::Ptr> components;
675   TopExp_Explorer exp( theShape, TopAbs_SOLID );
676   for ( ; exp.More(); exp.Next() )
677   {
678     if ( _MeshOfSolid* pm =
679          _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
680     {
681       if ( toMakeN2NMap && !pm->_n2nMapComputed )
682         if ( !bulder.MakeN2NMap( pm ))
683           return SMESH_ProxyMesh::Ptr();
684       components.push_back( SMESH_ProxyMesh::Ptr( pm ));
685       pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
686     }
687     _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
688   }
689   switch ( components.size() )
690   {
691   case 0: break;
692
693   case 1: return components[0];
694
695   default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
696   }
697   return SMESH_ProxyMesh::Ptr();
698 } // --------------------------------------------------------------------------------
699 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
700 {
701   save << " " << _nbLayers
702        << " " << _thickness
703        << " " << _stretchFactor
704        << " " << _shapeIds.size();
705   for ( size_t i = 0; i < _shapeIds.size(); ++i )
706     save << " " << _shapeIds[i];
707   save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
708   return save;
709 } // --------------------------------------------------------------------------------
710 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
711 {
712   int nbFaces, faceID, shapeToTreat;
713   load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
714   while ( _shapeIds.size() < nbFaces && load >> faceID )
715     _shapeIds.push_back( faceID );
716   if ( load >> shapeToTreat )
717     _isToIgnoreShapes = !shapeToTreat;
718   else
719     _isToIgnoreShapes = true; // old behavior
720   return load;
721 } // --------------------------------------------------------------------------------
722 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh*   theMesh,
723                                                    const TopoDS_Shape& theShape)
724 {
725   // TODO
726   return false;
727 }
728 // END StdMeshers_ViscousLayers hypothesis
729 //================================================================================
730
731 namespace
732 {
733   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
734   {
735     gp_Vec dir;
736     double f,l;
737     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
738     gp_Pnt p = BRep_Tool::Pnt( fromV );
739     double distF = p.SquareDistance( c->Value( f ));
740     double distL = p.SquareDistance( c->Value( l ));
741     c->D1(( distF < distL ? f : l), p, dir );
742     if ( distL < distF ) dir.Reverse();
743     return dir.XYZ();
744   }
745   //--------------------------------------------------------------------------------
746   gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
747                      SMESH_MesherHelper& helper)
748   {
749     gp_Vec dir;
750     double f,l; gp_Pnt p;
751     Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
752     double u = helper.GetNodeU( E, atNode );
753     c->D1( u, p, dir );
754     return dir.XYZ();
755   }
756   //--------------------------------------------------------------------------------
757   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
758                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
759   {
760     gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
761     Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
762     gp_Pnt p; gp_Vec du, dv, norm;
763     surface->D1( uv.X(),uv.Y(), p, du,dv );
764     norm = du ^ dv;
765
766     double f,l;
767     Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
768     double u = helper.GetNodeU( fromE, node, 0, &ok );
769     c->D1( u, p, du );
770     TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
771     if ( o == TopAbs_REVERSED )
772       du.Reverse();
773
774     gp_Vec dir = norm ^ du;
775
776     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
777          helper.IsClosedEdge( fromE ))
778     {
779       if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
780       else                         c->D1( f, p, dv );
781       if ( o == TopAbs_REVERSED )
782         dv.Reverse();
783       gp_Vec dir2 = norm ^ dv;
784       dir = dir.Normalized() + dir2.Normalized();
785     }
786     return dir.XYZ();
787   }
788   //--------------------------------------------------------------------------------
789   gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
790                      const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
791                      bool& ok, double* cosin=0)
792   {
793     double f,l; TopLoc_Location loc;
794     vector< TopoDS_Edge > edges; // sharing a vertex
795     PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
796     while ( eIt->more())
797     {
798       const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
799       if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
800         edges.push_back( *e );
801     }
802     gp_XYZ dir(0,0,0);
803     if ( !( ok = ( edges.size() > 0 ))) return dir;
804     // get average dir of edges going fromV
805     gp_XYZ edgeDir;
806     //if ( edges.size() > 1 )
807     for ( size_t i = 0; i < edges.size(); ++i )
808     {
809       edgeDir = getEdgeDir( edges[i], fromV );
810       double size2 = edgeDir.SquareModulus();
811       if ( size2 > numeric_limits<double>::min() )
812         edgeDir /= sqrt( size2 );
813       else
814         ok = false;
815       dir += edgeDir;
816     }
817     gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
818     try {
819       if ( edges.size() == 1 )
820         dir = fromEdgeDir;
821       else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
822         dir = fromEdgeDir.Normalized() + getFaceDir( F, edges[1], node, helper, ok ).Normalized();
823       else if ( dir * fromEdgeDir < 0 )
824         dir *= -1;
825     }
826     catch ( Standard_Failure )
827     {
828       ok = false;
829     }
830     if ( ok )
831     {
832       //dir /= edges.size();
833       if ( cosin ) {
834         double angle = gp_Vec( edgeDir ).Angle( dir );
835         *cosin = cos( angle );
836       }
837     }
838     return dir;
839   }
840   //================================================================================
841   /*!
842    * \brief Returns true if a FACE is bound by a concave EDGE
843    */
844   //================================================================================
845
846   bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
847   {
848     // if ( helper.Count( F, TopAbs_WIRE, /*useMap=*/false) > 1 )
849     //   return true;
850     gp_Vec2d drv1, drv2;
851     gp_Pnt2d p;
852     TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
853     for ( ; eExp.More(); eExp.Next() )
854     {
855       const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
856       if ( SMESH_Algo::isDegenerated( E )) continue;
857       // check if 2D curve is concave
858       BRepAdaptor_Curve2d curve( E, F );
859       const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
860       TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
861       curve.Intervals( intervals, GeomAbs_C2 );
862       bool isConvex = true;
863       for ( int i = 1; i <= nbIntervals && isConvex; ++i )
864       {
865         double u1 = intervals( i );
866         double u2 = intervals( i+1 );
867         curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
868         double cross = drv2 ^ drv1;
869         if ( E.Orientation() == TopAbs_REVERSED )
870           cross = -cross;
871         isConvex = ( cross > 0.1 ); //-1e-9 );
872       }
873       // check if concavity is strong enough to care about it
874       //const double maxAngle = 5 * Standard_PI180;
875       if ( !isConvex )
876       {
877         //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
878         return true;
879         // map< double, const SMDS_MeshNode* > u2nodes;
880         // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
881         //                                         /*ignoreMedium=*/true, u2nodes))
882         //   continue;
883         // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
884         // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
885         // double    uPrev = u2n->first;
886         // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
887         // {
888         //   gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
889         //   gp_Vec2d segmentDir( uvPrev, uv );
890         //   curve.D1( uPrev, p, drv1 );
891         //   try {
892         //     if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
893         //       return true;
894         //   }
895         //   catch ( ... ) {}
896         //   uvPrev = uv;
897         //   uPrev = u2n->first;
898         // }
899       }
900     }
901     // check angles at VERTEXes
902     TError error;
903     TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *helper.GetMesh(), 0, error );
904     for ( size_t iW = 0; iW < wires.size(); ++iW )
905     {
906       const int nbEdges = wires[iW]->NbEdges();
907       if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wires[iW]->Edge(0)))
908         continue;
909       for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
910       {
911         if ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE1 ))) continue;
912         int iE2 = ( iE1 + 1 ) % nbEdges;
913         while ( SMESH_Algo::isDegenerated( wires[iW]->Edge( iE2 )))
914           iE2 = ( iE2 + 1 ) % nbEdges;
915         double angle = helper.GetAngle( wires[iW]->Edge( iE1 ),
916                                         wires[iW]->Edge( iE2 ), F );
917         if ( angle < -5. * M_PI / 180. )
918           return true;
919       }
920     }
921     return false;
922   }
923   //--------------------------------------------------------------------------------
924   // DEBUG. Dump intermediate node positions into a python script
925 #ifdef __myDEBUG
926   ofstream* py;
927   struct PyDump {
928     PyDump() {
929       const char* fname = "/tmp/viscous.py";
930       cout << "execfile('"<<fname<<"')"<<endl;
931       py = new ofstream(fname);
932       *py << "import SMESH" << endl
933           << "from salome.smesh import smeshBuilder" << endl
934           << "smesh  = smeshBuilder.New(salome.myStudy)" << endl
935           << "meshSO = smesh.GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
936           << "mesh   = smesh.Mesh( meshSO.GetObject() )"<<endl;
937     }
938     void Finish() {
939       if (py)
940         *py << "mesh.MakeGroup('Viscous Prisms',SMESH.VOLUME,SMESH.FT_ElemGeomType,'=',SMESH.Geom_PENTA)"<<endl;
941       delete py; py=0;
942     }
943     ~PyDump() { Finish(); }
944   };
945 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
946 #define dumpMove(n)     { _dumpMove(n, __LINE__);}
947 #define dumpCmd(txt)    { _dumpCmd(txt, __LINE__);}
948   void _dumpFunction(const string& fun, int ln)
949   { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
950   void _dumpMove(const SMDS_MeshNode* n, int ln)
951   { if (py) *py<< "  mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
952                << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
953   void _dumpCmd(const string& txt, int ln)
954   { if (py) *py<< "  "<<txt<<" # "<< ln <<endl; }
955   void dumpFunctionEnd()
956   { if (py) *py<< "  return"<< endl; }
957   void dumpChangeNodes( const SMDS_MeshElement* f )
958   { if (py) { *py<< "  mesh.ChangeElemNodes( " << f->GetID()<<", [";
959       for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
960       *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
961 #else
962   struct PyDump { void Finish() {} };
963 #define dumpFunction(f) f
964 #define dumpMove(n)
965 #define dumpCmd(txt)
966 #define dumpFunctionEnd()
967 #define dumpChangeNodes(f)
968 #endif
969 }
970
971 using namespace VISCOUS_3D;
972
973 //================================================================================
974 /*!
975  * \brief Constructor of _ViscousBuilder
976  */
977 //================================================================================
978
979 _ViscousBuilder::_ViscousBuilder()
980 {
981   _error = SMESH_ComputeError::New(COMPERR_OK);
982   _tmpFaceID = 0;
983 }
984
985 //================================================================================
986 /*!
987  * \brief Stores error description and returns false
988  */
989 //================================================================================
990
991 bool _ViscousBuilder::error(const string& text, int solidId )
992 {
993   _error->myName    = COMPERR_ALGO_FAILED;
994   _error->myComment = string("Viscous layers builder: ") + text;
995   if ( _mesh )
996   {
997     SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
998     if ( !sm && !_sdVec.empty() )
999       sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
1000     if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
1001     {
1002       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1003       if ( smError && smError->myAlgo )
1004         _error->myAlgo = smError->myAlgo;
1005       smError = _error;
1006     }
1007   }
1008   makeGroupOfLE(); // debug
1009
1010   return false;
1011 }
1012
1013 //================================================================================
1014 /*!
1015  * \brief At study restoration, restore event listeners used to clear an inferior
1016  *  dim sub-mesh modified by viscous layers
1017  */
1018 //================================================================================
1019
1020 void _ViscousBuilder::RestoreListeners()
1021 {
1022   // TODO
1023 }
1024
1025 //================================================================================
1026 /*!
1027  * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
1028  */
1029 //================================================================================
1030
1031 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
1032 {
1033   SMESH_subMesh* solidSM = pm->mySubMeshes.front();
1034   TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
1035   for ( ; fExp.More(); fExp.Next() )
1036   {
1037     SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
1038     const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
1039
1040     if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
1041       continue;
1042     if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
1043       continue;
1044
1045     if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
1046       return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
1047
1048     SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
1049     SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
1050     while( prxIt->more() )
1051     {
1052       const SMDS_MeshElement* fSrc = srcIt->next();
1053       const SMDS_MeshElement* fPrx = prxIt->next();
1054       if ( fSrc->NbNodes() != fPrx->NbNodes())
1055         return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
1056       for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
1057         pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
1058     }
1059   }
1060   pm->_n2nMapComputed = true;
1061   return true;
1062 }
1063
1064 //================================================================================
1065 /*!
1066  * \brief Does its job
1067  */
1068 //================================================================================
1069
1070 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh&         theMesh,
1071                                                const TopoDS_Shape& theShape)
1072 {
1073   // TODO: set priority of solids during Gen::Compute()
1074
1075   _mesh = & theMesh;
1076
1077   // check if proxy mesh already computed
1078   TopExp_Explorer exp( theShape, TopAbs_SOLID );
1079   if ( !exp.More() )
1080     return error("No SOLID's in theShape"), _error;
1081
1082   if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
1083     return SMESH_ComputeErrorPtr(); // everything already computed
1084
1085   PyDump debugDump;
1086
1087   // TODO: ignore already computed SOLIDs 
1088   if ( !findSolidsWithLayers())
1089     return _error;
1090
1091   if ( !findFacesWithLayers() )
1092     return _error;
1093
1094   for ( size_t i = 0; i < _sdVec.size(); ++i )
1095   {
1096     if ( ! makeLayer(_sdVec[i]) )
1097       return _error;
1098
1099     if ( _sdVec[i]._edges.size() == 0 )
1100       continue;
1101     
1102     if ( ! inflate(_sdVec[i]) )
1103       return _error;
1104
1105     if ( ! refine(_sdVec[i]) )
1106       return _error;
1107   }
1108   if ( !shrink() )
1109     return _error;
1110
1111   addBoundaryElements();
1112
1113   makeGroupOfLE(); // debug
1114   debugDump.Finish();
1115
1116   return _error;
1117 }
1118
1119 //================================================================================
1120 /*!
1121  * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1122  */
1123 //================================================================================
1124
1125 bool _ViscousBuilder::findSolidsWithLayers()
1126 {
1127   // get all solids
1128   TopTools_IndexedMapOfShape allSolids;
1129   TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1130   _sdVec.reserve( allSolids.Extent());
1131
1132   SMESH_Gen* gen = _mesh->GetGen();
1133   SMESH_HypoFilter filter;
1134   for ( int i = 1; i <= allSolids.Extent(); ++i )
1135   {
1136     // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1137     SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1138     if ( !algo ) continue;
1139     // TODO: check if algo is hidden
1140     const list <const SMESHDS_Hypothesis *> & allHyps =
1141       algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1142     list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1143     const StdMeshers_ViscousLayers* viscHyp = 0;
1144     for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1145       viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1146     if ( viscHyp )
1147     {
1148       TopoDS_Shape hypShape;
1149       filter.Init( filter.Is( viscHyp ));
1150       _mesh->GetHypothesis( allSolids(i), filter, true, &hypShape );
1151
1152       _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1153                                                                 allSolids(i),
1154                                                                 /*toCreate=*/true);
1155       _sdVec.push_back( _SolidData( allSolids(i), viscHyp, hypShape, proxyMesh ));
1156       _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1157     }
1158   }
1159   if ( _sdVec.empty() )
1160     return error
1161       ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1162
1163   return true;
1164 }
1165
1166 //================================================================================
1167 /*!
1168  * \brief 
1169  */
1170 //================================================================================
1171
1172 bool _ViscousBuilder::findFacesWithLayers()
1173 {
1174   SMESH_MesherHelper helper( *_mesh );
1175   TopExp_Explorer exp;
1176   TopTools_IndexedMapOfShape solids;
1177
1178   // collect all faces to ignore defined by hyp
1179   for ( size_t i = 0; i < _sdVec.size(); ++i )
1180   {
1181     solids.Add( _sdVec[i]._solid );
1182
1183     vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1184     if ( _sdVec[i]._hyp->IsToIgnoreShapes() ) // FACEs to ignore are given
1185     {
1186       for ( size_t ii = 0; ii < ids.size(); ++ii )
1187       {
1188         const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[ii] );
1189         if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1190           _sdVec[i]._ignoreFaceIds.insert( ids[ii] );
1191       }
1192     }
1193     else // FACEs with layers are given
1194     {
1195       exp.Init( _sdVec[i]._solid, TopAbs_FACE );
1196       for ( ; exp.More(); exp.Next() )
1197       {
1198         TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1199         if ( find( ids.begin(), ids.end(), faceInd ) == ids.end() )
1200           _sdVec[i]._ignoreFaceIds.insert( faceInd );
1201       }
1202     }
1203
1204     // ignore internal FACEs if inlets and outlets are specified
1205     {
1206       TopTools_IndexedDataMapOfShapeListOfShape solidsOfFace;
1207       if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1208         TopExp::MapShapesAndAncestors( _sdVec[i]._hypShape,
1209                                        TopAbs_FACE, TopAbs_SOLID, solidsOfFace);
1210
1211       exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1212       for ( ; exp.More(); exp.Next() )
1213       {
1214         const TopoDS_Face& face = TopoDS::Face( exp.Current() );
1215         if ( helper.NbAncestors( face, *_mesh, TopAbs_SOLID ) < 2 )
1216           continue;
1217
1218         const TGeomID faceInd = getMeshDS()->ShapeToIndex( face );
1219         if ( _sdVec[i]._hyp->IsToIgnoreShapes() )
1220         {
1221           int nbSolids = solidsOfFace.FindFromKey( face ).Extent();
1222           if ( nbSolids > 1 )
1223             _sdVec[i]._ignoreFaceIds.insert( faceInd );
1224         }
1225
1226         if ( helper.IsReversedSubMesh( face ))
1227         {
1228           _sdVec[i]._reversedFaceIds.insert( faceInd );
1229         }
1230       }
1231     }
1232   }
1233
1234   // Find faces to shrink mesh on (solution 2 in issue 0020832);
1235   TopTools_IndexedMapOfShape shapes;
1236   for ( size_t i = 0; i < _sdVec.size(); ++i )
1237   {
1238     shapes.Clear();
1239     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1240     for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1241     {
1242       const TopoDS_Shape& edge = shapes(iE);
1243       // find 2 faces sharing an edge
1244       TopoDS_Shape FF[2];
1245       PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1246       while ( fIt->more())
1247       {
1248         const TopoDS_Shape* f = fIt->next();
1249         if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1250           FF[ int( !FF[0].IsNull()) ] = *f;
1251       }
1252       if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1253       // check presence of layers on them
1254       int ignore[2];
1255       for ( int j = 0; j < 2; ++j )
1256         ignore[j] = _sdVec[i]._ignoreFaceIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1257       if ( ignore[0] == ignore[1] )
1258         continue; // nothing interesting
1259       TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1260       // check presence of layers on fWOL within an adjacent SOLID
1261       PShapeIteratorPtr sIt = helper.GetAncestors( fWOL, *_mesh, TopAbs_SOLID );
1262       while ( const TopoDS_Shape* solid = sIt->next() )
1263         if ( !solid->IsSame( _sdVec[i]._solid ))
1264         {
1265           int iSolid = solids.FindIndex( *solid );
1266           int  iFace = getMeshDS()->ShapeToIndex( fWOL );
1267           if ( iSolid > 0 && !_sdVec[ iSolid-1 ]._ignoreFaceIds.count( iFace ))
1268           {
1269             _sdVec[i]._noShrinkFaces.insert( iFace );
1270             fWOL.Nullify();
1271           }
1272         }
1273       // add edge to maps
1274       if ( !fWOL.IsNull())
1275       {
1276         TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1277         _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1278       }
1279     }
1280   }
1281   // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1282   // the algo of the SOLID sharing the FACE does not support it
1283   set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1284   for ( size_t i = 0; i < _sdVec.size(); ++i )
1285   {
1286     TopTools_MapOfShape noShrinkVertices;
1287     map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1288     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1289     {
1290       const TopoDS_Shape& fWOL = e2f->second;
1291       TGeomID           edgeID = e2f->first;
1292       bool notShrinkFace = false;
1293       PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1294       while ( soIt->more())
1295       {
1296         const TopoDS_Shape* solid = soIt->next();
1297         if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1298         SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1299         if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1300         notShrinkFace = true;
1301         for ( size_t j = 0; j < _sdVec.size(); ++j )
1302         {
1303           if ( _sdVec[j]._solid.IsSame( *solid ) )
1304             if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1305               notShrinkFace = false;
1306         }
1307       }
1308       if ( notShrinkFace )
1309       {
1310         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1311         for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1312           noShrinkVertices.Add( vExp.Current() );
1313       }
1314     }
1315     // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1316     // to the found not shrinked fWOL's
1317     e2f = _sdVec[i]._shrinkShape2Shape.begin();
1318     for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1319     {
1320       TGeomID edgeID = e2f->first;
1321       TopoDS_Vertex VV[2];
1322       TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1323       if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1324       {
1325         _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1326         _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1327       }
1328       else
1329       {
1330         e2f++;
1331       }
1332     }
1333   }
1334
1335   // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1336
1337   for ( size_t i = 0; i < _sdVec.size(); ++i )
1338   {
1339     shapes.Clear();
1340     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1341     for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1342     {
1343       const TopoDS_Shape& vertex = shapes(iV);
1344       // find faces WOL sharing the vertex
1345       vector< TopoDS_Shape > facesWOL;
1346       int totalNbFaces = 0;
1347       PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1348       while ( fIt->more())
1349       {
1350         const TopoDS_Shape* f = fIt->next();
1351         if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1352         {
1353           totalNbFaces++;
1354           const int fID = getMeshDS()->ShapeToIndex( *f );
1355           if ( _sdVec[i]._ignoreFaceIds.count ( fID ) &&
1356                !_sdVec[i]._noShrinkFaces.count( fID ))
1357             facesWOL.push_back( *f );
1358         }
1359       }
1360       if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1361         continue; // no layers at this vertex or no WOL
1362       TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1363       switch ( facesWOL.size() )
1364       {
1365       case 1:
1366       {
1367         helper.SetSubShape( facesWOL[0] );
1368         if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1369         {
1370           TopoDS_Shape seamEdge;
1371           PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1372           while ( eIt->more() && seamEdge.IsNull() )
1373           {
1374             const TopoDS_Shape* e = eIt->next();
1375             if ( helper.IsRealSeam( *e ) )
1376               seamEdge = *e;
1377           }
1378           if ( !seamEdge.IsNull() )
1379           {
1380             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1381             break;
1382           }
1383         }
1384         _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1385         break;
1386       }
1387       case 2:
1388       {
1389         // find an edge shared by 2 faces
1390         PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1391         while ( eIt->more())
1392         {
1393           const TopoDS_Shape* e = eIt->next();
1394           if ( helper.IsSubShape( *e, facesWOL[0]) &&
1395                helper.IsSubShape( *e, facesWOL[1]))
1396           {
1397             _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1398           }
1399         }
1400         break;
1401       }
1402       default:
1403         return error("Not yet supported case", _sdVec[i]._index);
1404       }
1405     }
1406   }
1407
1408   // add FACEs of other SOLIDs to _ignoreFaceIds
1409   for ( size_t i = 0; i < _sdVec.size(); ++i )
1410   {
1411     shapes.Clear();
1412     TopExp::MapShapes(_sdVec[i]._solid, TopAbs_FACE, shapes);
1413
1414     for ( exp.Init( _mesh->GetShapeToMesh(), TopAbs_FACE ); exp.More(); exp.Next() )
1415     {
1416       if ( !shapes.Contains( exp.Current() ))
1417         _sdVec[i]._ignoreFaceIds.insert( getMeshDS()->ShapeToIndex( exp.Current() ));
1418     }
1419   }
1420
1421   return true;
1422 }
1423
1424 //================================================================================
1425 /*!
1426  * \brief Create the inner surface of the viscous layer and prepare data for infation
1427  */
1428 //================================================================================
1429
1430 bool _ViscousBuilder::makeLayer(_SolidData& data)
1431 {
1432   // get all sub-shapes to make layers on
1433   set<TGeomID> subIds, faceIds;
1434   subIds = data._noShrinkFaces;
1435   TopExp_Explorer exp( data._solid, TopAbs_FACE );
1436   for ( ; exp.More(); exp.Next() )
1437     {
1438       SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1439       if ( ! data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1440         faceIds.insert( fSubM->GetId() );
1441       SMESH_subMeshIteratorPtr subIt =
1442         fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1443       while ( subIt->more() )
1444         subIds.insert( subIt->next()->GetId() );
1445     }
1446
1447   // make a map to find new nodes on sub-shapes shared with other SOLID
1448   map< TGeomID, TNode2Edge* > s2neMap;
1449   map< TGeomID, TNode2Edge* >::iterator s2ne;
1450   map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1451   for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1452   {
1453     TGeomID shapeInd = s2s->first;
1454     for ( size_t i = 0; i < _sdVec.size(); ++i )
1455     {
1456       if ( _sdVec[i]._index == data._index ) continue;
1457       map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1458       if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1459            *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1460       {
1461         s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1462         break;
1463       }
1464     }
1465   }
1466
1467   // Create temporary faces and _LayerEdge's
1468
1469   dumpFunction(SMESH_Comment("makeLayers_")<<data._index); 
1470
1471   data._stepSize = Precision::Infinite();
1472   data._stepSizeNodes[0] = 0;
1473
1474   SMESH_MesherHelper helper( *_mesh );
1475   helper.SetSubShape( data._solid );
1476   helper.SetElementsOnShape(true);
1477
1478   vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1479   TNode2Edge::iterator n2e2;
1480
1481   // collect _LayerEdge's of shapes they are based on
1482   const int nbShapes = getMeshDS()->MaxShapeIndex();
1483   vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1484
1485   for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1486   {
1487     SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1488     if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1489
1490     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1491     SMESH_ProxyMesh::SubMesh* proxySub =
1492       data._proxyMesh->getFaceSubM( F, /*create=*/true);
1493
1494     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1495     while ( eIt->more() )
1496     {
1497       const SMDS_MeshElement* face = eIt->next();
1498       newNodes.resize( face->NbCornerNodes() );
1499       double faceMaxCosin = -1;
1500       for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1501       {
1502         const SMDS_MeshNode* n = face->GetNode(i);
1503         TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1504         if ( !(*n2e).second )
1505         {
1506           // add a _LayerEdge
1507           _LayerEdge* edge = new _LayerEdge();
1508           n2e->second = edge;
1509           edge->_nodes.push_back( n );
1510           const int shapeID = n->getshapeId();
1511           edgesByGeom[ shapeID ].push_back( edge );
1512
1513           // set edge data or find already refined _LayerEdge and get data from it
1514           if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1515                ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1516                ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1517           {
1518             _LayerEdge* foundEdge = (*n2e2).second;
1519             edge->Copy( *foundEdge, helper );
1520             // location of the last node is modified but we can restore
1521             // it by node position on _sWOL stored by the node
1522             const_cast< SMDS_MeshNode* >
1523               ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1524           }
1525           else
1526           {
1527             edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1528             if ( !setEdgeData( *edge, subIds, helper, data ))
1529               return false;
1530           }
1531           dumpMove(edge->_nodes.back());
1532           if ( edge->_cosin > 0.01 )
1533           {
1534             if ( edge->_cosin > faceMaxCosin )
1535               faceMaxCosin = edge->_cosin;
1536           }
1537         }
1538         newNodes[ i ] = n2e->second->_nodes.back();
1539       }
1540       // create a temporary face
1541       const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1542       proxySub->AddElement( newFace );
1543
1544       // compute inflation step size by min size of element on a convex surface
1545       if ( faceMaxCosin > 0.1 )
1546         limitStepSize( data, face, faceMaxCosin );
1547     } // loop on 2D elements on a FACE
1548   } // loop on FACEs of a SOLID
1549
1550   data._epsilon = 1e-7;
1551   if ( data._stepSize < 1. )
1552     data._epsilon *= data._stepSize;
1553
1554   // fill data._simplexTestEdges
1555   findSimplexTestEdges( data, edgesByGeom );
1556
1557   // Put _LayerEdge's into the vector data._edges
1558   if ( !sortEdges( data, edgesByGeom ))
1559     return false;
1560
1561   // Set target nodes into _Simplex and _2NearEdges of _LayerEdge's
1562   TNode2Edge::iterator n2e;
1563   for ( size_t i = 0; i < data._edges.size(); ++i )
1564   {
1565     if ( data._edges[i]->IsOnEdge())
1566       for ( int j = 0; j < 2; ++j )
1567       {
1568         if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1569           break; // _LayerEdge is shared by two _SolidData's
1570         const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1571         if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1572           return error("_LayerEdge not found by src node", data._index);
1573         n = (*n2e).second->_nodes.back();
1574         data._edges[i]->_2neibors->_edges[j] = n2e->second;
1575       }
1576     //else
1577     for ( size_t j = 0; j < data._edges[i]->_simplices.size(); ++j )
1578     {
1579       _Simplex& s = data._edges[i]->_simplices[j];
1580       s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1581       s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1582     }
1583   }
1584
1585   dumpFunctionEnd();
1586   return true;
1587 }
1588
1589 //================================================================================
1590 /*!
1591  * \brief Compute inflation step size by min size of element on a convex surface
1592  */
1593 //================================================================================
1594
1595 void _ViscousBuilder::limitStepSize( _SolidData&             data,
1596                                      const SMDS_MeshElement* face,
1597                                      const double            cosin)
1598 {
1599   int iN = 0;
1600   double minSize = 10 * data._stepSize;
1601   const int nbNodes = face->NbCornerNodes();
1602   for ( int i = 0; i < nbNodes; ++i )
1603   {
1604     const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1605     const SMDS_MeshNode* curN = face->GetNode( i );
1606     if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1607          curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1608     {
1609       double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1610       if ( dist < minSize )
1611         minSize = dist, iN = i;
1612     }
1613   }
1614   double newStep = 0.8 * minSize / cosin;
1615   if ( newStep < data._stepSize )
1616   {
1617     data._stepSize = newStep;
1618     data._stepSizeCoeff = 0.8 / cosin;
1619     data._stepSizeNodes[0] = face->GetNode( iN );
1620     data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1621   }
1622 }
1623
1624 //================================================================================
1625 /*!
1626  * \brief Compute inflation step size by min size of element on a convex surface
1627  */
1628 //================================================================================
1629
1630 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize )
1631 {
1632   if ( minSize < data._stepSize )
1633   {
1634     data._stepSize = minSize;
1635     if ( data._stepSizeNodes[0] )
1636     {
1637       double dist =
1638         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1639       data._stepSizeCoeff = data._stepSize / dist;
1640     }
1641   }
1642 }
1643
1644 //================================================================================
1645 /*!
1646  * Fill data._simplexTestEdges. These _LayerEdge's are used to stop inflation
1647  * in the case where there are no _LayerEdge's on a curved convex FACE,
1648  * as e.g. on a fillet surface with no internal nodes - issue 22580,
1649  * so that collision of viscous internal faces is not detected by check of
1650  * intersection of _LayerEdge's with the viscous internal faces.
1651  */
1652 //================================================================================
1653
1654 void _ViscousBuilder::findSimplexTestEdges( _SolidData&                    data,
1655                                             vector< vector<_LayerEdge*> >& edgesByGeom)
1656 {
1657   data._simplexTestEdges.clear();
1658
1659   SMESH_MesherHelper helper( *_mesh );
1660
1661   vector< vector<_LayerEdge*> * > ledgesOnEdges;
1662   set< const SMDS_MeshNode* > usedNodes;
1663
1664   const double minCurvature = 1. / data._hyp->GetTotalThickness();
1665
1666   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1667   {
1668     // look for a FACE with layers and w/o _LayerEdge's
1669     const vector<_LayerEdge*>& eS = edgesByGeom[iS];
1670     if ( !eS.empty() ) continue;
1671     const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1672     if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
1673     if ( data._ignoreFaceIds.count( iS )) continue;
1674
1675     const TopoDS_Face& F = TopoDS::Face( S );
1676
1677     // look for _LayerEdge's on EDGEs with null _sWOL
1678     ledgesOnEdges.clear();
1679     TopExp_Explorer eExp( F, TopAbs_EDGE );
1680     for ( ; eExp.More(); eExp.Next() )
1681     {
1682       TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1683       vector<_LayerEdge*>& eE = edgesByGeom[iE];
1684       if ( !eE.empty() && eE[0]->_sWOL.IsNull() )
1685         ledgesOnEdges.push_back( & eE );
1686     }
1687     if ( ledgesOnEdges.empty() ) continue;
1688
1689     // check FACE convexity
1690     const _LayerEdge* le = ledgesOnEdges[0]->back();
1691     gp_XY uv = helper.GetNodeUV( F, le->_nodes[0] );
1692     BRepAdaptor_Surface surf( F );
1693     BRepLProp_SLProps surfProp( surf, uv.X(), uv.Y(), 2, 1e-6 );
1694     if ( !surfProp.IsCurvatureDefined() )
1695       continue;
1696     double surfCurvature = Max( Abs( surfProp.MaxCurvature() ),
1697                                 Abs( surfProp.MinCurvature() ));
1698     if ( surfCurvature < minCurvature )
1699       continue;
1700     gp_Dir minDir, maxDir;
1701     surfProp.CurvatureDirections( maxDir, minDir );
1702     if ( F.Orientation() == TopAbs_REVERSED ) {
1703       maxDir.Reverse(); minDir.Reverse();
1704     }
1705     const gp_XYZ& inDir = le->_normal;
1706     if ( inDir * maxDir.XYZ() < 0 &&
1707          inDir * minDir.XYZ() < 0 )
1708       continue;
1709
1710     limitStepSize( data, 0.9 / surfCurvature );
1711
1712     // add _simplices to the _LayerEdge's
1713     for ( size_t iE = 0; iE < ledgesOnEdges.size(); ++iE )
1714     {
1715       const vector<_LayerEdge*>& ledges = *ledgesOnEdges[iE];
1716       for ( size_t iLE = 0; iLE < ledges.size(); ++iLE )
1717       {
1718         _LayerEdge* ledge = ledges[iLE];
1719         const SMDS_MeshNode* srcNode = ledge->_nodes[0];
1720         if ( !usedNodes.insert( srcNode ).second ) continue;
1721
1722         getSimplices( srcNode, ledge->_simplices, data._ignoreFaceIds, &data );
1723         for ( size_t i = 0; i < ledge->_simplices.size(); ++i )
1724         {
1725           usedNodes.insert( ledge->_simplices[i]._nPrev );
1726           usedNodes.insert( ledge->_simplices[i]._nNext );
1727         }
1728         data._simplexTestEdges.push_back( ledge );
1729       }
1730     }
1731   }
1732 }
1733
1734 //================================================================================
1735 /*!
1736  * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1737  */
1738 //================================================================================
1739
1740 bool _ViscousBuilder::sortEdges( _SolidData&                    data,
1741                                  vector< vector<_LayerEdge*> >& edgesByGeom)
1742 {
1743   // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1744   // boundry inclined at a sharp angle to the shape
1745
1746   list< TGeomID > shapesToSmooth;
1747   
1748   SMESH_MesherHelper helper( *_mesh );
1749   bool ok = true;
1750
1751   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1752   {
1753     vector<_LayerEdge*>& eS = edgesByGeom[iS];
1754     if ( eS.empty() ) continue;
1755     const TopoDS_Shape& S = getMeshDS()->IndexToShape( iS );
1756     bool needSmooth = false;
1757     switch ( S.ShapeType() )
1758     {
1759     case TopAbs_EDGE: {
1760
1761       bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1762       for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1763       {
1764         TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1765         vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1766         if ( eV.empty() ) continue;
1767         double cosin = eV[0]->_cosin;
1768         bool badCosin =
1769           ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1770         if ( badCosin )
1771         {
1772           gp_Vec dir1, dir2;
1773           if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1774             dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1775           else
1776             dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1777                                eV[0]->_nodes[0], helper, ok);
1778           dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1779           double angle = dir1.Angle( dir2 );
1780           cosin = cos( angle );
1781         }
1782         needSmooth = ( cosin > 0.1 );
1783       }
1784       break;
1785     }
1786     case TopAbs_FACE: {
1787
1788       for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1789       {
1790         TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1791         vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1792         if ( eE.empty() ) continue;
1793         if ( eE[0]->_sWOL.IsNull() )
1794         {
1795           for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1796             needSmooth = ( eE[i]->_cosin > 0.1 );
1797         }
1798         else
1799         {
1800           const TopoDS_Face& F1 = TopoDS::Face( S );
1801           const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1802           const TopoDS_Edge& E  = TopoDS::Edge( eExp.Current() );
1803           for ( size_t i = 0; i < eE.size() && !needSmooth; ++i )
1804           {
1805             gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1806             gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1807             double angle = dir1.Angle( dir2 );
1808             double cosin = cos( angle );
1809             needSmooth = ( cosin > 0.1 );
1810           }
1811         }
1812       }
1813       break;
1814     }
1815     case TopAbs_VERTEX:
1816       continue;
1817     default:;
1818     }
1819     if ( needSmooth )
1820     {
1821       if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1822       else                                shapesToSmooth.push_back ( iS );
1823     }
1824
1825   } // loop on edgesByGeom
1826
1827   data._edges.reserve( data._n2eMap.size() );
1828   data._endEdgeToSmooth.clear();
1829
1830   // first we put _LayerEdge's on shapes to smooth
1831   list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1832   for ( ; gIt != shapesToSmooth.end(); ++gIt )
1833   {
1834     vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1835     if ( eVec.empty() ) continue;
1836     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1837     data._endEdgeToSmooth.push_back( data._edges.size() );
1838     eVec.clear();
1839   }
1840
1841   // then the rest _LayerEdge's
1842   for ( size_t iS = 0; iS < edgesByGeom.size(); ++iS )
1843   {
1844     vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1845     data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1846     eVec.clear();
1847   }
1848
1849   return ok;
1850 }
1851
1852 //================================================================================
1853 /*!
1854  * \brief Set data of _LayerEdge needed for smoothing
1855  *  \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1856  */
1857 //================================================================================
1858
1859 bool _ViscousBuilder::setEdgeData(_LayerEdge&         edge,
1860                                   const set<TGeomID>& subIds,
1861                                   SMESH_MesherHelper& helper,
1862                                   _SolidData&         data)
1863 {
1864   SMESH_MeshEditor editor(_mesh);
1865
1866   const SMDS_MeshNode* node = edge._nodes[0]; // source node
1867   SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1868
1869   edge._len = 0;
1870   edge._2neibors = 0;
1871   edge._curvature = 0;
1872
1873   // --------------------------
1874   // Compute _normal and _cosin
1875   // --------------------------
1876
1877   edge._cosin = 0;
1878   edge._normal.SetCoord(0,0,0);
1879
1880   int totalNbFaces = 0;
1881   gp_Pnt p;
1882   gp_Vec du, dv, geomNorm;
1883   bool normOK = true;
1884
1885   TGeomID shapeInd = node->getshapeId();
1886   map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1887   bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1888   TopoDS_Shape vertEdge;
1889
1890   if ( onShrinkShape ) // one of faces the node is on has no layers
1891   {
1892     vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1893     if ( s2s->second.ShapeType() == TopAbs_EDGE )
1894     {
1895       // inflate from VERTEX along EDGE
1896       edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1897     }
1898     else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1899     {
1900       // inflate from VERTEX along FACE
1901       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1902                                  node, helper, normOK, &edge._cosin);
1903     }
1904     else
1905     {
1906       // inflate from EDGE along FACE
1907       edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1908                                  node, helper, normOK);
1909     }
1910   }
1911   else // layers are on all faces of SOLID the node is on
1912   {
1913     // find indices of geom faces the node lies on
1914     set<TGeomID> faceIds;
1915     if  ( posType == SMDS_TOP_FACE )
1916     {
1917       faceIds.insert( node->getshapeId() );
1918     }
1919     else
1920     {
1921       SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1922       while ( fIt->more() )
1923         faceIds.insert( editor.FindShape(fIt->next()));
1924     }
1925
1926     set<TGeomID>::iterator id = faceIds.begin();
1927     TopoDS_Face F;
1928     std::pair< TGeomID, gp_XYZ > id2Norm[20];
1929     for ( ; id != faceIds.end(); ++id )
1930     {
1931       const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1932       if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1933         continue;
1934       F = TopoDS::Face( s );
1935
1936       gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1937       Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1938       {
1939         gp_Dir normal;
1940         if ( GeomLib::NormEstim( surface, uv, 1e-10, normal ) < 3 )
1941         {
1942           geomNorm = normal;
1943           normOK = true;
1944         }
1945         else // hard singularity
1946         {
1947           SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1948           while ( fIt->more() )
1949           {
1950             const SMDS_MeshElement* f = fIt->next();
1951             if ( editor.FindShape( f ) == *id )
1952             {
1953               SMESH_MeshAlgos::FaceNormal( f, (gp_XYZ&) geomNorm.XYZ(), /*normalized=*/false );
1954               if ( helper.IsReversedSubMesh( F ))
1955                 geomNorm.Reverse();
1956               break;
1957             }
1958           }
1959           double size2 = geomNorm.SquareMagnitude();
1960           if ( size2 > numeric_limits<double>::min() )
1961             geomNorm /= sqrt( size2 );
1962           else
1963             normOK = false;
1964         }
1965       }
1966       if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1967         geomNorm.Reverse();
1968       id2Norm[ totalNbFaces ].first  = *id;
1969       id2Norm[ totalNbFaces ].second = geomNorm.XYZ();
1970       totalNbFaces++;
1971       edge._normal += geomNorm.XYZ();
1972     }
1973     if ( totalNbFaces == 0 )
1974       return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1975
1976     if ( totalNbFaces < 3 )
1977     {
1978       //edge._normal /= totalNbFaces;
1979     }
1980     else
1981     {
1982       edge._normal = getWeigthedNormal( node, id2Norm, totalNbFaces );
1983     }
1984
1985     switch ( posType )
1986     {
1987     case SMDS_TOP_FACE:
1988       edge._cosin = 0; break;
1989
1990     case SMDS_TOP_EDGE: {
1991       TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1992       gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1993       double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1994       edge._cosin = cos( angle );
1995       //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1996       break;
1997     }
1998     case SMDS_TOP_VERTEX: {
1999       TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
2000       gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
2001       double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
2002       edge._cosin = cos( angle );
2003       //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
2004       break;
2005     }
2006     default:
2007       return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
2008     }
2009   }
2010
2011   double normSize = edge._normal.SquareModulus();
2012   if ( normSize < numeric_limits<double>::min() )
2013     return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
2014
2015   edge._normal /= sqrt( normSize );
2016
2017   // TODO: if ( !normOK ) then get normal by mesh faces
2018
2019   // Set the rest data
2020   // --------------------
2021   if ( onShrinkShape )
2022   {
2023     edge._sWOL = (*s2s).second;
2024
2025     SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
2026     if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
2027       sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
2028
2029     // set initial position which is parameters on _sWOL in this case
2030     if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
2031     {
2032       double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
2033       edge._pos.push_back( gp_XYZ( u, 0, 0));
2034       getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
2035     }
2036     else // TopAbs_FACE
2037     {
2038       gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
2039       edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2040       getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
2041     }
2042   }
2043   else
2044   {
2045     edge._pos.push_back( SMESH_TNodeXYZ( node ));
2046
2047     if ( posType == SMDS_TOP_FACE )
2048     {
2049       getSimplices( node, edge._simplices, data._ignoreFaceIds, &data );
2050       double avgNormProj = 0, avgLen = 0;
2051       for ( size_t i = 0; i < edge._simplices.size(); ++i )
2052       {
2053         gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
2054         avgNormProj += edge._normal * vec;
2055         avgLen += vec.Modulus();
2056       }
2057       avgNormProj /= edge._simplices.size();
2058       avgLen /= edge._simplices.size();
2059       edge._curvature = _Curvature::New( avgNormProj, avgLen );
2060     }
2061   }
2062
2063   // Set neighbour nodes for a _LayerEdge based on EDGE
2064
2065   if ( posType == SMDS_TOP_EDGE /*||
2066        ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
2067   {
2068     edge._2neibors = new _2NearEdges;
2069     // target node instead of source ones will be set later
2070     if ( ! findNeiborsOnEdge( &edge,
2071                               edge._2neibors->_nodes[0],
2072                               edge._2neibors->_nodes[1],
2073                               data))
2074       return false;
2075     edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
2076                              edge._2neibors->_nodes[1],
2077                              helper);
2078   }
2079
2080   edge.SetCosin( edge._cosin ); // to update edge._lenFactor
2081
2082   return true;
2083 }
2084
2085 //================================================================================
2086 /*!
2087  * \brief Return normal at a node weighted with angles taken by FACEs
2088  *  \param [in] n - the node
2089  *  \param [in] fId2Normal - FACE ids and normals
2090  *  \param [in] nbFaces - nb of FACEs meeting at the node
2091  *  \return gp_XYZ - computed normal
2092  */
2093 //================================================================================
2094
2095 gp_XYZ _ViscousBuilder::getWeigthedNormal( const SMDS_MeshNode*         n,
2096                                            std::pair< TGeomID, gp_XYZ > fId2Normal[],
2097                                            const int                    nbFaces )
2098 {
2099   gp_XYZ resNorm(0,0,0);
2100   TopoDS_Shape V = SMESH_MesherHelper::GetSubShapeByNode( n, getMeshDS() );
2101   if ( V.ShapeType() != TopAbs_VERTEX )
2102   {
2103     for ( int i = 0; i < nbFaces; ++i )
2104       resNorm += fId2Normal[i].second / nbFaces ;
2105     return resNorm;
2106   }
2107
2108   double angles[30];
2109   for ( int i = 0; i < nbFaces; ++i )
2110   {
2111     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( fId2Normal[i].first ));
2112
2113     // look for two EDGEs shared by F and other FACEs within fId2Normal
2114     TopoDS_Edge ee[2];
2115     int nbE = 0;
2116     PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V, *_mesh, TopAbs_EDGE );
2117     while ( const TopoDS_Shape* E = eIt->next() )
2118     {
2119       if ( !SMESH_MesherHelper::IsSubShape( *E, F ))
2120         continue;
2121       bool isSharedEdge = false;
2122       for ( int j = 0; j < nbFaces && !isSharedEdge; ++j )
2123       {
2124         if ( i == j ) continue;
2125         const TopoDS_Shape& otherF = getMeshDS()->IndexToShape( fId2Normal[j].first );
2126         isSharedEdge = SMESH_MesherHelper::IsSubShape( *E, otherF );
2127       }
2128       if ( !isSharedEdge )
2129         continue;
2130       ee[ nbE ] = TopoDS::Edge( *E );
2131       ee[ nbE ].Orientation( SMESH_MesherHelper::GetSubShapeOri( F, *E ));
2132       if ( ++nbE == 2 )
2133         break;
2134     }
2135
2136     // get an angle between the two EDGEs
2137     angles[i] = 0;
2138     if ( nbE < 1 ) continue;
2139     if ( nbE == 1 )
2140     {
2141       ee[ 1 ] == ee[ 0 ];
2142     }
2143     else
2144     {
2145       TopoDS_Vertex v10 = SMESH_MesherHelper::IthVertex( 1, ee[ 0 ]);
2146       TopoDS_Vertex v01 = SMESH_MesherHelper::IthVertex( 0, ee[ 1 ]);
2147       if ( !v10.IsSame( v01 ))
2148         std::swap( ee[0], ee[1] );
2149     }
2150     angles[i] = SMESH_MesherHelper::GetAngle( ee[0], ee[1], F );
2151   }
2152
2153   // compute a weighted normal
2154   double sumAngle = 0;
2155   for ( int i = 0; i < nbFaces; ++i )
2156   {
2157     angles[i] = ( angles[i] > 2*M_PI )  ?  0  :  M_PI - angles[i];
2158     sumAngle += angles[i];
2159   }
2160   for ( int i = 0; i < nbFaces; ++i )
2161     resNorm += angles[i] / sumAngle * fId2Normal[i].second;
2162
2163   return resNorm;
2164 }
2165
2166 //================================================================================
2167 /*!
2168  * \brief Find 2 neigbor nodes of a node on EDGE
2169  */
2170 //================================================================================
2171
2172 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge*     edge,
2173                                         const SMDS_MeshNode*& n1,
2174                                         const SMDS_MeshNode*& n2,
2175                                         _SolidData&           data)
2176 {
2177   const SMDS_MeshNode* node = edge->_nodes[0];
2178   const int shapeInd = node->getshapeId();
2179   SMESHDS_SubMesh* edgeSM = 0;
2180   if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
2181   {
2182     
2183     edgeSM = getMeshDS()->MeshElements( shapeInd );
2184     if ( !edgeSM || edgeSM->NbElements() == 0 )
2185       return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
2186   }
2187   int iN = 0;
2188   n2 = 0;
2189   SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
2190   while ( eIt->more() && !n2 )
2191   {
2192     const SMDS_MeshElement* e = eIt->next();
2193     const SMDS_MeshNode*   nNeibor = e->GetNode( 0 );
2194     if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
2195     if ( edgeSM )
2196     {
2197       if (!edgeSM->Contains(e)) continue;
2198     }
2199     else
2200     {
2201       TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
2202       if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
2203     }
2204     ( iN++ ? n2 : n1 ) = nNeibor;
2205   }
2206   if ( !n2 )
2207     return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
2208   return true;
2209 }
2210
2211 //================================================================================
2212 /*!
2213  * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
2214  */
2215 //================================================================================
2216
2217 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
2218                                      const SMDS_MeshNode* n2,
2219                                      SMESH_MesherHelper&  helper)
2220 {
2221   if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
2222     return;
2223
2224   gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
2225   gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
2226   gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
2227
2228   // Set _curvature
2229
2230   double sumLen = vec1.Modulus() + vec2.Modulus();
2231   _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
2232   _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
2233   double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
2234   double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
2235   if ( _curvature ) delete _curvature;
2236   _curvature = _Curvature::New( avgNormProj, avgLen );
2237 #ifdef __myDEBUG
2238 //     if ( _curvature )
2239 //       cout << _nodes[0]->GetID()
2240 //            << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
2241 //            << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
2242 //            << _curvature->lenDelta(0) << endl;
2243 #endif
2244
2245   // Set _plnNorm
2246
2247   if ( _sWOL.IsNull() )
2248   {
2249     TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
2250     gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
2251     gp_XYZ plnNorm = dirE ^ _normal;
2252     double proj0 = plnNorm * vec1;
2253     double proj1 = plnNorm * vec2;
2254     if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
2255     {
2256       if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
2257       _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
2258     }
2259   }
2260 }
2261
2262 //================================================================================
2263 /*!
2264  * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
2265  * this and other _LayerEdge's are inflated along a FACE or an EDGE
2266  */
2267 //================================================================================
2268
2269 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
2270 {
2271   _nodes     = other._nodes;
2272   _normal    = other._normal;
2273   _len       = 0;
2274   _lenFactor = other._lenFactor;
2275   _cosin     = other._cosin;
2276   _sWOL      = other._sWOL;
2277   _2neibors  = other._2neibors;
2278   _curvature = 0; std::swap( _curvature, other._curvature );
2279   _2neibors  = 0; std::swap( _2neibors,  other._2neibors );
2280
2281   if ( _sWOL.ShapeType() == TopAbs_EDGE )
2282   {
2283     double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
2284     _pos.push_back( gp_XYZ( u, 0, 0));
2285   }
2286   else // TopAbs_FACE
2287   {
2288     gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
2289     _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
2290   }
2291 }
2292
2293 //================================================================================
2294 /*!
2295  * \brief Set _cosin and _lenFactor
2296  */
2297 //================================================================================
2298
2299 void _LayerEdge::SetCosin( double cosin )
2300 {
2301   _cosin = cosin;
2302   _lenFactor = ( Abs( _cosin ) > 0.1 ) ?  1./sqrt(1-_cosin*_cosin) : 1.0;
2303 }
2304
2305 //================================================================================
2306 /*!
2307  * \brief Fills a vector<_Simplex > 
2308  */
2309 //================================================================================
2310
2311 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
2312                                     vector<_Simplex>&    simplices,
2313                                     const set<TGeomID>&  ingnoreShapes,
2314                                     const _SolidData*    dataToCheckOri,
2315                                     const bool           toSort)
2316 {
2317   simplices.clear();
2318   SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
2319   while ( fIt->more() )
2320   {
2321     const SMDS_MeshElement* f = fIt->next();
2322     const TGeomID    shapeInd = f->getshapeId();
2323     if ( ingnoreShapes.count( shapeInd )) continue;
2324     const int nbNodes = f->NbCornerNodes();
2325     const int  srcInd = f->GetNodeIndex( node );
2326     const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
2327     const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
2328     const SMDS_MeshNode* nOpp  = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
2329     if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
2330       std::swap( nPrev, nNext );
2331     simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
2332   }
2333
2334   if ( toSort )
2335   {
2336     vector<_Simplex> sortedSimplices( simplices.size() );
2337     sortedSimplices[0] = simplices[0];
2338     int nbFound = 0;
2339     for ( size_t i = 1; i < simplices.size(); ++i )
2340     {
2341       for ( size_t j = 1; j < simplices.size(); ++j )
2342         if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
2343         {
2344           sortedSimplices[i] = simplices[j];
2345           nbFound++;
2346           break;
2347         }
2348     }
2349     if ( nbFound == simplices.size() - 1 )
2350       simplices.swap( sortedSimplices );
2351   }
2352 }
2353
2354 //================================================================================
2355 /*!
2356  * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2357  */
2358 //================================================================================
2359
2360 void _ViscousBuilder::makeGroupOfLE()
2361 {
2362 #ifdef _DEBUG_
2363   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
2364   {
2365     if ( _sdVec[i]._edges.empty() ) continue;
2366 //     string name = SMESH_Comment("_LayerEdge's_") << i;
2367 //     int id;
2368 //     SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2369 //     SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2370 //     SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2371
2372     dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2373     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2374     {
2375       _LayerEdge* le = _sdVec[i]._edges[j];
2376       for ( size_t iN = 1; iN < le->_nodes.size(); ++iN )
2377         dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2378                 << ", " << le->_nodes[iN]->GetID() <<"])");
2379       //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2380     }
2381     dumpFunctionEnd();
2382
2383     dumpFunction( SMESH_Comment("makeNormals") << i );
2384     for ( size_t j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2385     {
2386       _LayerEdge& edge = *_sdVec[i]._edges[j];
2387       SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2388       nXYZ += edge._normal * _sdVec[i]._stepSize;
2389       dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2390               << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2391     }
2392     dumpFunctionEnd();
2393
2394 //     name = SMESH_Comment("tmp_faces ") << i;
2395 //     g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2396 //     gDS = (SMESHDS_Group*)g->GetGroupDS();
2397 //     SMESH_MeshEditor editor( _mesh );
2398     dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2399     TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2400     for ( ; fExp.More(); fExp.Next() )
2401     {
2402       if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2403       {
2404         SMDS_ElemIteratorPtr fIt = sm->GetElements();
2405         while ( fIt->more())
2406         {
2407           const SMDS_MeshElement* e = fIt->next();
2408           SMESH_Comment cmd("mesh.AddFace([");
2409           for ( int j=0; j < e->NbCornerNodes(); ++j )
2410             cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2411           dumpCmd( cmd );
2412           //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2413           //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2414         }
2415       }
2416     }
2417     dumpFunctionEnd();
2418   }
2419 #endif
2420 }
2421
2422 //================================================================================
2423 /*!
2424  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2425  */
2426 //================================================================================
2427
2428 bool _ViscousBuilder::inflate(_SolidData& data)
2429 {
2430   SMESH_MesherHelper helper( *_mesh );
2431
2432   // Limit inflation step size by geometry size found by itersecting
2433   // normals of _LayerEdge's with mesh faces
2434   double geomSize = Precision::Infinite(), intersecDist;
2435   auto_ptr<SMESH_ElementSearcher> searcher
2436     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2437                                            data._proxyMesh->GetFaces( data._solid )) );
2438   for ( size_t i = 0; i < data._edges.size(); ++i )
2439   {
2440     if ( data._edges[i]->IsOnEdge() ) continue;
2441     data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2442     if ( geomSize > intersecDist && intersecDist > 0 )
2443       geomSize = intersecDist;
2444   }
2445   if ( data._stepSize > 0.3 * geomSize )
2446     limitStepSize( data, 0.3 * geomSize );
2447
2448   const double tgtThick = data._hyp->GetTotalThickness();
2449   if ( data._stepSize > tgtThick )
2450     limitStepSize( data, tgtThick );
2451
2452   if ( data._stepSize < 1. )
2453     data._epsilon = data._stepSize * 1e-7;
2454
2455 #ifdef __myDEBUG
2456   cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2457 #endif
2458
2459   double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2460   int nbSteps = 0, nbRepeats = 0;
2461   while ( 1.01 * avgThick < tgtThick )
2462   {
2463     // new target length
2464     curThick += data._stepSize;
2465     if ( curThick > tgtThick )
2466     {
2467       curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2468       nbRepeats++;
2469     }
2470
2471     // Elongate _LayerEdge's
2472     dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2473     for ( size_t i = 0; i < data._edges.size(); ++i )
2474     {
2475       data._edges[i]->SetNewLength( curThick, helper );
2476     }
2477     dumpFunctionEnd();
2478
2479     if ( !nbSteps )
2480       if ( !updateNormals( data, helper ) )
2481         return false;
2482
2483     // Improve and check quality
2484     if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2485     {
2486       if ( nbSteps > 0 )
2487       {
2488         dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2489         for ( size_t i = 0; i < data._edges.size(); ++i )
2490         {
2491           data._edges[i]->InvalidateStep( nbSteps+1 );
2492         }
2493         dumpFunctionEnd();
2494       }
2495       break; // no more inflating possible
2496     }
2497     nbSteps++;
2498
2499     // Evaluate achieved thickness
2500     avgThick = 0;
2501     for ( size_t i = 0; i < data._edges.size(); ++i )
2502       avgThick += data._edges[i]->_len;
2503     avgThick /= data._edges.size();
2504 #ifdef __myDEBUG
2505     cout << "-- Thickness " << avgThick << " reached" << endl;
2506 #endif
2507
2508     if ( distToIntersection < avgThick*1.5 )
2509     {
2510 #ifdef __myDEBUG
2511       cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2512            << avgThick << " ) * 1.5" << endl;
2513 #endif
2514       break;
2515     }
2516     // new step size
2517     limitStepSize( data, 0.25 * distToIntersection );
2518     if ( data._stepSizeNodes[0] )
2519       data._stepSize = data._stepSizeCoeff *
2520         SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2521   }
2522
2523   if (nbSteps == 0 )
2524     return error("failed at the very first inflation step", data._index);
2525
2526   return true;
2527 }
2528
2529 //================================================================================
2530 /*!
2531  * \brief Improve quality of layer inner surface and check intersection
2532  */
2533 //================================================================================
2534
2535 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2536                                      const int   nbSteps,
2537                                      double &    distToIntersection)
2538 {
2539   if ( data._endEdgeToSmooth.empty() )
2540     return true; // no shapes needing smoothing
2541
2542   bool moved, improved;
2543
2544   SMESH_MesherHelper helper(*_mesh);
2545   Handle(Geom_Surface) surface;
2546   TopoDS_Face F;
2547
2548   int iBeg, iEnd = 0;
2549   for ( size_t iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2550   {
2551     iBeg = iEnd;
2552     iEnd = data._endEdgeToSmooth[ iS ];
2553
2554     if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2555          data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2556     {
2557       if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2558         F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2559         helper.SetSubShape( F );
2560         surface = BRep_Tool::Surface( F );
2561       }
2562     }
2563     else
2564     {
2565       F.Nullify(); surface.Nullify();
2566     }
2567     TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2568
2569     if ( data._edges[ iBeg ]->IsOnEdge() )
2570     { 
2571       dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2572
2573       // try a simple solution on an analytic EDGE
2574       if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2575       {
2576         // smooth on EDGE's
2577         int step = 0;
2578         do {
2579           moved = false;
2580           for ( int i = iBeg; i < iEnd; ++i )
2581           {
2582             moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2583           }
2584           dumpCmd( SMESH_Comment("# end step ")<<step);
2585         }
2586         while ( moved && step++ < 5 );
2587         //cout << " NB STEPS: " << step << endl;
2588       }
2589       dumpFunctionEnd();
2590     }
2591     else
2592     {
2593       // smooth on FACE's
2594       int step = 0, stepLimit = 5, badNb = 0; moved = true;
2595       while (( ++step <= stepLimit && moved ) || improved )
2596       {
2597         dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2598                      <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2599         int oldBadNb = badNb;
2600         badNb = 0;
2601         moved = false;
2602         for ( int i = iBeg; i < iEnd; ++i )
2603           moved |= data._edges[i]->Smooth(badNb);
2604         improved = ( badNb < oldBadNb );
2605
2606         // issue 22576. no bad faces but still there are intersections to fix
2607         if ( improved && badNb == 0 )
2608           stepLimit = step + 3;
2609
2610         dumpFunctionEnd();
2611       }
2612       if ( badNb > 0 )
2613       {
2614 #ifdef __myDEBUG
2615         for ( int i = iBeg; i < iEnd; ++i )
2616         {
2617           _LayerEdge* edge = data._edges[i];
2618           SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2619           for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2620             if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2621             {
2622               cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2623                    << " "<< edge->_simplices[j]._nPrev->GetID()
2624                    << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2625               return false;
2626             }
2627         }
2628 #endif
2629         return false;
2630       }
2631     }
2632   } // loop on shapes to smooth
2633
2634   // Check orientation of simplices of _simplexTestEdges
2635   for ( size_t i = 0; i < data._simplexTestEdges.size(); ++i )
2636   {
2637     const _LayerEdge* edge = data._simplexTestEdges[i];
2638     SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2639     for ( size_t j = 0; j < edge->_simplices.size(); ++j )
2640       if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2641       {
2642 #ifdef __myDEBUG
2643         cout << "Bad simplex of _simplexTestEdges ("
2644              << " "<< edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2645              << " "<< edge->_simplices[j]._nPrev->GetID()
2646              << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2647 #endif
2648         return false;
2649       }
2650   }
2651
2652   // Check if the last segments of _LayerEdge intersects 2D elements;
2653   // checked elements are either temporary faces or faces on surfaces w/o the layers
2654
2655   auto_ptr<SMESH_ElementSearcher> searcher
2656     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2657                                            data._proxyMesh->GetFaces( data._solid )) );
2658
2659   distToIntersection = Precision::Infinite();
2660   double dist;
2661   const SMDS_MeshElement* intFace = 0;
2662 #ifdef __myDEBUG
2663   const SMDS_MeshElement* closestFace = 0;
2664   int iLE = 0;
2665 #endif
2666   for ( size_t i = 0; i < data._edges.size(); ++i )
2667   {
2668     if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2669       return false;
2670     if ( distToIntersection > dist )
2671     {
2672       distToIntersection = dist;
2673 #ifdef __myDEBUG
2674       iLE = i;
2675       closestFace = intFace;
2676 #endif
2677     }
2678   }
2679 #ifdef __myDEBUG
2680   if ( closestFace )
2681   {
2682     SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2683     cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2684          << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2685          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2686          << ") distance = " << distToIntersection<< endl;
2687   }
2688 #endif
2689
2690   return true;
2691 }
2692
2693 //================================================================================
2694 /*!
2695  * \brief Return a curve of the EDGE to be used for smoothing and arrange
2696  *        _LayerEdge's to be in a consequent order
2697  */
2698 //================================================================================
2699
2700 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge&    E,
2701                                                const int             iFrom,
2702                                                const int             iTo,
2703                                                Handle(Geom_Surface)& surface,
2704                                                const TopoDS_Face&    F,
2705                                                SMESH_MesherHelper&   helper)
2706 {
2707   TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2708
2709   map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2710
2711   if ( i2curve == _edge2curve.end() )
2712   {
2713     // sort _LayerEdge's by position on the EDGE
2714     {
2715       map< double, _LayerEdge* > u2edge;
2716       for ( int i = iFrom; i < iTo; ++i )
2717         u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2718
2719       ASSERT( u2edge.size() == iTo - iFrom );
2720       map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2721       for ( int i = iFrom; i < iTo; ++i, ++u2e )
2722         _edges[i] = u2e->second;
2723
2724       // set _2neibors according to the new order
2725       for ( int i = iFrom; i < iTo-1; ++i )
2726         if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2727           _edges[i]->_2neibors->reverse();
2728       if ( u2edge.size() > 1 &&
2729            _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2730         _edges[iTo-1]->_2neibors->reverse();
2731     }
2732
2733     SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2734
2735     TopLoc_Location loc; double f,l;
2736
2737     Handle(Geom_Line)   line;
2738     Handle(Geom_Circle) circle;
2739     bool isLine, isCirc;
2740     if ( F.IsNull() ) // 3D case
2741     {
2742       // check if the EDGE is a line
2743       Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2744       if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2745         curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2746
2747       line   = Handle(Geom_Line)::DownCast( curve );
2748       circle = Handle(Geom_Circle)::DownCast( curve );
2749       isLine = (!line.IsNull());
2750       isCirc = (!circle.IsNull());
2751
2752       if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2753       {
2754         Bnd_B3d bndBox;
2755         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2756         while ( nIt->more() )
2757           bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2758         gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2759
2760         SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2761         SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2762         const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2763         for ( int i = 0; i < 3 && !isLine; ++i )
2764           isLine = ( size.Coord( i+1 ) <= lineTol );
2765       }
2766       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2767       {
2768         // TODO
2769       }
2770     }
2771     else // 2D case
2772     {
2773       // check if the EDGE is a line
2774       Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2775       if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2776         curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2777
2778       Handle(Geom2d_Line)   line2d   = Handle(Geom2d_Line)::DownCast( curve );
2779       Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2780       isLine = (!line2d.IsNull());
2781       isCirc = (!circle2d.IsNull());
2782
2783       if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2784       {
2785         Bnd_B2d bndBox;
2786         SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2787         while ( nIt->more() )
2788           bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2789         gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2790
2791         const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2792         for ( int i = 0; i < 2 && !isLine; ++i )
2793           isLine = ( size.Coord( i+1 ) <= lineTol );
2794       }
2795       if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2796       {
2797         // TODO
2798       }
2799       if ( isLine )
2800       {
2801         line = new Geom_Line( gp::OX() ); // only type does matter
2802       }
2803       else if ( isCirc )
2804       {
2805         gp_Pnt2d p = circle2d->Location();
2806         gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2807         circle = new Geom_Circle( ax, 1.); // only center position does matter
2808       }
2809     }
2810
2811     Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2812     if ( isLine )
2813       res = line;
2814     else if ( isCirc )
2815       res = circle;
2816
2817     return res;
2818   }
2819   return i2curve->second;
2820 }
2821
2822 //================================================================================
2823 /*!
2824  * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2825  */
2826 //================================================================================
2827
2828 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData&           data,
2829                                           const int             iFrom,
2830                                           const int             iTo,
2831                                           Handle(Geom_Surface)& surface,
2832                                           const TopoDS_Face&    F,
2833                                           SMESH_MesherHelper&   helper)
2834 {
2835   TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2836                                              helper.GetMeshDS());
2837   TopoDS_Edge E = TopoDS::Edge( S );
2838
2839   Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2840   if ( curve.IsNull() ) return false;
2841
2842   // compute a relative length of segments
2843   vector< double > len( iTo-iFrom+1 );
2844   {
2845     double curLen, prevLen = len[0] = 1.0;
2846     for ( int i = iFrom; i < iTo; ++i )
2847     {
2848       curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2849       len[i-iFrom+1] = len[i-iFrom] + curLen;
2850       prevLen = curLen;
2851     }
2852   }
2853
2854   if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2855   {
2856     if ( F.IsNull() ) // 3D
2857     {
2858       SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2859       SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2860       for ( int i = iFrom; i < iTo; ++i )
2861       {
2862         double r = len[i-iFrom] / len.back();
2863         gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2864         data._edges[i]->_pos.back() = newPos;
2865         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2866         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2867         dumpMove( tgtNode );
2868       }
2869     }
2870     else
2871     {
2872       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2873       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2874       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2875            data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2876       {
2877         int iPeriodic = helper.GetPeriodicIndex();
2878         if ( iPeriodic == 1 || iPeriodic == 2 )
2879         {
2880           uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2881           if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2882             std::swap( uv0, uv1 );
2883         }
2884       }
2885       const gp_XY rangeUV = uv1 - uv0;
2886       for ( int i = iFrom; i < iTo; ++i )
2887       {
2888         double r = len[i-iFrom] / len.back();
2889         gp_XY newUV = uv0 + r * rangeUV;
2890         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2891
2892         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2893         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2894         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2895         dumpMove( tgtNode );
2896
2897         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2898         pos->SetUParameter( newUV.X() );
2899         pos->SetVParameter( newUV.Y() );
2900       }
2901     }
2902     return true;
2903   }
2904
2905   if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2906   {
2907     Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2908     gp_Pnt center3D = circle->Location();
2909
2910     if ( F.IsNull() ) // 3D
2911     {
2912       if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2913            data._edges[iTo-1]->_2neibors->_nodes[1] )
2914         return true; // closed EDGE - nothing to do
2915
2916       return false; // TODO ???
2917     }
2918     else // 2D
2919     {
2920       const gp_XY center( center3D.X(), center3D.Y() );
2921
2922       gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2923       gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2924       gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2925       gp_Vec2d vec0( center, uv0 );
2926       gp_Vec2d vecM( center, uvM );
2927       gp_Vec2d vec1( center, uv1 );
2928       double uLast = vec0.Angle( vec1 ); // -PI - +PI
2929       double uMidl = vec0.Angle( vecM );
2930       if ( uLast * uMidl < 0. )
2931         uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2932       const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2933
2934       gp_Ax2d   axis( center, vec0 );
2935       gp_Circ2d circ( axis, radius );
2936       for ( int i = iFrom; i < iTo; ++i )
2937       {
2938         double    newU = uLast * len[i-iFrom] / len.back();
2939         gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2940         data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2941
2942         gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2943         SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2944         tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2945         dumpMove( tgtNode );
2946
2947         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2948         pos->SetUParameter( newUV.X() );
2949         pos->SetVParameter( newUV.Y() );
2950       }
2951     }
2952     return true;
2953   }
2954
2955   return false;
2956 }
2957
2958 //================================================================================
2959 /*!
2960  * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2961  * _LayerEdge's on neighbor EDGE's
2962  */
2963 //================================================================================
2964
2965 bool _ViscousBuilder::updateNormals( _SolidData&         data,
2966                                      SMESH_MesherHelper& helper )
2967 {
2968   // make temporary quadrangles got by extrusion of
2969   // mesh edges along _LayerEdge._normal's
2970
2971   vector< const SMDS_MeshElement* > tmpFaces;
2972   {
2973     set< SMESH_TLink > extrudedLinks; // contains target nodes
2974     vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2975
2976     dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2977     for ( size_t i = 0; i < data._edges.size(); ++i )
2978     {
2979       _LayerEdge* edge = data._edges[i];
2980       if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2981       const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2982       for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2983       {
2984         const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2985         pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2986           extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2987         if ( !link_isnew.second )
2988         {
2989           extrudedLinks.erase( link_isnew.first );
2990           continue; // already extruded and will no more encounter
2991         }
2992         // look for a _LayerEdge containg tgt2
2993 //         _LayerEdge* neiborEdge = 0;
2994 //         size_t di = 0; // check _edges[i+di] and _edges[i-di]
2995 //         while ( !neiborEdge && ++di <= data._edges.size() )
2996 //         {
2997 //           if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2998 //             neiborEdge = data._edges[i+di];
2999 //           else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
3000 //             neiborEdge = data._edges[i-di];
3001 //         }
3002 //         if ( !neiborEdge )
3003 //           return error("updateNormals(): neighbor _LayerEdge not found", data._index);
3004         _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
3005
3006         TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
3007         tmpFaces.push_back( f );
3008
3009         dumpCmd(SMESH_Comment("mesh.AddFace([ ")
3010                 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
3011                 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
3012       }
3013     }
3014     dumpFunctionEnd();
3015   }
3016   // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
3017   // Perform two loops on _LayerEdge on EDGE's:
3018   // 1) to find and fix intersection
3019   // 2) to check that no new intersection appears as result of 1)
3020
3021   SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
3022                                                             tmpFaces.end()));
3023   auto_ptr<SMESH_ElementSearcher> searcher
3024     ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
3025
3026   // 1) Find intersections
3027   double dist;
3028   const SMDS_MeshElement* face;
3029   typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
3030   TLEdge2LEdgeSet edge2CloseEdge;
3031
3032   const double eps = data._epsilon * data._epsilon;
3033   for ( size_t i = 0; i < data._edges.size(); ++i )
3034   {
3035     _LayerEdge* edge = data._edges[i];
3036     if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
3037     if ( edge->FindIntersection( *searcher, dist, eps, &face ))
3038     {
3039       const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
3040       set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
3041       ee.insert( f->_le1 );
3042       ee.insert( f->_le2 );
3043       if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() ) 
3044         edge2CloseEdge[ f->_le1 ].insert( edge );
3045       if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() ) 
3046         edge2CloseEdge[ f->_le2 ].insert( edge );
3047     }
3048   }
3049
3050   // Set _LayerEdge._normal
3051
3052   if ( !edge2CloseEdge.empty() )
3053   {
3054     dumpFunction(SMESH_Comment("updateNormals")<<data._index);
3055
3056     TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
3057     for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
3058     {
3059       _LayerEdge* edge1       = e2ee->first;
3060       _LayerEdge* edge2       = 0;
3061       set< _LayerEdge*, _LayerEdgeCmp >& ee  = e2ee->second;
3062
3063       // find EDGEs the edges reside
3064       TopoDS_Edge E1, E2;
3065       TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
3066       if ( S.ShapeType() != TopAbs_EDGE )
3067         continue; // TODO: find EDGE by VERTEX
3068       E1 = TopoDS::Edge( S );
3069       set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
3070       while ( E2.IsNull() && eIt != ee.end())
3071       {
3072         _LayerEdge* e2 = *eIt++;
3073         TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
3074         if ( S.ShapeType() == TopAbs_EDGE )
3075           E2 = TopoDS::Edge( S ), edge2 = e2;
3076       }
3077       if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
3078
3079       // find 3 FACEs sharing 2 EDGEs
3080
3081       TopoDS_Face FF1[2], FF2[2];
3082       PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
3083       while ( fIt->more() && FF1[1].IsNull())
3084       {
3085         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3086         if ( helper.IsSubShape( *F, data._solid))
3087           FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
3088       }
3089       fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
3090       while ( fIt->more() && FF2[1].IsNull())
3091       {
3092         const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
3093         if ( helper.IsSubShape( *F, data._solid))
3094           FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
3095       }
3096       // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
3097       if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
3098         std::swap( FF1[0], FF1[1] );
3099       if ( FF2[0].IsSame( FF1[0]) )
3100         std::swap( FF2[0], FF2[1] );
3101       if ( FF1[0].IsNull() || FF2[0].IsNull() )
3102         continue;
3103
3104       // get a new normal for edge1
3105       bool ok;
3106       gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
3107       if ( edge1->_cosin < 0 )
3108         dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
3109       if ( edge2->_cosin < 0 )
3110         dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
3111       // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3112       // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
3113       // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3114       // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3115       // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3116       // newNorm.Normalize();
3117
3118       double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3119       double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
3120       gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
3121       newNorm.Normalize();
3122
3123       edge1->_normal = newNorm.XYZ();
3124
3125       // update data of edge1 depending on _normal
3126       const SMDS_MeshNode *n1, *n2;
3127       n1 = edge1->_2neibors->_edges[0]->_nodes[0];
3128       n2 = edge1->_2neibors->_edges[1]->_nodes[0];
3129       //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
3130       //  continue;
3131       edge1->SetDataByNeighbors( n1, n2, helper );
3132       gp_Vec dirInFace;
3133       if ( edge1->_cosin < 0 )
3134         dirInFace = dir1;
3135       else
3136         getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
3137       double angle = dir1.Angle( edge1->_normal ); // [0,PI]
3138       edge1->SetCosin( cos( angle ));
3139
3140       // limit data._stepSize
3141       if ( edge1->_cosin > 0.1 )
3142       {
3143         SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
3144         while ( fIt->more() )
3145           limitStepSize( data, fIt->next(), edge1->_cosin );
3146       }
3147       // set new XYZ of target node
3148       edge1->InvalidateStep( 1 );
3149       edge1->_len = 0;
3150       edge1->SetNewLength( data._stepSize, helper );
3151     }
3152
3153     // Update normals and other dependent data of not intersecting _LayerEdge's
3154     // neighboring the intersecting ones
3155
3156     for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
3157     {
3158       _LayerEdge* edge1 = e2ee->first;
3159       if ( !edge1->_2neibors )
3160         continue;
3161       for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
3162       {
3163         _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
3164         if ( edge2CloseEdge.count ( neighbor ))
3165           continue; // j-th neighbor is also intersected
3166         _LayerEdge* prevEdge = edge1;
3167         const int nbSteps = 6;
3168         for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
3169         {
3170           if ( !neighbor->_2neibors )
3171             break; // neighbor is on VERTEX
3172           int iNext = 0;
3173           _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
3174           if ( nextEdge == prevEdge )
3175             nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
3176 //           const double&  wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
3177 //           const double&  wgtNext = neighbor->_2neibors->_wgt[iNext];
3178           double r = double(step-1)/nbSteps;
3179           if ( !nextEdge->_2neibors )
3180             r = 0.5;
3181
3182           gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
3183           newNorm.Normalize();
3184
3185           neighbor->_normal = newNorm;
3186           neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
3187           neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
3188
3189           neighbor->InvalidateStep( 1 );
3190           neighbor->_len = 0;
3191           neighbor->SetNewLength( data._stepSize, helper );
3192
3193           // goto the next neighbor
3194           prevEdge = neighbor;
3195           neighbor = nextEdge;
3196         }
3197       }
3198     }
3199     dumpFunctionEnd();
3200   }
3201   // 2) Check absence of intersections
3202   // TODO?
3203
3204   for ( size_t i = 0 ; i < tmpFaces.size(); ++i )
3205     delete tmpFaces[i];
3206
3207   return true;
3208 }
3209
3210 //================================================================================
3211 /*!
3212  * \brief Looks for intersection of it's last segment with faces
3213  *  \param distance - returns shortest distance from the last node to intersection
3214  */
3215 //================================================================================
3216
3217 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher&   searcher,
3218                                    double &                 distance,
3219                                    const double&            epsilon,
3220                                    const SMDS_MeshElement** face)
3221 {
3222   vector< const SMDS_MeshElement* > suspectFaces;
3223   double segLen;
3224   gp_Ax1 lastSegment = LastSegment(segLen);
3225   searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
3226
3227   bool segmentIntersected = false;
3228   distance = Precision::Infinite();
3229   int iFace = -1; // intersected face
3230   for ( size_t j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
3231   {
3232     const SMDS_MeshElement* face = suspectFaces[j];
3233     if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
3234          face->GetNodeIndex( _nodes[0]     ) >= 0 )
3235       continue; // face sharing _LayerEdge node
3236     const int nbNodes = face->NbCornerNodes();
3237     bool intFound = false;
3238     double dist;
3239     SMDS_MeshElement::iterator nIt = face->begin_nodes();
3240     if ( nbNodes == 3 )
3241     {
3242       intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
3243     }
3244     else
3245     {
3246       const SMDS_MeshNode* tria[3];
3247       tria[0] = *nIt++;
3248       tria[1] = *nIt++;;
3249       for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
3250       {
3251         tria[2] = *nIt++;
3252         intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
3253         tria[1] = tria[2];
3254       }
3255     }
3256     if ( intFound )
3257     {
3258       if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
3259         segmentIntersected = true;
3260       if ( distance > dist )
3261         distance = dist, iFace = j;
3262     }
3263   }
3264   if ( iFace != -1 && face ) *face = suspectFaces[iFace];
3265 //   if ( distance && iFace > -1 )
3266 //   {
3267 //     // distance is used to limit size of inflation step which depends on
3268 //     // whether the intersected face bears viscous layers or not
3269 //     bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
3270 //     if ( faceHasVL )
3271 //       *distance /= 2;
3272 //   }
3273   if ( segmentIntersected )
3274   {
3275 #ifdef __myDEBUG
3276     SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
3277     gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
3278     cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
3279          << ", intersection with face ("
3280          << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
3281          << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
3282          << ") distance = " << distance - segLen<< endl;
3283 #endif
3284   }
3285
3286   distance -= segLen;
3287
3288   return segmentIntersected;
3289 }
3290
3291 //================================================================================
3292 /*!
3293  * \brief Returns size and direction of the last segment
3294  */
3295 //================================================================================
3296
3297 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
3298 {
3299   // find two non-coincident positions
3300   gp_XYZ orig = _pos.back();
3301   gp_XYZ dir;
3302   int iPrev = _pos.size() - 2;
3303   while ( iPrev >= 0 )
3304   {
3305     dir = orig - _pos[iPrev];
3306     if ( dir.SquareModulus() > 1e-100 )
3307       break;
3308     else
3309       iPrev--;
3310   }
3311
3312   // make gp_Ax1
3313   gp_Ax1 segDir;
3314   if ( iPrev < 0 )
3315   {
3316     segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
3317     segDir.SetDirection( _normal );
3318     segLen = 0;
3319   }
3320   else
3321   {
3322     gp_Pnt pPrev = _pos[ iPrev ];
3323     if ( !_sWOL.IsNull() )
3324     {
3325       TopLoc_Location loc;
3326       if ( _sWOL.ShapeType() == TopAbs_EDGE )
3327       {
3328         double f,l;
3329         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3330         pPrev = curve->Value( pPrev.X() ).Transformed( loc );
3331       }
3332       else
3333       {
3334         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3335         pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
3336       }
3337       dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
3338     }
3339     segDir.SetLocation( pPrev );
3340     segDir.SetDirection( dir );
3341     segLen = dir.Modulus();
3342   }
3343
3344   return segDir;
3345 }
3346
3347 //================================================================================
3348 /*!
3349  * \brief Test intersection of the last segment with a given triangle
3350  *   using Moller-Trumbore algorithm
3351  * Intersection is detected if distance to intersection is less than _LayerEdge._len
3352  */
3353 //================================================================================
3354
3355 bool _LayerEdge::SegTriaInter( const gp_Ax1&        lastSegment,
3356                                const SMDS_MeshNode* n0,
3357                                const SMDS_MeshNode* n1,
3358                                const SMDS_MeshNode* n2,
3359                                double&              t,
3360                                const double&        EPSILON) const
3361 {
3362   //const double EPSILON = 1e-6;
3363
3364   gp_XYZ orig = lastSegment.Location().XYZ();
3365   gp_XYZ dir  = lastSegment.Direction().XYZ();
3366
3367   SMESH_TNodeXYZ vert0( n0 );
3368   SMESH_TNodeXYZ vert1( n1 );
3369   SMESH_TNodeXYZ vert2( n2 );
3370
3371   /* calculate distance from vert0 to ray origin */
3372   gp_XYZ tvec = orig - vert0;
3373
3374   if ( tvec * dir > EPSILON )
3375     // intersected face is at back side of the temporary face this _LayerEdge belongs to
3376     return false;
3377
3378   gp_XYZ edge1 = vert1 - vert0;
3379   gp_XYZ edge2 = vert2 - vert0;
3380
3381   /* begin calculating determinant - also used to calculate U parameter */
3382   gp_XYZ pvec = dir ^ edge2;
3383
3384   /* if determinant is near zero, ray lies in plane of triangle */
3385   double det = edge1 * pvec;
3386
3387   if (det > -EPSILON && det < EPSILON)
3388     return 0;
3389   double inv_det = 1.0 / det;
3390
3391   /* calculate U parameter and test bounds */
3392   double u = ( tvec * pvec ) * inv_det;
3393   if (u < 0.0 || u > 1.0)
3394     return 0;
3395
3396   /* prepare to test V parameter */
3397   gp_XYZ qvec = tvec ^ edge1;
3398
3399   /* calculate V parameter and test bounds */
3400   double v = (dir * qvec) * inv_det;
3401   if ( v < 0.0 || u + v > 1.0 )
3402     return 0;
3403
3404   /* calculate t, ray intersects triangle */
3405   t = (edge2 * qvec) * inv_det;
3406
3407   //   if (det < EPSILON)
3408   //     return false;
3409
3410   //   /* calculate distance from vert0 to ray origin */
3411   //   gp_XYZ tvec = orig - vert0;
3412
3413   //   /* calculate U parameter and test bounds */
3414   //   double u = tvec * pvec;
3415   //   if (u < 0.0 || u > det)
3416 //     return 0;
3417
3418 //   /* prepare to test V parameter */
3419 //   gp_XYZ qvec = tvec ^ edge1;
3420
3421 //   /* calculate V parameter and test bounds */
3422 //   double v = dir * qvec;
3423 //   if (v < 0.0 || u + v > det)
3424 //     return 0;
3425
3426 //   /* calculate t, scale parameters, ray intersects triangle */
3427 //   double t = edge2 * qvec;
3428 //   double inv_det = 1.0 / det;
3429 //   t *= inv_det;
3430 //   //u *= inv_det;
3431 //   //v *= inv_det;
3432
3433   return true;
3434 }
3435
3436 //================================================================================
3437 /*!
3438  * \brief Perform smooth of _LayerEdge's based on EDGE's
3439  *  \retval bool - true if node has been moved
3440  */
3441 //================================================================================
3442
3443 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3444                               const TopoDS_Face&    F,
3445                               SMESH_MesherHelper&   helper)
3446 {
3447   ASSERT( IsOnEdge() );
3448
3449   SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3450   SMESH_TNodeXYZ oldPos( tgtNode );
3451   double dist01, distNewOld;
3452   
3453   SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3454   SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3455   dist01 = p0.Distance( _2neibors->_nodes[1] );
3456
3457   gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3458   double lenDelta = 0;
3459   if ( _curvature )
3460   {
3461     //lenDelta = _curvature->lenDelta( _len );
3462     lenDelta = _curvature->lenDeltaByDist( dist01 );
3463     newPos.ChangeCoord() += _normal * lenDelta;
3464   }
3465
3466   distNewOld = newPos.Distance( oldPos );
3467
3468   if ( F.IsNull() )
3469   {
3470     if ( _2neibors->_plnNorm )
3471     {
3472       // put newPos on the plane defined by source node and _plnNorm
3473       gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3474       double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3475       newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3476     }
3477     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3478     _pos.back() = newPos.XYZ();
3479   }
3480   else
3481   {
3482     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3483     gp_XY uv( Precision::Infinite(), 0 );
3484     helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3485     _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3486
3487     newPos = surface->Value( uv.X(), uv.Y() );
3488     tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3489   }
3490
3491   if ( _curvature && lenDelta < 0 )
3492   {
3493     gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3494     _len -= prevPos.Distance( oldPos );
3495     _len += prevPos.Distance( newPos );
3496   }
3497   bool moved = distNewOld > dist01/50;
3498   //if ( moved )
3499   dumpMove( tgtNode ); // debug
3500
3501   return moved;
3502 }
3503
3504 //================================================================================
3505 /*!
3506  * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3507  *  \retval bool - true if _tgtNode has been moved
3508  */
3509 //================================================================================
3510
3511 bool _LayerEdge::Smooth(int& badNb)
3512 {
3513   if ( _simplices.size() < 2 )
3514     return false; // _LayerEdge inflated along EDGE or FACE
3515
3516   // compute new position for the last _pos
3517   gp_XYZ newPos (0,0,0);
3518   for ( size_t i = 0; i < _simplices.size(); ++i )
3519     newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3520   newPos /= _simplices.size();
3521
3522   if ( _curvature )
3523     newPos += _normal * _curvature->lenDelta( _len );
3524
3525   gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3526 //   if ( _cosin < -0.1)
3527 //   {
3528 //     // Avoid decreasing length of edge on concave surface
3529 //     //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3530 //     gp_Vec newMove( prevPos, newPos );
3531 //     newPos = _pos.back() + newMove.XYZ();
3532 //   }
3533 //   else if ( _cosin > 0.3 )
3534 //   {
3535 //     // Avoid increasing length of edge too much
3536
3537 //   }
3538   // count quality metrics (orientation) of tetras around _tgtNode
3539   int nbOkBefore = 0;
3540   SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3541   for ( size_t i = 0; i < _simplices.size(); ++i )
3542     nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3543
3544   int nbOkAfter = 0;
3545   for ( size_t i = 0; i < _simplices.size(); ++i )
3546     nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3547
3548   if ( nbOkAfter < nbOkBefore )
3549     return false;
3550
3551   SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3552
3553   _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3554   _len += prevPos.Distance(newPos);
3555
3556   n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3557   _pos.back() = newPos;
3558
3559   badNb += _simplices.size() - nbOkAfter;
3560
3561   dumpMove( n );
3562
3563   return true;
3564 }
3565
3566 //================================================================================
3567 /*!
3568  * \brief Add a new segment to _LayerEdge during inflation
3569  */
3570 //================================================================================
3571
3572 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3573 {
3574   if ( _len - len > -1e-6 )
3575   {
3576     _pos.push_back( _pos.back() );
3577     return;
3578   }
3579
3580   SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3581   SMESH_TNodeXYZ oldXYZ( n );
3582   gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3583   n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3584
3585   _pos.push_back( nXYZ );
3586   _len = len;
3587   if ( !_sWOL.IsNull() )
3588   {
3589     double distXYZ[4];
3590     if ( _sWOL.ShapeType() == TopAbs_EDGE )
3591     {
3592       double u = Precision::Infinite(); // to force projection w/o distance check
3593       helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3594       _pos.back().SetCoord( u, 0, 0 );
3595       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3596       pos->SetUParameter( u );
3597     }
3598     else //  TopAbs_FACE
3599     {
3600       gp_XY uv( Precision::Infinite(), 0 );
3601       helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3602       _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3603       SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3604       pos->SetUParameter( uv.X() );
3605       pos->SetVParameter( uv.Y() );
3606     }
3607     n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3608   }
3609   dumpMove( n ); //debug
3610 }
3611
3612 //================================================================================
3613 /*!
3614  * \brief Remove last inflation step
3615  */
3616 //================================================================================
3617
3618 void _LayerEdge::InvalidateStep( int curStep )
3619 {
3620   if ( _pos.size() > curStep )
3621   {
3622     _pos.resize( curStep );
3623     gp_Pnt nXYZ = _pos.back();
3624     SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3625     if ( !_sWOL.IsNull() )
3626     {
3627       TopLoc_Location loc;
3628       if ( _sWOL.ShapeType() == TopAbs_EDGE )
3629       {
3630         SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3631         pos->SetUParameter( nXYZ.X() );
3632         double f,l;
3633         Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3634         nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3635       }
3636       else
3637       {
3638         SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3639         pos->SetUParameter( nXYZ.X() );
3640         pos->SetVParameter( nXYZ.Y() );
3641         Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3642         nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3643       }
3644     }
3645     n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3646     dumpMove( n );
3647   }
3648 }
3649
3650 //================================================================================
3651 /*!
3652  * \brief Create layers of prisms
3653  */
3654 //================================================================================
3655
3656 bool _ViscousBuilder::refine(_SolidData& data)
3657 {
3658   SMESH_MesherHelper helper( *_mesh );
3659   helper.SetSubShape( data._solid );
3660   helper.SetElementsOnShape(false);
3661
3662   Handle(Geom_Curve) curve;
3663   Handle(Geom_Surface) surface;
3664   TopoDS_Edge geomEdge;
3665   TopoDS_Face geomFace;
3666   TopLoc_Location loc;
3667   double f,l, u/*, distXYZ[4]*/;
3668   gp_XY uv;
3669   bool isOnEdge;
3670
3671   for ( size_t i = 0; i < data._edges.size(); ++i )
3672   {
3673     _LayerEdge& edge = *data._edges[i];
3674
3675     // get accumulated length of segments
3676     vector< double > segLen( edge._pos.size() );
3677     segLen[0] = 0.0;
3678     for ( size_t j = 1; j < edge._pos.size(); ++j )
3679       segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3680
3681     // allocate memory for new nodes if it is not yet refined
3682     const SMDS_MeshNode* tgtNode = edge._nodes.back();
3683     if ( edge._nodes.size() == 2 )
3684     {
3685       edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3686       edge._nodes[1] = 0;
3687       edge._nodes.back() = tgtNode;
3688     }
3689     if ( !edge._sWOL.IsNull() )
3690     {
3691       isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3692       // restore position of the last node
3693 //       gp_Pnt p;
3694       if ( isOnEdge )
3695       {
3696         geomEdge = TopoDS::Edge( edge._sWOL );
3697         curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3698 //         double u = helper.GetNodeU( tgtNode );
3699 //         p = curve->Value( u );
3700       }
3701       else
3702       {
3703         geomFace = TopoDS::Face( edge._sWOL );
3704         surface = BRep_Tool::Surface( geomFace, loc );
3705 //         gp_XY uv = helper.GetNodeUV( tgtNode );
3706 //         p = surface->Value( uv.X(), uv.Y() );
3707       }
3708 //       p.Transform( loc );
3709 //       const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3710     }
3711     // calculate height of the first layer
3712     double h0;
3713     const double T = segLen.back(); //data._hyp.GetTotalThickness();
3714     const double f = data._hyp->GetStretchFactor();
3715     const int    N = data._hyp->GetNumberLayers();
3716     const double fPowN = pow( f, N );
3717     if ( fPowN - 1 <= numeric_limits<double>::min() )
3718       h0 = T / N;
3719     else
3720       h0 = T * ( f - 1 )/( fPowN - 1 );
3721
3722     const double zeroLen = std::numeric_limits<double>::min();
3723
3724     // create intermediate nodes
3725     double hSum = 0, hi = h0/f;
3726     size_t iSeg = 1;
3727     for ( size_t iStep = 1; iStep < edge._nodes.size(); ++iStep )
3728     {
3729       // compute an intermediate position
3730       hi *= f;
3731       hSum += hi;
3732       while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3733         ++iSeg;
3734       int iPrevSeg = iSeg-1;
3735       while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3736         --iPrevSeg;
3737       double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3738       gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3739
3740       SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3741       if ( !edge._sWOL.IsNull() )
3742       {
3743         // compute XYZ by parameters <pos>
3744         if ( isOnEdge )
3745         {
3746           u = pos.X();
3747           pos = curve->Value( u ).Transformed(loc);
3748         }
3749         else
3750         {
3751           uv.SetCoord( pos.X(), pos.Y() );
3752           pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3753         }
3754       }
3755       // create or update the node
3756       if ( !node )
3757       {
3758         node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3759         if ( !edge._sWOL.IsNull() )
3760         {
3761           if ( isOnEdge )
3762             getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3763           else
3764             getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3765         }
3766         else
3767         {
3768           getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3769         }
3770       }
3771       else
3772       {
3773         if ( !edge._sWOL.IsNull() )
3774         {
3775           // make average pos from new and current parameters
3776           if ( isOnEdge )
3777           {
3778             u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3779             pos = curve->Value( u ).Transformed(loc);
3780           }
3781           else
3782           {
3783             uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3784             pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3785           }
3786         }
3787         node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3788       }
3789     }
3790   }
3791
3792   if ( !getMeshDS()->IsEmbeddedMode() )
3793     // Log node movement
3794     for ( size_t i = 0; i < data._edges.size(); ++i )
3795     {
3796       _LayerEdge& edge = *data._edges[i];
3797       SMESH_TNodeXYZ p ( edge._nodes.back() );
3798       getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3799     }
3800
3801   // TODO: make quadratic prisms and polyhedrons(?)
3802
3803   helper.SetElementsOnShape(true);
3804
3805   TopExp_Explorer exp( data._solid, TopAbs_FACE );
3806   for ( ; exp.More(); exp.Next() )
3807   {
3808     if ( data._ignoreFaceIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3809       continue;
3810     SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3811     SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3812     vector< vector<const SMDS_MeshNode*>* > nnVec;
3813     while ( fIt->more() )
3814     {
3815       const SMDS_MeshElement* face = fIt->next();
3816       int nbNodes = face->NbCornerNodes();
3817       nnVec.resize( nbNodes );
3818       SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3819       for ( int iN = 0; iN < nbNodes; ++iN )
3820       {
3821         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3822         nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3823       }
3824
3825       int nbZ = nnVec[0]->size();
3826       switch ( nbNodes )
3827       {
3828       case 3:
3829         for ( int iZ = 1; iZ < nbZ; ++iZ )
3830           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3831                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],   (*nnVec[2])[iZ]);
3832         break;
3833       case 4:
3834         for ( int iZ = 1; iZ < nbZ; ++iZ )
3835           helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3836                             (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3837                             (*nnVec[0])[iZ],   (*nnVec[1])[iZ],
3838                             (*nnVec[2])[iZ],   (*nnVec[3])[iZ]);
3839         break;
3840       default:
3841         return error("Not supported type of element", data._index);
3842       }
3843     }
3844   }
3845   return true;
3846 }
3847
3848 //================================================================================
3849 /*!
3850  * \brief Shrink 2D mesh on faces to let space for inflated layers
3851  */
3852 //================================================================================
3853
3854 bool _ViscousBuilder::shrink()
3855 {
3856   // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3857   // inflated along FACE or EDGE)
3858   map< TGeomID, _SolidData* > f2sdMap;
3859   for ( size_t i = 0 ; i < _sdVec.size(); ++i )
3860   {
3861     _SolidData& data = _sdVec[i];
3862     TopTools_MapOfShape FFMap;
3863     map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3864     for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3865       if ( s2s->second.ShapeType() == TopAbs_FACE )
3866       {
3867         f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3868
3869         if ( FFMap.Add( (*s2s).second ))
3870           // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3871           // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3872           // by StdMeshers_QuadToTriaAdaptor
3873           if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3874           {
3875             SMESH_ProxyMesh::SubMesh* proxySub =
3876               data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3877             SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3878             while ( fIt->more() )
3879               proxySub->AddElement( fIt->next() );
3880             // as a result 3D algo will use elements from proxySub and not from smDS
3881           }
3882       }
3883   }
3884
3885   SMESH_MesherHelper helper( *_mesh );
3886   helper.ToFixNodeParameters( true );
3887
3888   // EDGE's to shrink
3889   map< TGeomID, _Shrinker1D > e2shrMap;
3890
3891   // loop on FACES to srink mesh on
3892   map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3893   for ( ; f2sd != f2sdMap.end(); ++f2sd )
3894   {
3895     _SolidData&     data = *f2sd->second;
3896     TNode2Edge&   n2eMap = data._n2eMap;
3897     const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3898
3899     Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3900
3901     SMESH_subMesh*     sm = _mesh->GetSubMesh( F );
3902     SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3903
3904     helper.SetSubShape(F);
3905
3906     // ===========================
3907     // Prepare data for shrinking
3908     // ===========================
3909
3910     // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3911     // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3912     vector < const SMDS_MeshNode* > smoothNodes;
3913     {
3914       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3915       while ( nIt->more() )
3916       {
3917         const SMDS_MeshNode* n = nIt->next();
3918         if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3919           smoothNodes.push_back( n );
3920       }
3921     }
3922     // Find out face orientation
3923     double refSign = 1;
3924     const set<TGeomID> ignoreShapes;
3925     bool isOkUV;
3926     if ( !smoothNodes.empty() )
3927     {
3928       vector<_Simplex> simplices;
3929       getSimplices( smoothNodes[0], simplices, ignoreShapes );
3930       helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3931       helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3932       gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3933       if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3934         refSign = -1;
3935     }
3936
3937     // Find _LayerEdge's inflated along F
3938     vector< _LayerEdge* > lEdges;
3939     {
3940       SMESH_subMeshIteratorPtr subIt =
3941         sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3942       while ( subIt->more() )
3943       {
3944         SMESH_subMesh*     sub = subIt->next();
3945         SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3946         if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3947           continue;
3948         SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3949         while ( nIt->more() )
3950         {
3951           _LayerEdge* edge = n2eMap[ nIt->next() ];
3952           lEdges.push_back( edge );
3953           prepareEdgeToShrink( *edge, F, helper, smDS );
3954         }
3955       }
3956     }
3957
3958     dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3959     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3960     while ( fIt->more() )
3961       if ( const SMDS_MeshElement* f = fIt->next() )
3962         dumpChangeNodes( f );
3963
3964     // Replace source nodes by target nodes in mesh faces to shrink
3965     const SMDS_MeshNode* nodes[20];
3966     for ( size_t i = 0; i < lEdges.size(); ++i )
3967     {
3968       _LayerEdge& edge = *lEdges[i];
3969       const SMDS_MeshNode* srcNode = edge._nodes[0];
3970       const SMDS_MeshNode* tgtNode = edge._nodes.back();
3971       SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3972       while ( fIt->more() )
3973       {
3974         const SMDS_MeshElement* f = fIt->next();
3975         if ( !smDS->Contains( f ))
3976           continue;
3977         SMDS_NodeIteratorPtr nIt = f->nodeIterator();
3978         for ( int iN = 0; nIt->more(); ++iN )
3979         {
3980           const SMDS_MeshNode* n = nIt->next();
3981           nodes[iN] = ( n == srcNode ? tgtNode : n );
3982         }
3983         helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3984       }
3985     }
3986
3987     // find out if a FACE is concave
3988     const bool isConcaveFace = isConcave( F, helper );
3989
3990     // Create _SmoothNode's on face F
3991     vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3992     {
3993       const bool sortSimplices = isConcaveFace;
3994       for ( size_t i = 0; i < smoothNodes.size(); ++i )
3995       {
3996         const SMDS_MeshNode* n = smoothNodes[i];
3997         nodesToSmooth[ i ]._node = n;
3998         // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3999         getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
4000         // fix up incorrect uv of nodes on the FACE
4001         helper.GetNodeUV( F, n, 0, &isOkUV);
4002         dumpMove( n );
4003       }
4004     }
4005     //if ( nodesToSmooth.empty() ) continue;
4006
4007     // Find EDGE's to shrink and set simpices to LayerEdge's
4008     set< _Shrinker1D* > eShri1D;
4009     {
4010       for ( size_t i = 0; i < lEdges.size(); ++i )
4011       {
4012         _LayerEdge* edge = lEdges[i];
4013         if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
4014         {
4015           TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
4016           _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
4017           eShri1D.insert( & srinker );
4018           srinker.AddEdge( edge, helper );
4019           VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
4020           // restore params of nodes on EGDE if the EDGE has been already
4021           // srinked while srinking another FACE
4022           srinker.RestoreParams();
4023         }
4024         getSimplices( /*tgtNode=*/edge->_nodes.back(), edge->_simplices, ignoreShapes );
4025       }
4026     }
4027
4028     bool toFixTria = false; // to improve quality of trias by diagonal swap
4029     if ( isConcaveFace )
4030     {
4031       const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
4032       if ( hasTria != hasQuad ) {
4033         toFixTria = hasTria;
4034       }
4035       else {
4036         set<int> nbNodesSet;
4037         SMDS_ElemIteratorPtr fIt = smDS->GetElements();
4038         while ( fIt->more() && nbNodesSet.size() < 2 )
4039           nbNodesSet.insert( fIt->next()->NbCornerNodes() );
4040         toFixTria = ( *nbNodesSet.begin() == 3 );
4041       }
4042     }
4043
4044     // ==================
4045     // Perform shrinking
4046     // ==================
4047
4048     bool shrinked = true;
4049     int badNb, shriStep=0, smooStep=0;
4050     _SmoothNode::SmoothType smoothType
4051       = isConcaveFace ? _SmoothNode::ANGULAR : _SmoothNode::LAPLACIAN;
4052     while ( shrinked )
4053     {
4054       shriStep++;
4055       // Move boundary nodes (actually just set new UV)
4056       // -----------------------------------------------
4057       dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep ); // debug
4058       shrinked = false;
4059       for ( size_t i = 0; i < lEdges.size(); ++i )
4060       {
4061         shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
4062       }
4063       dumpFunctionEnd();
4064
4065       // Move nodes on EDGE's
4066       // (XYZ is set as soon as a needed length reached in SetNewLength2d())
4067       set< _Shrinker1D* >::iterator shr = eShri1D.begin();
4068       for ( ; shr != eShri1D.end(); ++shr )
4069         (*shr)->Compute( /*set3D=*/false, helper );
4070
4071       // Smoothing in 2D
4072       // -----------------
4073       int nbNoImpSteps = 0;
4074       bool       moved = true;
4075       badNb = 1;
4076       while (( nbNoImpSteps < 5 && badNb > 0) && moved)
4077       {
4078         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4079
4080         int oldBadNb = badNb;
4081         badNb = 0;
4082         moved = false;
4083         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4084         {
4085           moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4086                                             smoothType, /*set3D=*/isConcaveFace);
4087         }
4088         if ( badNb < oldBadNb )
4089           nbNoImpSteps = 0;
4090         else
4091           nbNoImpSteps++;
4092
4093         dumpFunctionEnd();
4094       }
4095       if ( badNb > 0 )
4096         return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
4097       if ( shriStep > 200 )
4098         return error(SMESH_Comment("Infinite loop at shrinking 2D mesh on face ") << f2sd->first );
4099
4100       // Fix narrow triangles by swapping diagonals
4101       // ---------------------------------------
4102       if ( toFixTria )
4103       {
4104         set<const SMDS_MeshNode*> usedNodes;
4105         fixBadFaces( F, helper, /*is2D=*/true, shriStep, & usedNodes); // swap diagonals
4106
4107         // update working data
4108         set<const SMDS_MeshNode*>::iterator n;
4109         for ( size_t i = 0; i < nodesToSmooth.size() && !usedNodes.empty(); ++i )
4110         {
4111           n = usedNodes.find( nodesToSmooth[ i ]._node );
4112           if ( n != usedNodes.end())
4113           {
4114             getSimplices( nodesToSmooth[ i ]._node,
4115                           nodesToSmooth[ i ]._simplices,
4116                           ignoreShapes, NULL,
4117                           /*sortSimplices=*/ smoothType == _SmoothNode::ANGULAR );
4118             usedNodes.erase( n );
4119           }
4120         }
4121         for ( size_t i = 0; i < lEdges.size() && !usedNodes.empty(); ++i )
4122         {
4123           n = usedNodes.find( /*tgtNode=*/ lEdges[i]->_nodes.back() );
4124           if ( n != usedNodes.end())
4125           {
4126             getSimplices( lEdges[i]->_nodes.back(),
4127                           lEdges[i]->_simplices,
4128                           ignoreShapes );
4129             usedNodes.erase( n );
4130           }
4131         }
4132       }
4133     } // while ( shrinked )
4134
4135     // No wrongly shaped faces remain; final smooth. Set node XYZ.
4136     bool isStructuredFixed = false;
4137     if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
4138       isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
4139     if ( !isStructuredFixed )
4140     {
4141       if ( isConcaveFace ) // fix narrow faces by swapping diagonals
4142         fixBadFaces( F, helper, /*is2D=*/false, ++shriStep );
4143
4144       for ( int st = 3; st; --st )
4145       {
4146         switch( st ) {
4147         case 1: smoothType = _SmoothNode::LAPLACIAN; break;
4148         case 2: smoothType = _SmoothNode::LAPLACIAN; break;
4149         case 3: smoothType = _SmoothNode::ANGULAR; break;
4150         }
4151         dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
4152         for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4153         {
4154           nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
4155                                    smoothType,/*set3D=*/st==1 );
4156         }
4157         dumpFunctionEnd();
4158       }
4159     }
4160     // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
4161     VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
4162
4163     if ( !getMeshDS()->IsEmbeddedMode() )
4164       // Log node movement
4165       for ( size_t i = 0; i < nodesToSmooth.size(); ++i )
4166       {
4167         SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
4168         getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
4169       }
4170
4171   } // loop on FACES to srink mesh on
4172
4173
4174   // Replace source nodes by target nodes in shrinked mesh edges
4175
4176   map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
4177   for ( ; e2shr != e2shrMap.end(); ++e2shr )
4178     e2shr->second.SwapSrcTgtNodes( getMeshDS() );
4179
4180   return true;
4181 }
4182
4183 //================================================================================
4184 /*!
4185  * \brief Computes 2d shrink direction and finds nodes limiting shrinking
4186  */
4187 //================================================================================
4188
4189 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge&            edge,
4190                                            const TopoDS_Face&     F,
4191                                            SMESH_MesherHelper&    helper,
4192                                            const SMESHDS_SubMesh* faceSubMesh)
4193 {
4194   const SMDS_MeshNode* srcNode = edge._nodes[0];
4195   const SMDS_MeshNode* tgtNode = edge._nodes.back();
4196
4197   edge._pos.clear();
4198
4199   if ( edge._sWOL.ShapeType() == TopAbs_FACE )
4200   {
4201     gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4202     gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4203     gp_Vec2d uvDir( srcUV, tgtUV );
4204     double uvLen = uvDir.Magnitude();
4205     uvDir /= uvLen;
4206     edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
4207     edge._len = uvLen;
4208
4209     // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4210     // vector<const SMDS_MeshElement*> faces;
4211     // multimap< double, const SMDS_MeshNode* > proj2node;
4212     // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4213     // while ( fIt->more() )
4214     // {
4215     //   const SMDS_MeshElement* f = fIt->next();
4216     //   if ( faceSubMesh->Contains( f ))
4217     //     faces.push_back( f );
4218     // }
4219     // for ( size_t i = 0; i < faces.size(); ++i )
4220     // {
4221     //   const int nbNodes = faces[i]->NbCornerNodes();
4222     //   for ( int j = 0; j < nbNodes; ++j )
4223     //   {
4224     //     const SMDS_MeshNode* n = faces[i]->GetNode(j);
4225     //     if ( n == srcNode ) continue;
4226     //     if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
4227     //          ( faces.size() > 1 || nbNodes > 3 ))
4228     //       continue;
4229     //     gp_Pnt2d uv = helper.GetNodeUV( F, n );
4230     //     gp_Vec2d uvDirN( srcUV, uv );
4231     //     double proj = uvDirN * uvDir;
4232     //     proj2node.insert( make_pair( proj, n ));
4233     //   }
4234     // }
4235
4236     // multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
4237     // const double       minProj = p2n->first;
4238     // const double projThreshold = 1.1 * uvLen;
4239     // if ( minProj > projThreshold )
4240     // {
4241     //   // tgtNode is located so that it does not make faces with wrong orientation
4242     //   return true;
4243     // }
4244     edge._pos.resize(1);
4245     edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
4246
4247     // store most risky nodes in _simplices
4248     // p2nEnd = proj2node.lower_bound( projThreshold );
4249     // int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
4250     // edge._simplices.resize( nbSimpl );
4251     // for ( int i = 0; i < nbSimpl; ++i )
4252     // {
4253     //   edge._simplices[i]._nPrev = p2n->second;
4254     //   if ( ++p2n != p2nEnd )
4255     //     edge._simplices[i]._nNext = p2n->second;
4256     // }
4257     // set UV of source node to target node
4258     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4259     pos->SetUParameter( srcUV.X() );
4260     pos->SetVParameter( srcUV.Y() );
4261   }
4262   else // _sWOL is TopAbs_EDGE
4263   {
4264     TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
4265     SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
4266     if ( !edgeSM || edgeSM->NbElements() == 0 )
4267       return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4268
4269     const SMDS_MeshNode* n2 = 0;
4270     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4271     while ( eIt->more() && !n2 )
4272     {
4273       const SMDS_MeshElement* e = eIt->next();
4274       if ( !edgeSM->Contains(e)) continue;
4275       n2 = e->GetNode( 0 );
4276       if ( n2 == srcNode ) n2 = e->GetNode( 1 );
4277     }
4278     if ( !n2 )
4279       return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
4280
4281     double uSrc = helper.GetNodeU( E, srcNode, n2 );
4282     double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
4283     double u2   = helper.GetNodeU( E, n2,      srcNode );
4284
4285     if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
4286     {
4287       // tgtNode is located so that it does not make faces with wrong orientation
4288       return true;
4289     }
4290     edge._pos.resize(1);
4291     edge._pos[0].SetCoord( U_TGT, uTgt );
4292     edge._pos[0].SetCoord( U_SRC, uSrc );
4293     edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
4294
4295     edge._simplices.resize( 1 );
4296     edge._simplices[0]._nPrev = n2;
4297
4298     // set UV of source node to target node
4299     SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4300     pos->SetUParameter( uSrc );
4301   }
4302   return true;
4303
4304   //================================================================================
4305   /*!
4306    * \brief Compute positions (UV) to set to a node on edge moved during shrinking
4307    */
4308   //================================================================================
4309   
4310   // Compute UV to follow during shrinking
4311
4312 //   const SMDS_MeshNode* srcNode = edge._nodes[0];
4313 //   const SMDS_MeshNode* tgtNode = edge._nodes.back();
4314
4315 //   gp_XY srcUV = helper.GetNodeUV( F, srcNode );
4316 //   gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
4317 //   gp_Vec2d uvDir( srcUV, tgtUV );
4318 //   double uvLen = uvDir.Magnitude();
4319 //   uvDir /= uvLen;
4320
4321 //   // Select shrinking step such that not to make faces with wrong orientation.
4322 //   // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
4323 //   const double minStepSize = uvLen / 20;
4324 //   double stepSize = uvLen;
4325 //   SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
4326 //   while ( fIt->more() )
4327 //   {
4328 //     const SMDS_MeshElement* f = fIt->next();
4329 //     if ( !faceSubMesh->Contains( f )) continue;
4330 //     const int nbNodes = f->NbCornerNodes();
4331 //     for ( int i = 0; i < nbNodes; ++i )
4332 //     {
4333 //       const SMDS_MeshNode* n = f->GetNode(i);
4334 //       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
4335 //         continue;
4336 //       gp_XY uv = helper.GetNodeUV( F, n );
4337 //       gp_Vec2d uvDirN( srcUV, uv );
4338 //       double proj = uvDirN * uvDir;
4339 //       if ( proj < stepSize && proj > minStepSize )
4340 //         stepSize = proj;
4341 //     }
4342 //   }
4343 //   stepSize *= 0.8;
4344
4345 //   const int nbSteps = ceil( uvLen / stepSize );
4346 //   gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
4347 //   gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
4348 //   edge._pos.resize( nbSteps );
4349 //   edge._pos[0] = tgtUV0;
4350 //   for ( int i = 1; i < nbSteps; ++i )
4351 //   {
4352 //     double r = i / double( nbSteps );
4353 //     edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
4354 //   }
4355 //   return true;
4356 }
4357
4358 //================================================================================
4359 /*!
4360  * \brief Try to fix triangles with high aspect ratio by swaping diagonals
4361  */
4362 //================================================================================
4363
4364 void _ViscousBuilder::fixBadFaces(const TopoDS_Face&          F,
4365                                   SMESH_MesherHelper&         helper,
4366                                   const bool                  is2D,
4367                                   const int                   step,
4368                                   set<const SMDS_MeshNode*> * involvedNodes)
4369 {
4370   SMESH::Controls::AspectRatio qualifier;
4371   SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
4372   const double maxAspectRatio = is2D ? 4. : 2;
4373   NodeCoordHelper xyz( F, helper, is2D );
4374
4375   // find bad triangles
4376
4377   vector< const SMDS_MeshElement* > badTrias;
4378   vector< double >                  badAspects;
4379   SMESHDS_SubMesh*      sm = helper.GetMeshDS()->MeshElements( F );
4380   SMDS_ElemIteratorPtr fIt = sm->GetElements();
4381   while ( fIt->more() )
4382   {
4383     const SMDS_MeshElement * f = fIt->next();
4384     if ( f->NbCornerNodes() != 3 ) continue;
4385     for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = xyz( f->GetNode(iP));
4386     double aspect = qualifier.GetValue( points );
4387     if ( aspect > maxAspectRatio )
4388     {
4389       badTrias.push_back( f );
4390       badAspects.push_back( aspect );
4391     }
4392   }
4393   if ( step == 1 )
4394   {
4395     dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4396     SMDS_ElemIteratorPtr fIt = sm->GetElements();
4397     while ( fIt->more() )
4398     {
4399       const SMDS_MeshElement * f = fIt->next();
4400       if ( f->NbCornerNodes() == 3 )
4401         dumpChangeNodes( f );
4402     }
4403     dumpFunctionEnd();
4404   }
4405   if ( badTrias.empty() )
4406     return;
4407
4408   // find couples of faces to swap diagonal
4409
4410   typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
4411   vector< T2Trias > triaCouples; 
4412
4413   TIDSortedElemSet involvedFaces, emptySet;
4414   for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
4415   {
4416     T2Trias trias    [3];
4417     double  aspRatio [3];
4418     int i1, i2, i3;
4419
4420     if ( !involvedFaces.insert( badTrias[iTia] ).second )
4421       continue;
4422     for ( int iP = 0; iP < 3; ++iP )
4423       points(iP+1) = xyz( badTrias[iTia]->GetNode(iP));
4424
4425     // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
4426     int bestCouple = -1;
4427     for ( int iSide = 0; iSide < 3; ++iSide )
4428     {
4429       const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
4430       const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
4431       trias [iSide].first  = badTrias[iTia];
4432       trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
4433                                                              & i1, & i2 );
4434       if (( ! trias[iSide].second ) ||
4435           ( trias[iSide].second->NbCornerNodes() != 3 ) ||
4436           ( ! sm->Contains( trias[iSide].second )))
4437         continue;
4438
4439       // aspect ratio of an adjacent tria
4440       for ( int iP = 0; iP < 3; ++iP )
4441         points2(iP+1) = xyz( trias[iSide].second->GetNode(iP));
4442       double aspectInit = qualifier.GetValue( points2 );
4443
4444       // arrange nodes as after diag-swaping
4445       if ( helper.WrapIndex( i1+1, 3 ) == i2 )
4446         i3 = helper.WrapIndex( i1-1, 3 );
4447       else
4448         i3 = helper.WrapIndex( i1+1, 3 );
4449       points1 = points;
4450       points1( 1+ iSide ) = points2( 1+ i3 );
4451       points2( 1+ i2    ) = points1( 1+ ( iSide+2 ) % 3 );
4452
4453       // aspect ratio after diag-swaping
4454       aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
4455       if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
4456         continue;
4457
4458       // prevent inversion of a triangle
4459       gp_Vec norm1 = gp_Vec( points1(1), points1(3) ) ^ gp_Vec( points1(1), points1(2) );
4460       gp_Vec norm2 = gp_Vec( points2(1), points2(3) ) ^ gp_Vec( points2(1), points2(2) );
4461       if ( norm1 * norm2 < 0. && norm1.Angle( norm2 ) > 70./180.*M_PI )
4462         continue;
4463
4464       if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4465         bestCouple = iSide;
4466     }
4467
4468     if ( bestCouple >= 0 )
4469     {
4470       triaCouples.push_back( trias[bestCouple] );
4471       involvedFaces.insert ( trias[bestCouple].second );
4472     }
4473     else
4474     {
4475       involvedFaces.erase( badTrias[iTia] );
4476     }
4477   }
4478   if ( triaCouples.empty() )
4479     return;
4480
4481   // swap diagonals
4482
4483   SMESH_MeshEditor editor( helper.GetMesh() );
4484   dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4485   for ( size_t i = 0; i < triaCouples.size(); ++i )
4486   {
4487     dumpChangeNodes( triaCouples[i].first );
4488     dumpChangeNodes( triaCouples[i].second );
4489     editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4490   }
4491
4492   if ( involvedNodes )
4493     for ( size_t i = 0; i < triaCouples.size(); ++i )
4494     {
4495       involvedNodes->insert( triaCouples[i].first->begin_nodes(),
4496                              triaCouples[i].first->end_nodes() );
4497       involvedNodes->insert( triaCouples[i].second->begin_nodes(),
4498                              triaCouples[i].second->end_nodes() );
4499     }
4500
4501   // just for debug dump resulting triangles
4502   dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID()<<"_"<<step);
4503   for ( size_t i = 0; i < triaCouples.size(); ++i )
4504   {
4505     dumpChangeNodes( triaCouples[i].first );
4506     dumpChangeNodes( triaCouples[i].second );
4507   }
4508 }
4509
4510 //================================================================================
4511 /*!
4512  * \brief Move target node to it's final position on the FACE during shrinking
4513  */
4514 //================================================================================
4515
4516 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4517                                  const TopoDS_Face&    F,
4518                                  SMESH_MesherHelper&   helper )
4519 {
4520   if ( _pos.empty() )
4521     return false; // already at the target position
4522
4523   SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4524
4525   if ( _sWOL.ShapeType() == TopAbs_FACE )
4526   {
4527     gp_XY    curUV = helper.GetNodeUV( F, tgtNode );
4528     gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y() );
4529     gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4530     const double uvLen = tgtUV.Distance( curUV );
4531     const double kSafe = Max( 0.5, 1. - 0.1 * _simplices.size() );
4532
4533     // Select shrinking step such that not to make faces with wrong orientation.
4534     double stepSize = uvLen;
4535     for ( size_t i = 0; i < _simplices.size(); ++i )
4536     {
4537       // find intersection of 2 lines: curUV-tgtUV and that connecting simplex nodes
4538       gp_XY uvN1 = helper.GetNodeUV( F, _simplices[i]._nPrev );
4539       gp_XY uvN2 = helper.GetNodeUV( F, _simplices[i]._nNext );
4540       gp_XY dirN = uvN2 - uvN1;
4541       double det = uvDir.Crossed( dirN );
4542       if ( Abs( det )  < std::numeric_limits<double>::min() ) continue;
4543       gp_XY dirN2Cur = curUV - uvN1;
4544       double step = dirN.Crossed( dirN2Cur ) / det;
4545       if ( step > 0 )
4546         stepSize = Min( step, stepSize );
4547     }
4548     gp_Pnt2d newUV;
4549     if ( uvLen - stepSize < _len / 200. )
4550     {
4551       newUV = tgtUV;
4552       _pos.clear();
4553     }
4554     else if ( stepSize > 0 )
4555     {
4556       newUV = curUV + uvDir.XY() * stepSize * kSafe;
4557     }
4558     else
4559     {
4560       return true;
4561     }
4562     SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4563     pos->SetUParameter( newUV.X() );
4564     pos->SetVParameter( newUV.Y() );
4565
4566 #ifdef __myDEBUG
4567     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4568     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4569     dumpMove( tgtNode );
4570 #endif
4571   }
4572   else // _sWOL is TopAbs_EDGE
4573   {
4574     TopoDS_Edge E = TopoDS::Edge( _sWOL );
4575     const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4576     SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4577
4578     const double u2 = helper.GetNodeU( E, n2, tgtNode );
4579     const double uSrc   = _pos[0].Coord( U_SRC );
4580     const double lenTgt = _pos[0].Coord( LEN_TGT );
4581
4582     double newU = _pos[0].Coord( U_TGT );
4583     if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4584     {
4585       _pos.clear();
4586     }
4587     else
4588     {
4589       newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4590     }
4591     tgtPos->SetUParameter( newU );
4592 #ifdef __myDEBUG
4593     gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4594     gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4595     tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4596     dumpMove( tgtNode );
4597 #endif
4598   }
4599   return true;
4600 }
4601
4602 //================================================================================
4603 /*!
4604  * \brief Perform smooth on the FACE
4605  *  \retval bool - true if the node has been moved
4606  */
4607 //================================================================================
4608
4609 bool _SmoothNode::Smooth(int&                  badNb,
4610                          Handle(Geom_Surface)& surface,
4611                          SMESH_MesherHelper&   helper,
4612                          const double          refSign,
4613                          SmoothType            how,
4614                          bool                  set3D)
4615 {
4616   const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4617
4618   // get uv of surrounding nodes
4619   vector<gp_XY> uv( _simplices.size() );
4620   for ( size_t i = 0; i < _simplices.size(); ++i )
4621     uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4622
4623   // compute new UV for the node
4624   gp_XY newPos (0,0);
4625   if ( how == TFI && _simplices.size() == 4 )
4626   {
4627     gp_XY corners[4];
4628     for ( size_t i = 0; i < _simplices.size(); ++i )
4629       if ( _simplices[i]._nOpp )
4630         corners[i] = helper.GetNodeUV( face, _simplices[i]._nOpp, _node );
4631       else
4632         throw SALOME_Exception(LOCALIZED("TFI smoothing: _Simplex::_nOpp not set!"));
4633
4634     newPos = helper.calcTFI ( 0.5, 0.5,
4635                               corners[0], corners[1], corners[2], corners[3],
4636                               uv[1], uv[2], uv[3], uv[0] );
4637   }
4638   else if ( how == ANGULAR )
4639   {
4640     newPos = computeAngularPos( uv, helper.GetNodeUV( face, _node ), refSign );
4641   }
4642   else if ( how == CENTROIDAL && _simplices.size() > 3 )
4643   {
4644     // average centers of diagonals wieghted with their reciprocal lengths
4645     if ( _simplices.size() == 4 )
4646     {
4647       double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4648       double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4649       newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4650     }
4651     else
4652     {
4653       double sumWeight = 0;
4654       int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4655       for ( int i = 0; i < nb; ++i )
4656       {
4657         int iFrom = i + 2;
4658         int iTo   = i + _simplices.size() - 1;
4659         for ( int j = iFrom; j < iTo; ++j )
4660         {
4661           int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4662           double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4663           sumWeight += w;
4664           newPos += w * ( uv[i]+uv[i2] );
4665         }
4666       }
4667       newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4668     }
4669   }
4670   else
4671   {
4672     // Laplacian smooth
4673     for ( size_t i = 0; i < _simplices.size(); ++i )
4674       newPos += uv[i];
4675     newPos /= _simplices.size();
4676   }
4677
4678   // count quality metrics (orientation) of triangles around the node
4679   int nbOkBefore = 0;
4680   gp_XY tgtUV = helper.GetNodeUV( face, _node );
4681   for ( size_t i = 0; i < _simplices.size(); ++i )
4682     nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4683
4684   int nbOkAfter = 0;
4685   for ( size_t i = 0; i < _simplices.size(); ++i )
4686     nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4687
4688   if ( nbOkAfter < nbOkBefore )
4689   {
4690     badNb += _simplices.size() - nbOkBefore;
4691     return false;
4692   }
4693
4694   SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4695   pos->SetUParameter( newPos.X() );
4696   pos->SetVParameter( newPos.Y() );
4697
4698 #ifdef __myDEBUG
4699   set3D = true;
4700 #endif
4701   if ( set3D )
4702   {
4703     gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4704     const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4705     dumpMove( _node );
4706   }
4707
4708   badNb += _simplices.size() - nbOkAfter;
4709   return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4710 }
4711
4712 //================================================================================
4713 /*!
4714  * \brief Computes new UV using angle based smoothing technic
4715  */
4716 //================================================================================
4717
4718 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4719                                      const gp_XY&   uvToFix,
4720                                      const double   refSign)
4721 {
4722   uv.push_back( uv.front() );
4723
4724   vector< gp_XY >  edgeDir ( uv.size() );
4725   vector< double > edgeSize( uv.size() );
4726   for ( size_t i = 1; i < edgeDir.size(); ++i )
4727   {
4728     edgeDir [i-1] = uv[i] - uv[i-1];
4729     edgeSize[i-1] = edgeDir[i-1].Modulus();
4730     if ( edgeSize[i-1] < numeric_limits<double>::min() )
4731       edgeDir[i-1].SetX( 100 );
4732     else
4733       edgeDir[i-1] /= edgeSize[i-1] * refSign;
4734   }
4735   edgeDir.back()  = edgeDir.front();
4736   edgeSize.back() = edgeSize.front();
4737
4738   gp_XY  newPos(0,0);
4739   int    nbEdges = 0;
4740   double sumSize = 0;
4741   for ( size_t i = 1; i < edgeDir.size(); ++i )
4742   {
4743     if ( edgeDir[i-1].X() > 1. ) continue;
4744     int i1 = i-1;
4745     while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4746     if ( i == edgeDir.size() ) break;
4747     gp_XY p = uv[i];
4748     gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4749     gp_XY norm2( -edgeDir[i].Y(),  edgeDir[i].X() );
4750     gp_XY bisec = norm1 + norm2;
4751     double bisecSize = bisec.Modulus();
4752     if ( bisecSize < numeric_limits<double>::min() )
4753     {
4754       bisec = -edgeDir[i1] + edgeDir[i];
4755       bisecSize = bisec.Modulus();
4756     }
4757     bisec /= bisecSize;
4758
4759     gp_XY  dirToN  = uvToFix - p;
4760     double distToN = dirToN.Modulus();
4761     if ( bisec * dirToN < 0 )
4762       distToN = -distToN;
4763
4764     newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4765     ++nbEdges;
4766     sumSize += edgeSize[i1] + edgeSize[i];
4767   }
4768   newPos /= /*nbEdges * */sumSize;
4769   return newPos;
4770 }
4771
4772 //================================================================================
4773 /*!
4774  * \brief Delete _SolidData
4775  */
4776 //================================================================================
4777
4778 _SolidData::~_SolidData()
4779 {
4780   for ( size_t i = 0; i < _edges.size(); ++i )
4781   {
4782     if ( _edges[i] && _edges[i]->_2neibors )
4783       delete _edges[i]->_2neibors;
4784     delete _edges[i];
4785   }
4786   _edges.clear();
4787 }
4788 //================================================================================
4789 /*!
4790  * \brief Add a _LayerEdge inflated along the EDGE
4791  */
4792 //================================================================================
4793
4794 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4795 {
4796   // init
4797   if ( _nodes.empty() )
4798   {
4799     _edges[0] = _edges[1] = 0;
4800     _done = false;
4801   }
4802   // check _LayerEdge
4803   if ( e == _edges[0] || e == _edges[1] )
4804     return;
4805   if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4806     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4807   if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4808     throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4809
4810   // store _LayerEdge
4811   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4812   double f,l;
4813   BRep_Tool::Range( E, f,l );
4814   double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4815   _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4816
4817   // Update _nodes
4818
4819   const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4820   const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4821
4822   if ( _nodes.empty() )
4823   {
4824     SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4825     if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4826       return;
4827     TopLoc_Location loc;
4828     Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4829     GeomAdaptor_Curve aCurve(C, f,l);
4830     const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4831
4832     int nbExpectNodes = eSubMesh->NbNodes();
4833     _initU  .reserve( nbExpectNodes );
4834     _normPar.reserve( nbExpectNodes );
4835     _nodes  .reserve( nbExpectNodes );
4836     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4837     while ( nIt->more() )
4838     {
4839       const SMDS_MeshNode* node = nIt->next();
4840       if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4841            node == tgtNode0 || node == tgtNode1 )
4842         continue; // refinement nodes
4843       _nodes.push_back( node );
4844       _initU.push_back( helper.GetNodeU( E, node ));
4845       double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4846       _normPar.push_back(  len / totLen );
4847     }
4848   }
4849   else
4850   {
4851     // remove target node of the _LayerEdge from _nodes
4852     int nbFound = 0;
4853     for ( size_t i = 0; i < _nodes.size(); ++i )
4854       if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4855         _nodes[i] = 0, nbFound++;
4856     if ( nbFound == _nodes.size() )
4857       _nodes.clear();
4858   }
4859 }
4860
4861 //================================================================================
4862 /*!
4863  * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4864  */
4865 //================================================================================
4866
4867 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4868 {
4869   if ( _done || _nodes.empty())
4870     return;
4871   const _LayerEdge* e = _edges[0];
4872   if ( !e ) e = _edges[1];
4873   if ( !e ) return;
4874
4875   _done =  (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4876             ( !_edges[1] || _edges[1]->_pos.empty() ));
4877
4878   const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4879   double f,l;
4880   if ( set3D || _done )
4881   {
4882     Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4883     GeomAdaptor_Curve aCurve(C, f,l);
4884
4885     if ( _edges[0] )
4886       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4887     if ( _edges[1] )
4888       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4889     double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4890
4891     for ( size_t i = 0; i < _nodes.size(); ++i )
4892     {
4893       if ( !_nodes[i] ) continue;
4894       double len = totLen * _normPar[i];
4895       GCPnts_AbscissaPoint discret( aCurve, len, f );
4896       if ( !discret.IsDone() )
4897         return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4898       double u = discret.Parameter();
4899       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4900       pos->SetUParameter( u );
4901       gp_Pnt p = C->Value( u );
4902       const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4903     }
4904   }
4905   else
4906   {
4907     BRep_Tool::Range( E, f,l );
4908     if ( _edges[0] )
4909       f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4910     if ( _edges[1] )
4911       l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4912     
4913     for ( size_t i = 0; i < _nodes.size(); ++i )
4914     {
4915       if ( !_nodes[i] ) continue;
4916       double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4917       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4918       pos->SetUParameter( u );
4919     }
4920   }
4921 }
4922
4923 //================================================================================
4924 /*!
4925  * \brief Restore initial parameters of nodes on EDGE
4926  */
4927 //================================================================================
4928
4929 void _Shrinker1D::RestoreParams()
4930 {
4931   if ( _done )
4932     for ( size_t i = 0; i < _nodes.size(); ++i )
4933     {
4934       if ( !_nodes[i] ) continue;
4935       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4936       pos->SetUParameter( _initU[i] );
4937     }
4938   _done = false;
4939 }
4940
4941 //================================================================================
4942 /*!
4943  * \brief Replace source nodes by target nodes in shrinked mesh edges
4944  */
4945 //================================================================================
4946
4947 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4948 {
4949   const SMDS_MeshNode* nodes[3];
4950   for ( int i = 0; i < 2; ++i )
4951   {
4952     if ( !_edges[i] ) continue;
4953
4954     SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4955     if ( !eSubMesh ) return;
4956     const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4957     const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4958     SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4959     while ( eIt->more() )
4960     {
4961       const SMDS_MeshElement* e = eIt->next();
4962       if ( !eSubMesh->Contains( e ))
4963           continue;
4964       SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4965       for ( int iN = 0; iN < e->NbNodes(); ++iN )
4966       {
4967         const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4968         nodes[iN] = ( n == srcNode ? tgtNode : n );
4969       }
4970       mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4971     }
4972   }
4973 }
4974
4975 //================================================================================
4976 /*!
4977  * \brief Creates 2D and 1D elements on boundaries of new prisms
4978  */
4979 //================================================================================
4980
4981 bool _ViscousBuilder::addBoundaryElements()
4982 {
4983   SMESH_MesherHelper helper( *_mesh );
4984
4985   for ( size_t i = 0; i < _sdVec.size(); ++i )
4986   {
4987     _SolidData& data = _sdVec[i];
4988     TopTools_IndexedMapOfShape geomEdges;
4989     TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4990     for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4991     {
4992       const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4993
4994       // Get _LayerEdge's based on E
4995
4996       map< double, const SMDS_MeshNode* > u2nodes;
4997       if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4998         continue;
4999
5000       vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
5001       TNode2Edge & n2eMap = data._n2eMap;
5002       map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
5003       {
5004         //check if 2D elements are needed on E
5005         TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
5006         if ( n2e == n2eMap.end() ) continue; // no layers on vertex
5007         ledges.push_back( n2e->second );
5008         u2n++;
5009         if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
5010           continue; // no layers on E
5011         ledges.push_back( n2eMap[ u2n->second ]);
5012
5013         const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
5014         const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
5015         int nbSharedPyram = 0;
5016         SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
5017         while ( vIt->more() )
5018         {
5019           const SMDS_MeshElement* v = vIt->next();
5020           nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
5021         }
5022         if ( nbSharedPyram > 1 )
5023           continue; // not free border of the pyramid
5024
5025         if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
5026                                     ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
5027           continue; // faces already created
5028       }
5029       for ( ++u2n; u2n != u2nodes.end(); ++u2n )
5030         ledges.push_back( n2eMap[ u2n->second ]);
5031
5032       // Find out orientation and type of face to create
5033
5034       bool reverse = false, isOnFace;
5035       
5036       map< TGeomID, TopoDS_Shape >::iterator e2f =
5037         data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
5038       TopoDS_Shape F;
5039       if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
5040       {
5041         F = e2f->second.Oriented( TopAbs_FORWARD );
5042         reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
5043         if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
5044           reverse = !reverse, F.Reverse();
5045         if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
5046           reverse = !reverse;
5047       }
5048       else
5049       {
5050         // find FACE with layers sharing E
5051         PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
5052         while ( fIt->more() && F.IsNull() )
5053         {
5054           const TopoDS_Shape* pF = fIt->next();
5055           if ( helper.IsSubShape( *pF, data._solid) &&
5056                !data._ignoreFaceIds.count( e2f->first ))
5057             F = *pF;
5058         }
5059       }
5060       // Find the sub-mesh to add new faces
5061       SMESHDS_SubMesh* sm = 0;
5062       if ( isOnFace )
5063         sm = getMeshDS()->MeshElements( F );
5064       else
5065         sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
5066       if ( !sm )
5067         return error("error in addBoundaryElements()", data._index);
5068
5069       // Make faces
5070       const int dj1 = reverse ? 0 : 1;
5071       const int dj2 = reverse ? 1 : 0;
5072       for ( size_t j = 1; j < ledges.size(); ++j )
5073       {
5074         vector< const SMDS_MeshNode*>&  nn1 = ledges[j-dj1]->_nodes;
5075         vector< const SMDS_MeshNode*>&  nn2 = ledges[j-dj2]->_nodes;
5076         if ( isOnFace )
5077           for ( size_t z = 1; z < nn1.size(); ++z )
5078             sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
5079         else
5080           for ( size_t z = 1; z < nn1.size(); ++z )
5081             sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
5082       }
5083
5084       // Make edges
5085       for ( int isFirst = 0; isFirst < 2; ++isFirst )
5086       {
5087         _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
5088         if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
5089         {
5090           vector< const SMDS_MeshNode*>&  nn = edge->_nodes;
5091           if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
5092             continue;
5093           helper.SetSubShape( edge->_sWOL );
5094           helper.SetElementsOnShape( true );
5095           for ( size_t z = 1; z < nn.size(); ++z )
5096             helper.AddEdge( nn[z-1], nn[z] );
5097         }
5098       }
5099     }
5100   }
5101
5102   return true;
5103 }