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