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