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