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