Salome HOME
23239: [CEA 1739] Regression : crash trying to create mesh
[modules/smesh.git] / src / StdMeshers / StdMeshers_ViscousLayers2D.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : StdMeshers_ViscousLayers2D.cxx
21 // Created   : 23 Jul 2012
22 // Author    : Edward AGAPOV (eap)
23
24 #include "StdMeshers_ViscousLayers2D.hxx"
25
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_HypoFilter.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42 #include "SMESH_Quadtree.hxx"
43 #include "SMESH_subMesh.hxx"
44 #include "SMESH_subMeshEventListener.hxx"
45 #include "StdMeshers_FaceSide.hxx"
46
47 #include "utilities.h"
48
49 #include <BRepAdaptor_Curve.hxx>
50 #include <BRepAdaptor_Curve2d.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <Bnd_B3d.hxx>
54 #include <ElCLib.hxx>
55 #include <GCPnts_AbscissaPoint.hxx>
56 #include <Geom2dAdaptor_Curve.hxx>
57 #include <Geom2dInt_GInter.hxx>
58 #include <Geom2d_Circle.hxx>
59 #include <Geom2d_Line.hxx>
60 #include <Geom2d_TrimmedCurve.hxx>
61 #include <GeomAdaptor_Curve.hxx>
62 #include <Geom_Circle.hxx>
63 #include <Geom_Curve.hxx>
64 #include <Geom_Line.hxx>
65 #include <Geom_TrimmedCurve.hxx>
66 #include <IntRes2d_IntersectionPoint.hxx>
67 #include <Precision.hxx>
68 #include <Standard_ErrorHandler.hxx>
69 #include <TColStd_Array1OfReal.hxx>
70 #include <TopExp.hxx>
71 #include <TopExp_Explorer.hxx>
72 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
73 #include <TopTools_IndexedMapOfShape.hxx>
74 #include <TopTools_ListIteratorOfListOfShape.hxx>
75 #include <TopTools_ListOfShape.hxx>
76 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS.hxx>
78 #include <TopoDS_Edge.hxx>
79 #include <TopoDS_Face.hxx>
80 #include <TopoDS_Vertex.hxx>
81 #include <gp_Ax1.hxx>
82 #include <gp_Vec.hxx>
83 #include <gp_XY.hxx>
84
85 #include <list>
86 #include <string>
87 #include <cmath>
88 #include <limits>
89
90 #ifdef _DEBUG_
91 //#define __myDEBUG
92 #endif
93
94 using namespace std;
95
96 //================================================================================
97 namespace VISCOUS_2D
98 {
99   typedef int TGeomID;
100
101   //--------------------------------------------------------------------------------
102   /*!
103    * \brief Proxy Mesh of FACE with viscous layers. It's needed only to 
104    *        redefine newSubmesh().
105    */
106   struct _ProxyMeshOfFace : public SMESH_ProxyMesh
107   {
108     //---------------------------------------------------
109     // Proxy sub-mesh of an EDGE. It contains nodes in _uvPtStructVec.
110     struct _EdgeSubMesh : public SMESH_ProxyMesh::SubMesh
111     {
112       _EdgeSubMesh(int index=0): SubMesh(index) {}
113       //virtual int NbElements() const { return _elements.size()+1; }
114       virtual int NbNodes() const { return Max( 0, _uvPtStructVec.size()-2 ); }
115       void SetUVPtStructVec(UVPtStructVec& vec) { _uvPtStructVec.swap( vec ); }
116     };
117     _ProxyMeshOfFace(const SMESH_Mesh& mesh): SMESH_ProxyMesh(mesh) {}
118     _EdgeSubMesh* GetEdgeSubMesh(int ID) { return (_EdgeSubMesh*) getProxySubMesh(ID); }
119     virtual SubMesh* newSubmesh(int index=0) const { return new _EdgeSubMesh(index); }
120   };
121   //--------------------------------------------------------------------------------
122   /*!
123    * \brief SMESH_subMeshEventListener used to store _ProxyMeshOfFace, computed
124    *        by _ViscousBuilder2D, in a SMESH_subMesh of the FACE.
125    *        This is to delete _ProxyMeshOfFace when StdMeshers_ViscousLayers2D
126    *        hypothesis is modified
127    */
128   struct _ProxyMeshHolder : public SMESH_subMeshEventListener
129   {
130     _ProxyMeshHolder( const TopoDS_Face&    face,
131                       SMESH_ProxyMesh::Ptr& mesh)
132       : SMESH_subMeshEventListener( /*deletable=*/true, Name() )
133     {
134       SMESH_subMesh* faceSM = mesh->GetMesh()->GetSubMesh( face );
135       faceSM->SetEventListener( this, new _Data( mesh ), faceSM );
136     }
137     // Finds a proxy mesh of face
138     static SMESH_ProxyMesh::Ptr FindProxyMeshOfFace( const TopoDS_Shape& face,
139                                                      SMESH_Mesh&         mesh )
140     {
141       SMESH_ProxyMesh::Ptr proxy;
142       SMESH_subMesh* faceSM = mesh.GetSubMesh( face );
143       if ( EventListenerData* ld = faceSM->GetEventListenerData( Name() ))
144         proxy = static_cast< _Data* >( ld )->_mesh;
145       return proxy;
146     }
147     // Treat events
148     void ProcessEvent(const int          event,
149                       const int          eventType,
150                       SMESH_subMesh*     subMesh,
151                       EventListenerData* data,
152                       const SMESH_Hypothesis*  /*hyp*/)
153     {
154       if ( event == SMESH_subMesh::CLEAN && eventType == SMESH_subMesh::COMPUTE_EVENT)
155         ((_Data*) data)->_mesh.reset();
156     }
157   private:
158     // holder of a proxy mesh
159     struct _Data : public SMESH_subMeshEventListenerData
160     {
161       SMESH_ProxyMesh::Ptr _mesh;
162       _Data( SMESH_ProxyMesh::Ptr& mesh )
163         :SMESH_subMeshEventListenerData( /*isDeletable=*/true), _mesh( mesh )
164       {}
165     };
166     // Returns identifier string
167     static const char* Name() { return "VISCOUS_2D::_ProxyMeshHolder"; }
168   };
169   
170   struct _PolyLine;
171   //--------------------------------------------------------------------------------
172   /*!
173    * \brief Segment connecting inner ends of two _LayerEdge's.
174    */
175   struct _Segment
176   {
177     const gp_XY* _uv[2];       // poiter to _LayerEdge::_uvIn
178     int          _indexInLine; // position in _PolyLine
179
180     _Segment() {}
181     _Segment(const gp_XY& p1, const gp_XY& p2):_indexInLine(-1) { _uv[0] = &p1; _uv[1] = &p2; }
182     const gp_XY& p1() const { return *_uv[0]; }
183     const gp_XY& p2() const { return *_uv[1]; }
184   };
185   //--------------------------------------------------------------------------------
186   /*!
187    * \brief Tree of _Segment's used for a faster search of _Segment's.
188    */
189   struct _SegmentTree : public SMESH_Quadtree
190   {
191     typedef boost::shared_ptr< _SegmentTree > Ptr;
192
193     _SegmentTree( const vector< _Segment >& segments );
194     void GetSegmentsNear( const _Segment& seg, vector< const _Segment* >& found );
195     void GetSegmentsNear( const gp_Ax2d& ray, vector< const _Segment* >& found );
196   protected:
197     _SegmentTree() {}
198     _SegmentTree* newChild() const { return new _SegmentTree; }
199     void          buildChildrenData();
200     Bnd_B2d*      buildRootBox();
201   private:
202     static int    maxNbSegInLeaf() { return 5; }
203     struct _SegBox
204     {
205       const _Segment* _seg;
206       bool            _iMin[2];
207       void Set( const _Segment& seg )
208       {
209         _seg = &seg;
210         _iMin[0] = ( seg._uv[1]->X() < seg._uv[0]->X() );
211         _iMin[1] = ( seg._uv[1]->Y() < seg._uv[0]->Y() );
212       }
213       bool IsOut( const _Segment& seg ) const;
214       bool IsOut( const gp_Ax2d& ray ) const;
215     };
216     vector< _SegBox > _segments;
217   };
218   //--------------------------------------------------------------------------------
219   /*!
220    * \brief Edge normal to FACE boundary, connecting a point on EDGE (_uvOut)
221    * and a point of a layer internal boundary (_uvIn)
222    */
223   struct _LayerEdge
224   {
225     gp_XY         _uvOut;    // UV on the FACE boundary
226     gp_XY         _uvIn;     // UV inside the FACE
227     double        _length2D; // distance between _uvOut and _uvIn
228
229     bool          _isBlocked;// is more inflation possible or not
230
231     gp_XY         _normal2D; // to curve
232     double        _len2dTo3dRatio; // to pass 2D <--> 3D
233     gp_Ax2d       _ray;      // a ray starting at _uvOut
234
235     vector<gp_XY> _uvRefined; // divisions by layers
236
237     bool SetNewLength( const double length );
238
239 #ifdef _DEBUG_
240     int           _ID;
241 #endif
242   };
243   //--------------------------------------------------------------------------------
244   /*!
245    * \brief Poly line composed of _Segment's of one EDGE.
246    *        It's used to detect intersection of inflated layers by intersecting
247    *        _Segment's in 2D.
248    */
249   struct _PolyLine
250   {
251     StdMeshers_FaceSide* _wire;
252     int                  _edgeInd;     // index of my EDGE in _wire
253     bool                 _advancable;  // true if there is a viscous layer on my EDGE
254     bool                 _isStraight2D;// pcurve type
255     _PolyLine*           _leftLine;    // lines of neighbour EDGE's
256     _PolyLine*           _rightLine;
257     int                  _firstPntInd; // index in vector<UVPtStruct> of _wire
258     int                  _lastPntInd;
259     int                  _index;       // index in _ViscousBuilder2D::_polyLineVec
260
261     vector< _LayerEdge > _lEdges;      /* _lEdges[0] is usually is not treated
262                                           as it is equal to the last one of the _leftLine */
263     vector< _Segment >   _segments;    // segments connecting _uvIn's of _lEdges
264     _SegmentTree::Ptr    _segTree;
265
266     vector< _PolyLine* > _reachableLines;       // lines able to interfere with my layer
267
268     vector< const SMDS_MeshNode* > _leftNodes;  // nodes built from a left VERTEX
269     vector< const SMDS_MeshNode* > _rightNodes; // nodes built from a right VERTEX
270
271     typedef vector< _Segment >::iterator   TSegIterator;
272     typedef vector< _LayerEdge >::iterator TEdgeIterator;
273
274     TIDSortedElemSet     _newFaces; // faces generated from this line
275
276     bool IsCommonEdgeShared( const _PolyLine& other );
277     size_t FirstLEdge() const
278     {
279       return ( _leftLine->_advancable && _lEdges.size() > 2 ) ? 1 : 0;
280     }
281     bool IsAdjacent( const _Segment& seg, const _LayerEdge* LE=0 ) const
282     {
283       if ( LE /*&& seg._indexInLine < _lEdges.size()*/ )
284         return ( seg._uv[0] == & LE->_uvIn ||
285                  seg._uv[1] == & LE->_uvIn );
286       return ( & seg == &_leftLine->_segments.back() ||
287                & seg == &_rightLine->_segments[0] );
288     }
289     bool IsConcave() const;
290   };
291   //--------------------------------------------------------------------------------
292   /*!
293    * \brief Intersector of _Segment's
294    */
295   struct _SegmentIntersection
296   {
297     gp_XY    _vec1, _vec2;     // Vec( _seg.p1(), _seg.p2() )
298     gp_XY    _vec21;           // Vec( _seg2.p1(), _seg1.p1() )
299     double   _D;               // _vec1.Crossed( _vec2 )
300     double   _param1, _param2; // intersection param on _seg1 and _seg2
301
302     bool Compute(const _Segment& seg1, const _Segment& seg2, bool seg2IsRay = false )
303     {
304       // !!! If seg2IsRay, returns true at any _param2 !!!
305       const double eps = 1e-10;
306       _vec1  = seg1.p2() - seg1.p1(); 
307       _vec2  = seg2.p2() - seg2.p1(); 
308       _vec21 = seg1.p1() - seg2.p1(); 
309       _D = _vec1.Crossed(_vec2);
310       if ( fabs(_D) < std::numeric_limits<double>::min())
311         return false;
312       _param1 = _vec2.Crossed(_vec21) / _D; 
313       if (_param1 < -eps || _param1 > 1 + eps )
314         return false;
315       _param2 = _vec1.Crossed(_vec21) / _D;
316       return seg2IsRay || ( _param2 > -eps && _param2 < 1 + eps );
317     }
318     bool Compute( const _Segment& seg1, const gp_Ax2d& ray )
319     {
320       gp_XY segEnd = ray.Location().XY() + ray.Direction().XY();
321       _Segment seg2( ray.Location().XY(), segEnd );
322       return Compute( seg1, seg2, true );
323     }
324     //gp_XY GetPoint() { return _seg1.p1() + _param1 * _vec1; }
325   };
326   //--------------------------------------------------------------------------------
327
328   typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
329   typedef StdMeshers_ViscousLayers2D                           THypVL;
330   
331   //--------------------------------------------------------------------------------
332   /*!
333    * \brief Builder of viscous layers
334    */
335   class _ViscousBuilder2D
336   {
337   public:
338     _ViscousBuilder2D(SMESH_Mesh&                       theMesh,
339                       const TopoDS_Face&                theFace,
340                       vector< const THypVL* > &         theHyp,
341                       vector< TopoDS_Shape > &          theHypShapes);
342     SMESH_ComputeErrorPtr GetError() const { return _error; }
343     // does it's job
344     SMESH_ProxyMesh::Ptr  Compute();
345
346   private:
347
348     friend class ::StdMeshers_ViscousLayers2D;
349
350     bool findEdgesWithLayers();
351     bool makePolyLines();
352     bool inflate();
353     bool fixCollisions();
354     bool refine();
355     bool shrink();
356     bool improve();
357     bool toShrinkForAdjacent( const TopoDS_Face& adjFace,
358                               const TopoDS_Edge& E,
359                               const TopoDS_Vertex& V);
360     void setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut );
361     void setLayerEdgeData( _LayerEdge&                 lEdge,
362                            const double                u,
363                            Handle(Geom2d_Curve)&       pcurve,
364                            Handle(Geom_Curve)&         curve,
365                            const gp_Pnt                pOut,
366                            const bool                  reverse,
367                            GeomAPI_ProjectPointOnSurf* faceProj);
368     void adjustCommonEdge( _PolyLine& LL, _PolyLine& LR );
369     void calcLayersHeight(const double    totalThick,
370                           vector<double>& heights,
371                           const THypVL*   hyp);
372     bool removeMeshFaces(const TopoDS_Shape& face);
373
374     const THypVL*     getLineHypothesis(int iPL);
375     double            getLineThickness (int iPL);
376
377     bool              error( const string& text );
378     SMESHDS_Mesh*     getMeshDS() { return _mesh->GetMeshDS(); }
379     _ProxyMeshOfFace* getProxyMesh();
380
381     // debug
382     //void makeGroupOfLE();
383
384   private:
385
386     // input data
387     SMESH_Mesh*                 _mesh;
388     TopoDS_Face                 _face;
389     vector< const THypVL* >     _hyps;
390     vector< TopoDS_Shape >      _hypShapes;
391
392     // result data
393     SMESH_ProxyMesh::Ptr        _proxyMesh;
394     SMESH_ComputeErrorPtr       _error;
395
396     // working data
397     Handle(Geom_Surface)        _surface;
398     SMESH_MesherHelper          _helper;
399     TSideVector                 _faceSideVec; // wires (StdMeshers_FaceSide) of _face
400     vector<_PolyLine>           _polyLineVec; // fronts to advance
401     vector< const THypVL* >     _hypOfEdge; // a hyp per an EDGE of _faceSideVec
402     bool                        _is2DIsotropic; // is same U and V resoulution of _face
403     vector<TopoDS_Face>         _clearedFaces; // FACEs whose mesh was removed by shrink()
404
405     //double                      _fPowN; // to compute thickness of layers
406     double                      _maxThickness; // max possible layers thickness
407
408     // sub-shapes of _face 
409     set<TGeomID>                _ignoreShapeIds; // ids of EDGEs w/o layers
410     set<TGeomID>                _noShrinkVert;   // ids of VERTEXes that are extremities
411     // of EDGEs along which _LayerEdge can't be inflated because no viscous layers
412     // defined on neighbour FACEs sharing an EDGE. Nonetheless _LayerEdge's
413     // are inflated along such EDGEs but then such _LayerEdge's are turned into
414     // a node on VERTEX, i.e. all nodes on a _LayerEdge are melded into one node.
415     
416     int                         _nbLE; // for DEBUG
417   };
418
419   //================================================================================
420   /*!
421    * \brief Returns StdMeshers_ViscousLayers2D for the FACE
422    */
423   bool findHyps(SMESH_Mesh&                                   theMesh,
424                 const TopoDS_Face&                            theFace,
425                 vector< const StdMeshers_ViscousLayers2D* > & theHyps,
426                 vector< TopoDS_Shape > &                      theAssignedTo)
427   {
428     theHyps.clear();
429     theAssignedTo.clear();
430     SMESH_HypoFilter hypFilter
431       ( SMESH_HypoFilter::HasName( StdMeshers_ViscousLayers2D::GetHypType() ));
432     list< const SMESHDS_Hypothesis * > hypList;
433     list< TopoDS_Shape >               hypShapes;
434     int nbHyps = theMesh.GetHypotheses
435       ( theFace, hypFilter, hypList, /*ancestors=*/true, &hypShapes );
436     if ( nbHyps )
437     {
438       theHyps.reserve( nbHyps );
439       theAssignedTo.reserve( nbHyps );
440       list< const SMESHDS_Hypothesis * >::iterator hyp = hypList.begin();
441       list< TopoDS_Shape >::iterator               shape = hypShapes.begin();
442       for ( ; hyp != hypList.end(); ++hyp, ++shape )
443       {
444         theHyps.push_back( static_cast< const StdMeshers_ViscousLayers2D* > ( *hyp ));
445         theAssignedTo.push_back( *shape );
446       }
447     }
448     return nbHyps;
449   }
450
451   //================================================================================
452   /*!
453    * \brief Returns ids of EDGEs not to create Viscous Layers on
454    *  \param [in] theHyp - the hypothesis, holding edges either to ignore or not to.
455    *  \param [in] theFace - the FACE whose EDGEs are checked.
456    *  \param [in] theMesh - the mesh.
457    *  \param [in,out] theEdgeIds - container returning EDGEs to ignore.
458    *  \return int - number of found EDGEs of the FACE.
459    */
460   //================================================================================
461
462   int getEdgesToIgnore( const StdMeshers_ViscousLayers2D* theHyp,
463                         const TopoDS_Shape&               theFace,
464                         const SMESHDS_Mesh*               theMesh,
465                         set< int > &                      theEdgeIds)
466   {
467     int nbEdgesToIgnore = 0;
468     vector<TGeomID> ids = theHyp->GetBndShapes();
469     if ( theHyp->IsToIgnoreShapes() ) // EDGEs to ignore are given
470     {
471       for ( size_t i = 0; i < ids.size(); ++i )
472       {
473         const TopoDS_Shape& E = theMesh->IndexToShape( ids[i] );
474         if ( !E.IsNull() &&
475              E.ShapeType() == TopAbs_EDGE &&
476              SMESH_MesherHelper::IsSubShape( E, theFace ))
477         {
478           theEdgeIds.insert( ids[i] );
479           ++nbEdgesToIgnore;
480         }
481       }
482     }
483     else // EDGEs to make the Viscous Layers on are given
484     {
485       TopExp_Explorer E( theFace, TopAbs_EDGE );
486       for ( ; E.More(); E.Next(), ++nbEdgesToIgnore )
487         theEdgeIds.insert( theMesh->ShapeToIndex( E.Current() ));
488
489       for ( size_t i = 0; i < ids.size(); ++i )
490         nbEdgesToIgnore -= theEdgeIds.erase( ids[i] );
491     }
492     return nbEdgesToIgnore;
493   }
494
495 } // namespace VISCOUS_2D
496
497 //================================================================================
498 // StdMeshers_ViscousLayers hypothesis
499 //
500 StdMeshers_ViscousLayers2D::StdMeshers_ViscousLayers2D(int hypId, int studyId, SMESH_Gen* gen)
501   :StdMeshers_ViscousLayers(hypId, studyId, gen)
502 {
503   _name = StdMeshers_ViscousLayers2D::GetHypType();
504   _param_algo_dim = -2; // auxiliary hyp used by 2D algos
505 }
506 // --------------------------------------------------------------------------------
507 bool StdMeshers_ViscousLayers2D::SetParametersByMesh(const SMESH_Mesh*   theMesh,
508                                                      const TopoDS_Shape& theShape)
509 {
510   // TODO ???
511   return false;
512 }
513 // --------------------------------------------------------------------------------
514 SMESH_ProxyMesh::Ptr
515 StdMeshers_ViscousLayers2D::Compute(SMESH_Mesh&        theMesh,
516                                     const TopoDS_Face& theFace)
517 {
518   SMESH_ProxyMesh::Ptr pm;
519
520   vector< const StdMeshers_ViscousLayers2D* > hyps;
521   vector< TopoDS_Shape >                      hypShapes;
522   if ( VISCOUS_2D::findHyps( theMesh, theFace, hyps, hypShapes ))
523   {
524     VISCOUS_2D::_ViscousBuilder2D builder( theMesh, theFace, hyps, hypShapes );
525     pm = builder.Compute();
526     SMESH_ComputeErrorPtr error = builder.GetError();
527     if ( error && !error->IsOK() )
528       theMesh.GetSubMesh( theFace )->GetComputeError() = error;
529     else if ( !pm )
530       pm.reset( new SMESH_ProxyMesh( theMesh ));
531     if ( getenv("__ONLY__VL2D__"))
532       pm.reset();
533   }
534   else
535   {
536     pm.reset( new SMESH_ProxyMesh( theMesh ));
537   }
538   return pm;
539 }
540 // --------------------------------------------------------------------------------
541 SMESH_ComputeErrorPtr
542 StdMeshers_ViscousLayers2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
543                                             const TopoDS_Shape&                  theShape,
544                                             SMESH_Hypothesis::Hypothesis_Status& theStatus)
545 {
546   SMESH_ComputeErrorPtr error = SMESH_ComputeError::New(COMPERR_OK);
547   theStatus = SMESH_Hypothesis::HYP_OK;
548
549   TopExp_Explorer exp( theShape, TopAbs_FACE );
550   for ( ; exp.More() && theStatus == SMESH_Hypothesis::HYP_OK; exp.Next() )
551   {
552     const TopoDS_Face& face = TopoDS::Face( exp.Current() );
553     vector< const StdMeshers_ViscousLayers2D* > hyps;
554     vector< TopoDS_Shape >                      hypShapes;
555     if ( VISCOUS_2D::findHyps( theMesh, face, hyps, hypShapes ))
556     {
557       VISCOUS_2D::_ViscousBuilder2D builder( theMesh, face, hyps, hypShapes );
558       builder._faceSideVec =
559         StdMeshers_FaceSide::GetFaceWires( face, theMesh, true, error,
560                                            SMESH_ProxyMesh::Ptr(),
561                                            /*theCheckVertexNodes=*/false);
562       if ( error->IsOK() && !builder.findEdgesWithLayers())
563       {
564         error = builder.GetError();
565         if ( error && !error->IsOK() )
566           theStatus = SMESH_Hypothesis::HYP_INCOMPAT_HYPS;
567       }
568     }
569   }
570   return error;
571 }
572 // --------------------------------------------------------------------------------
573 void StdMeshers_ViscousLayers2D::RestoreListeners() const
574 {
575   StudyContextStruct* sc = _gen->GetStudyContext( _studyId );
576   std::map < int, SMESH_Mesh * >::iterator i_smesh = sc->mapMesh.begin();
577   for ( ; i_smesh != sc->mapMesh.end(); ++i_smesh )
578   {
579     SMESH_Mesh* smesh = i_smesh->second;
580     if ( !smesh ||
581          !smesh->HasShapeToMesh() ||
582          !smesh->GetMeshDS() ||
583          !smesh->GetMeshDS()->IsUsedHypothesis( this ))
584       continue;
585
586     // set event listeners to EDGE's of FACE where this hyp is used
587     TopoDS_Shape shape = i_smesh->second->GetShapeToMesh();
588     for ( TopExp_Explorer face( shape, TopAbs_FACE); face.More(); face.Next() )
589       if ( SMESH_Algo* algo = _gen->GetAlgo( *smesh, face.Current() ))
590       {
591         const std::list <const SMESHDS_Hypothesis *> & usedHyps =
592           algo->GetUsedHypothesis( *smesh, face.Current(), /*ignoreAuxiliary=*/false );
593         if ( std::find( usedHyps.begin(), usedHyps.end(), this ) != usedHyps.end() )
594           for ( TopExp_Explorer edge( face.Current(), TopAbs_EDGE); edge.More(); edge.Next() )
595             VISCOUS_3D::ToClearSubWithMain( smesh->GetSubMesh( edge.Current() ), face.Current() );
596       }
597   }
598 }
599 // END StdMeshers_ViscousLayers2D hypothesis
600 //================================================================================
601
602 using namespace VISCOUS_2D;
603
604 //================================================================================
605 /*!
606  * \brief Constructor of _ViscousBuilder2D
607  */
608 //================================================================================
609
610 _ViscousBuilder2D::_ViscousBuilder2D(SMESH_Mesh&               theMesh,
611                                      const TopoDS_Face&        theFace,
612                                      vector< const THypVL* > & theHyps,
613                                      vector< TopoDS_Shape > &  theAssignedTo):
614   _mesh( &theMesh ), _face( theFace ), _helper( theMesh )
615 {
616   _hyps.swap( theHyps );
617   _hypShapes.swap( theAssignedTo );
618
619   _helper.SetSubShape( _face );
620   _helper.SetElementsOnShape( true );
621
622   _face.Orientation( TopAbs_FORWARD ); // 2D logic works only in this case
623   _surface = BRep_Tool::Surface( _face );
624
625   _error = SMESH_ComputeError::New(COMPERR_OK);
626
627   _nbLE = 0;
628 }
629
630 //================================================================================
631 /*!
632  * \brief Stores error description and returns false
633  */
634 //================================================================================
635
636 bool _ViscousBuilder2D::error(const string& text )
637 {
638   _error->myName    = COMPERR_ALGO_FAILED;
639   _error->myComment = string("Viscous layers builder 2D: ") + text;
640   if ( SMESH_subMesh* sm = _mesh->GetSubMesh( _face ) )
641   {
642     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
643     if ( smError && smError->myAlgo )
644       _error->myAlgo = smError->myAlgo;
645     smError = _error;
646   }
647 #ifdef _DEBUG_
648   cout << "_ViscousBuilder2D::error " << text << endl;
649 #endif
650   return false;
651 }
652
653 //================================================================================
654 /*!
655  * \brief Does its job
656  */
657 //================================================================================
658
659 SMESH_ProxyMesh::Ptr _ViscousBuilder2D::Compute()
660 {
661   _faceSideVec = StdMeshers_FaceSide::GetFaceWires( _face, *_mesh, true, _error);
662
663   if ( !_error->IsOK() )
664     return _proxyMesh;
665
666   if ( !findEdgesWithLayers() ) // analysis of a shape
667     return _proxyMesh;
668
669   if ( ! makePolyLines() ) // creation of fronts
670     return _proxyMesh;
671     
672   if ( ! inflate() ) // advance fronts
673     return _proxyMesh;
674
675   // remove elements and nodes from _face
676   removeMeshFaces( _face );
677
678   if ( !shrink() ) // shrink segments on edges w/o layers
679     return _proxyMesh;
680
681   if ( ! refine() ) // make faces
682     return _proxyMesh;
683
684   //improve();
685
686   return _proxyMesh;
687 }
688
689 //================================================================================
690 /*!
691  * \brief Finds EDGE's to make viscous layers on.
692  */
693 //================================================================================
694
695 bool _ViscousBuilder2D::findEdgesWithLayers()
696 {
697   // collect all EDGEs to ignore defined by _hyps
698   typedef std::pair< set<TGeomID>, const THypVL* > TEdgesOfHyp;
699   vector< TEdgesOfHyp > ignoreEdgesOfHyp( _hyps.size() );
700   for ( size_t i = 0; i < _hyps.size(); ++i )
701   {
702     ignoreEdgesOfHyp[i].second = _hyps[i];
703     getEdgesToIgnore( _hyps[i], _face, getMeshDS(), ignoreEdgesOfHyp[i].first );
704   }
705
706   // get all shared EDGEs
707   TopTools_MapOfShape sharedEdges;
708   TopTools_IndexedMapOfShape hypFaces; // faces with VL hyps
709   for ( size_t i = 0; i < _hypShapes.size(); ++i )
710     TopExp::MapShapes( _hypShapes[i], TopAbs_FACE, hypFaces );
711   TopTools_IndexedDataMapOfShapeListOfShape facesOfEdgeMap;
712   for ( int iF = 1; iF <= hypFaces.Extent(); ++iF )
713     TopExp::MapShapesAndAncestors( hypFaces(iF), TopAbs_EDGE, TopAbs_FACE, facesOfEdgeMap);
714   for ( int iE = 1; iE <= facesOfEdgeMap.Extent(); ++iE )
715     if ( facesOfEdgeMap( iE ).Extent() > 1 )
716       sharedEdges.Add( facesOfEdgeMap.FindKey( iE ));
717
718   // fill _hypOfEdge
719   if ( _hyps.size() > 1 )
720   {
721     // check if two hypotheses define different parameters for the same EDGE
722     for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
723     {
724       StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
725       for ( int iE = 0; iE < wire->NbEdges(); ++iE )
726       {
727         const THypVL* hyp = 0;
728         const TGeomID edgeID = wire->EdgeID( iE );
729         if ( !sharedEdges.Contains( wire->Edge( iE )))
730         {
731           for ( size_t i = 0; i < ignoreEdgesOfHyp.size(); ++i )
732             if ( ! ignoreEdgesOfHyp[i].first.count( edgeID ))
733             {
734               if ( hyp )
735                 return error(SMESH_Comment("Several hypotheses define "
736                                            "Viscous Layers on the edge #") << edgeID );
737               hyp = ignoreEdgesOfHyp[i].second;
738             }
739         }
740         _hypOfEdge.push_back( hyp );
741         if ( !hyp )
742           _ignoreShapeIds.insert( edgeID );
743       }
744       // check if two hypotheses define different number of viscous layers for
745       // adjacent EDGEs
746       const THypVL *hyp, *prevHyp = _hypOfEdge.back();
747       size_t iH = _hypOfEdge.size() - wire->NbEdges();
748       for ( ; iH < _hypOfEdge.size(); ++iH )
749       {
750         hyp = _hypOfEdge[ iH ];
751         if ( hyp && prevHyp &&
752              hyp->GetNumberLayers() != prevHyp->GetNumberLayers() )
753         {
754           return error("Two hypotheses define different number of "
755                        "viscous layers on adjacent edges");
756         }
757         prevHyp = hyp;
758       }
759     }
760   }
761   else if ( _hyps.size() == 1 )
762   {
763     _ignoreShapeIds.swap( ignoreEdgesOfHyp[0].first );
764   }
765
766   // check all EDGEs of the _face to fill _ignoreShapeIds and _noShrinkVert
767
768   int totalNbEdges = 0;
769   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
770   {
771     StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
772     totalNbEdges += wire->NbEdges();
773     for ( int iE = 0; iE < wire->NbEdges(); ++iE )
774     {
775       if ( sharedEdges.Contains( wire->Edge( iE )))
776       {
777         // ignore internal EDGEs (shared by several FACEs)
778         const TGeomID edgeID = wire->EdgeID( iE );
779         _ignoreShapeIds.insert( edgeID );
780
781         // check if ends of an EDGE are to be added to _noShrinkVert
782         const TopTools_ListOfShape& faceList = facesOfEdgeMap.FindFromKey( wire->Edge( iE ));
783         TopTools_ListIteratorOfListOfShape faceIt( faceList );
784         for ( ; faceIt.More(); faceIt.Next() )
785         {
786           const TopoDS_Shape& neighbourFace = faceIt.Value();
787           if ( neighbourFace.IsSame( _face )) continue;
788           SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, neighbourFace );
789           if ( !algo ) continue;
790
791           const StdMeshers_ViscousLayers2D* viscHyp = 0;
792           const list <const SMESHDS_Hypothesis *> & allHyps =
793             algo->GetUsedHypothesis(*_mesh, neighbourFace, /*noAuxiliary=*/false);
794           list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
795           for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
796             viscHyp = dynamic_cast<const StdMeshers_ViscousLayers2D*>( *hyp );
797
798           // set<TGeomID> neighbourIgnoreEdges;
799           // if (viscHyp)
800           //   getEdgesToIgnore( viscHyp, neighbourFace, getMeshDS(), neighbourIgnoreEdges );
801
802           for ( int iV = 0; iV < 2; ++iV )
803           {
804             TopoDS_Vertex vertex = iV ? wire->LastVertex(iE) : wire->FirstVertex(iE);
805             if ( !viscHyp )
806               _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
807             else
808             {
809               PShapeIteratorPtr edgeIt = _helper.GetAncestors( vertex, *_mesh, TopAbs_EDGE );
810               while ( const TopoDS_Shape* edge = edgeIt->next() )
811                 if ( !edge->IsSame( wire->Edge( iE )) &&
812                      _helper.IsSubShape( *edge, neighbourFace ))
813                 {
814                   const TGeomID neighbourID = getMeshDS()->ShapeToIndex( *edge );
815                   bool hasVL = !sharedEdges.Contains( *edge );
816                   if ( hasVL )
817                   {
818                     hasVL = false;
819                     for ( hyp = allHyps.begin(); hyp != allHyps.end() && !hasVL; ++hyp )
820                       if (( viscHyp = dynamic_cast<const THypVL*>( *hyp )))
821                         hasVL = viscHyp->IsShapeWithLayers( neighbourID );
822                   }
823                   if ( !hasVL )
824                   {
825                     _noShrinkVert.insert( getMeshDS()->ShapeToIndex( vertex ));
826                     break;
827                   }
828                 }
829             }
830           }
831         }
832       }
833     }
834   }
835
836   int nbMyEdgesIgnored = _ignoreShapeIds.size();
837
838   // add VERTEXes w/o layers to _ignoreShapeIds (this is used by toShrinkForAdjacent())
839   // for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
840   // {
841   //   StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
842   //   for ( int iE = 0; iE < wire->NbEdges(); ++iE )
843   //   {
844   //     TGeomID edge1 = wire->EdgeID( iE );
845   //     TGeomID edge2 = wire->EdgeID( iE+1 );
846   //     if ( _ignoreShapeIds.count( edge1 ) && _ignoreShapeIds.count( edge2 ))
847   //       _ignoreShapeIds.insert( getMeshDS()->ShapeToIndex( wire->LastVertex( iE )));
848   //   }
849   // }
850
851   return ( nbMyEdgesIgnored < totalNbEdges );
852 }
853
854 //================================================================================
855 /*!
856  * \brief Create the inner front of the viscous layers and prepare data for inflation
857  */
858 //================================================================================
859
860 bool _ViscousBuilder2D::makePolyLines()
861 {
862   // Create _PolyLines and _LayerEdge's
863
864   // count total nb of EDGEs to allocate _polyLineVec
865   int nbEdges = 0;
866   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
867   {
868     StdMeshers_FaceSidePtr wire = _faceSideVec[ iWire ];
869     nbEdges += wire->NbEdges();
870     if ( wire->GetUVPtStruct().empty() && wire->NbPoints() > 0 )
871       return error("Invalid node parameters on some EDGE");
872   }
873   _polyLineVec.resize( nbEdges );
874
875   // check if 2D normal should be computed by 3D one by means of projection
876   GeomAPI_ProjectPointOnSurf* faceProj = 0;
877   TopLoc_Location loc;
878   {
879     _LayerEdge tmpLE;
880     const UVPtStruct& uv = _faceSideVec[0]->GetUVPtStruct()[0];
881     gp_Pnt p = SMESH_TNodeXYZ( uv.node );
882     tmpLE._uvOut.SetCoord( uv.u, uv.v );
883     tmpLE._normal2D.SetCoord( 1., 0. );
884     setLenRatio( tmpLE, p );
885     const double r1 = tmpLE._len2dTo3dRatio;
886     tmpLE._normal2D.SetCoord( 0., 1. );
887     setLenRatio( tmpLE, p );
888     const double r2 = tmpLE._len2dTo3dRatio;
889     // projection is needed if two _len2dTo3dRatio's differ too much
890     const double maxR = Max( r2, r1 );
891     if ( Abs( r2-r1 )/maxR > 0.2*maxR )
892       faceProj = & _helper.GetProjector( _face, loc );
893   }
894   _is2DIsotropic = !faceProj;
895
896   // Assign data to _PolyLine's
897   // ---------------------------
898
899   size_t iPoLine = 0;
900   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
901   {
902     StdMeshers_FaceSidePtr      wire = _faceSideVec[ iWire ];
903     const vector<UVPtStruct>& points = wire->GetUVPtStruct();
904     int iPnt = 0;
905     for ( int iE = 0; iE < wire->NbEdges(); ++iE )
906     {
907       _PolyLine& L  = _polyLineVec[ iPoLine++ ];
908       L._index      = iPoLine-1;
909       L._wire       = wire.get();
910       L._edgeInd    = iE;
911       L._advancable = !_ignoreShapeIds.count( wire->EdgeID( iE ));
912
913       int iRight    = iPoLine - (( iE+1 < wire->NbEdges() ) ? 0 : wire->NbEdges() );
914       L._rightLine  = &_polyLineVec[ iRight ];
915       _polyLineVec[ iRight ]._leftLine = &L;
916
917       L._firstPntInd = iPnt;
918       double lastNormPar = wire->LastParameter( iE ) - 1e-10;
919       while ( points[ iPnt ].normParam < lastNormPar )
920         ++iPnt;
921       L._lastPntInd = iPnt;
922       L._lEdges.resize( Max( 3, L._lastPntInd - L._firstPntInd + 1 )); // 3 edges minimum
923
924       // TODO: add more _LayerEdge's to strongly curved EDGEs
925       // in order not to miss collisions
926
927       double u; gp_Pnt p;
928       Handle(Geom_Curve)   curve  = BRep_Tool::Curve( L._wire->Edge( iE ), loc, u, u );
929       Handle(Geom2d_Curve) pcurve = L._wire->Curve2d( L._edgeInd );
930       const bool reverse = (( L._wire->Edge( iE ).Orientation() == TopAbs_REVERSED ) ^
931                             (_face.Orientation()                == TopAbs_REVERSED ));
932       for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
933       {
934         _LayerEdge& lEdge = L._lEdges[ i - L._firstPntInd ];
935         u = ( i == L._firstPntInd ? wire->FirstU(iE) : points[ i ].param );
936         p = SMESH_TNodeXYZ( points[ i ].node );
937         setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, faceProj );
938         setLenRatio( lEdge, p );
939       }
940       if ( L._lastPntInd - L._firstPntInd + 1 < 3 ) // add 3-d _LayerEdge in the middle
941       {
942         L._lEdges[2] = L._lEdges[1];
943         u = 0.5 * ( wire->FirstU(iE) + wire->LastU(iE) );
944         if ( !curve.IsNull() )
945           p = curve->Value( u );
946         else
947           p = 0.5 * ( SMESH_TNodeXYZ( points[ L._firstPntInd ].node ) +
948                       SMESH_TNodeXYZ( points[ L._lastPntInd ].node ));
949         setLayerEdgeData( L._lEdges[1], u, pcurve, curve, p, reverse, faceProj );
950         setLenRatio( L._lEdges[1], p );
951       }
952     }
953   }
954
955   // Fill _PolyLine's with _segments
956   // --------------------------------
957
958   double maxLen2dTo3dRatio = 0;
959   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
960   {
961     _PolyLine& L = _polyLineVec[ iPoLine ];
962     L._segments.resize( L._lEdges.size() - 1 );
963     for ( size_t i = 1; i < L._lEdges.size(); ++i )
964     {
965       _Segment & S   = L._segments[i-1];
966       S._uv[0]       = & L._lEdges[i-1]._uvIn;
967       S._uv[1]       = & L._lEdges[i  ]._uvIn;
968       S._indexInLine = i-1;
969       if ( maxLen2dTo3dRatio < L._lEdges[i]._len2dTo3dRatio )
970         maxLen2dTo3dRatio = L._lEdges[i]._len2dTo3dRatio;
971     }
972     // // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
973     // // becomes not connected to any segment
974     // if ( L._leftLine->_advancable )
975     //   L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
976
977     L._segTree.reset( new _SegmentTree( L._segments ));
978   }
979
980   // Evaluate max possible _thickness if required layers thickness seems too high
981   // ----------------------------------------------------------------------------
982
983   _maxThickness = _hyps[0]->GetTotalThickness();
984   for ( size_t iH = 1; iH < _hyps.size(); ++iH )
985     _maxThickness = Max( _maxThickness, _hyps[iH]->GetTotalThickness() );
986
987   _SegmentTree::box_type faceBndBox2D;
988   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
989     faceBndBox2D.Add( *_polyLineVec[ iPoLine]._segTree->getBox() );
990   const double boxTol = 1e-3 * sqrt( faceBndBox2D.SquareExtent() );
991
992   if ( _maxThickness * maxLen2dTo3dRatio > sqrt( faceBndBox2D.SquareExtent() ) / 10 )
993   {
994     vector< const _Segment* > foundSegs;
995     double maxPossibleThick = 0;
996     _SegmentIntersection intersection;
997     for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
998     {
999       _PolyLine& L1 = _polyLineVec[ iL1 ];
1000       _SegmentTree::box_type boxL1 = * L1._segTree->getBox();
1001       boxL1.Enlarge( boxTol );
1002       // consider case of a circle as well!
1003       for ( size_t iL2 = iL1; iL2 < _polyLineVec.size(); ++iL2 )
1004       {
1005         _PolyLine& L2 = _polyLineVec[ iL2 ];
1006         _SegmentTree::box_type boxL2 = * L2._segTree->getBox();
1007         boxL2.Enlarge( boxTol );
1008         if ( boxL1.IsOut( boxL2 ))
1009           continue;
1010         for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1011         {
1012           foundSegs.clear();
1013           L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1014           for ( size_t i = 0; i < foundSegs.size(); ++i )
1015             if ( intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1016             {
1017               double  distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1018               double psblThick = distToL2 / ( 1 + L1._advancable + L2._advancable );
1019               maxPossibleThick = Max( psblThick, maxPossibleThick );
1020             }
1021         }
1022       }
1023     }
1024     if ( maxPossibleThick > 0. )
1025       _maxThickness = Min( _maxThickness, maxPossibleThick );
1026   }
1027
1028   // Adjust _LayerEdge's at _PolyLine's extremities
1029   // -----------------------------------------------
1030
1031   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1032   {
1033     _PolyLine& LL = _polyLineVec[ iPoLine ];
1034     _PolyLine& LR = *LL._rightLine;
1035     adjustCommonEdge( LL, LR );
1036   }
1037   // recreate _segments if some _LayerEdge's have been removed by adjustCommonEdge()
1038   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1039   {
1040     _PolyLine& L = _polyLineVec[ iPoLine ];
1041     // if ( L._segments.size() ==  L._lEdges.size() - 1 )
1042     //   continue;
1043     L._segments.resize( L._lEdges.size() - 1 );
1044     for ( size_t i = 1; i < L._lEdges.size(); ++i )
1045     {
1046       _Segment & S   = L._segments[i-1];
1047       S._uv[0]       = & L._lEdges[i-1]._uvIn;
1048       S._uv[1]       = & L._lEdges[i  ]._uvIn;
1049       S._indexInLine = i-1;
1050     }
1051     L._segTree.reset( new _SegmentTree( L._segments ));
1052   }
1053   // connect _PolyLine's with segments, the 1st _LayerEdge of every _PolyLine
1054   // becomes not connected to any segment
1055   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1056   {
1057     _PolyLine& L = _polyLineVec[ iPoLine ];
1058     if ( L._leftLine->_advancable )
1059       L._segments[0]._uv[0] = & L._leftLine->_lEdges.back()._uvIn;
1060   }
1061
1062   // Fill _reachableLines.
1063   // ----------------------
1064
1065   // compute bnd boxes taking into account the layers total thickness
1066   vector< _SegmentTree::box_type > lineBoxes( _polyLineVec.size() );
1067   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1068   {
1069     lineBoxes[ iPoLine ] = *_polyLineVec[ iPoLine ]._segTree->getBox();
1070     lineBoxes[ iPoLine ].Enlarge( maxLen2dTo3dRatio * getLineThickness( iPoLine ) * 
1071                                   ( _polyLineVec[ iPoLine ]._advancable ? 2. : 1.2 ));
1072   }
1073   // _reachableLines
1074   for ( iPoLine = 0; iPoLine < _polyLineVec.size(); ++iPoLine )
1075   {
1076     _PolyLine& L1 = _polyLineVec[ iPoLine ];
1077     const double thick1 = getLineThickness( iPoLine );
1078     for ( size_t iL2 = 0; iL2 < _polyLineVec.size(); ++iL2 )
1079     {
1080       _PolyLine& L2 = _polyLineVec[ iL2 ];
1081       if ( iPoLine == iL2 || lineBoxes[ iPoLine ].IsOut( lineBoxes[ iL2 ]))
1082         continue;
1083       if ( !L1._advancable && ( L1._leftLine == &L2 || L1._rightLine == &L2 ))
1084         continue;
1085       // check reachability by _LayerEdge's
1086       int iDelta = 1; //Max( 1, L1._lEdges.size() / 100 );
1087       for ( size_t iLE = 1; iLE < L1._lEdges.size(); iLE += iDelta )
1088       {
1089         _LayerEdge& LE = L1._lEdges[iLE];
1090         if ( !lineBoxes[ iL2 ].IsOut ( LE._uvOut,
1091                                        LE._uvOut + LE._normal2D * thick1 * LE._len2dTo3dRatio ))
1092         {
1093           L1._reachableLines.push_back( & L2 );
1094           break;
1095         }
1096       }
1097     }
1098     // add self to _reachableLines
1099     Geom2dAdaptor_Curve pcurve( L1._wire->Curve2d( L1._edgeInd ));
1100     L1._isStraight2D = ( pcurve.GetType() == GeomAbs_Line );
1101     if ( !L1._isStraight2D )
1102     {
1103       // TODO: check carefully
1104       L1._reachableLines.push_back( & L1 );
1105     }
1106   }
1107
1108   return true;
1109 }
1110
1111 //================================================================================
1112 /*!
1113  * \brief adjust common _LayerEdge of two adjacent _PolyLine's
1114  *  \param LL - left _PolyLine
1115  *  \param LR - right _PolyLine
1116  */
1117 //================================================================================
1118
1119 void _ViscousBuilder2D::adjustCommonEdge( _PolyLine& LL, _PolyLine& LR )
1120 {
1121   int nbAdvancableL = LL._advancable + LR._advancable;
1122   if ( nbAdvancableL == 0 )
1123     return;
1124
1125   _LayerEdge& EL = LL._lEdges.back();
1126   _LayerEdge& ER = LR._lEdges.front();
1127   gp_XY normL    = EL._normal2D;
1128   gp_XY normR    = ER._normal2D;
1129   gp_XY tangL ( normL.Y(), -normL.X() );
1130
1131   // set common direction to a VERTEX _LayerEdge shared by two _PolyLine's
1132   gp_XY normCommon = ( normL * int( LL._advancable ) +
1133                        normR * int( LR._advancable )).Normalized();
1134   EL._normal2D = normCommon;
1135   EL._ray.SetLocation ( EL._uvOut );
1136   EL._ray.SetDirection( EL._normal2D );
1137   if ( nbAdvancableL == 1 ) { // _normal2D is true normal (not average)
1138     EL._isBlocked = true; // prevent intersecting with _Segments of _advancable line
1139     EL._length2D  = 0;
1140   }
1141   // update _LayerEdge::_len2dTo3dRatio according to a new direction
1142   const vector<UVPtStruct>& points = LL._wire->GetUVPtStruct();
1143   setLenRatio( EL, SMESH_TNodeXYZ( points[ LL._lastPntInd ].node ));
1144
1145   ER = EL;
1146
1147   const double dotNormTang = normR * tangL;
1148   const bool    largeAngle = Abs( dotNormTang ) > 0.2;
1149   if ( largeAngle ) // not 180 degrees
1150   {
1151     // recompute _len2dTo3dRatio to take into account angle between EDGEs
1152     gp_Vec2d oldNorm( LL._advancable ? normL : normR );
1153     double angleFactor  = 1. / Max( 0.3, Cos( oldNorm.Angle( normCommon )));
1154     EL._len2dTo3dRatio *= angleFactor;
1155     ER._len2dTo3dRatio  = EL._len2dTo3dRatio;
1156
1157     gp_XY normAvg = ( normL + normR ).Normalized(); // average normal at VERTEX
1158
1159     if ( dotNormTang < 0. ) // ---------------------------- CONVEX ANGLE
1160     {
1161       // Remove _LayerEdge's intersecting the normAvg to avoid collisions
1162       // during inflate().
1163       //
1164       // find max length of the VERTEX-based _LayerEdge whose direction is normAvg
1165       double       maxLen2D  = _maxThickness * EL._len2dTo3dRatio;
1166       const gp_XY& pCommOut  = ER._uvOut;
1167       gp_XY        pCommIn   = pCommOut + normAvg * maxLen2D;
1168       _Segment segCommon( pCommOut, pCommIn );
1169       _SegmentIntersection intersection;
1170       vector< const _Segment* > foundSegs;
1171       for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1172       {
1173         _PolyLine& L1 = _polyLineVec[ iL1 ];
1174         const _SegmentTree::box_type* boxL1 = L1._segTree->getBox();
1175         if ( boxL1->IsOut ( pCommOut, pCommIn ))
1176           continue;
1177         for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1178         {
1179           foundSegs.clear();
1180           L1._segTree->GetSegmentsNear( segCommon, foundSegs );
1181           for ( size_t i = 0; i < foundSegs.size(); ++i )
1182             if ( intersection.Compute( *foundSegs[i], segCommon ) &&
1183                  intersection._param2 > 1e-10 )
1184             {
1185               double len2D = intersection._param2 * maxLen2D / ( 2 + L1._advancable );
1186               if ( len2D < maxLen2D ) {
1187                 maxLen2D = len2D;
1188                 pCommIn  = pCommOut + normAvg * maxLen2D; // here length of segCommon changes
1189               }
1190             }
1191         }
1192       }
1193
1194       // remove _LayerEdge's intersecting segCommon
1195       for ( int isR = 0; isR < 2; ++isR ) // loop on [ LL, LR ]
1196       {
1197         _PolyLine&                 L = isR ? LR : LL;
1198         _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1199         int                      dIt = isR ? +1 : -1;
1200         if ( nbAdvancableL == 1 && L._advancable && normL * normR > -0.01 )
1201           continue;  // obtuse internal angle
1202         // at least 3 _LayerEdge's should remain in a _PolyLine
1203         if ( L._lEdges.size() < 4 ) continue;
1204         size_t iLE = 1;
1205         _SegmentIntersection lastIntersection;
1206         for ( ; iLE < L._lEdges.size(); ++iLE, eIt += dIt )
1207         {
1208           gp_XY uvIn = eIt->_uvOut + eIt->_normal2D * _maxThickness * eIt->_len2dTo3dRatio;
1209           _Segment segOfEdge( eIt->_uvOut, uvIn );
1210           if ( !intersection.Compute( segCommon, segOfEdge ))
1211             break;
1212           lastIntersection._param1 = intersection._param1;
1213           lastIntersection._param2 = intersection._param2;
1214         }
1215         if ( iLE >= L._lEdges.size() - 1 )
1216         {
1217           // all _LayerEdge's intersect the segCommon, limit inflation
1218           // of remaining 3 _LayerEdge's
1219           vector< _LayerEdge > newEdgeVec( Min( 3, L._lEdges.size() ));
1220           newEdgeVec.front() = L._lEdges.front();
1221           newEdgeVec.back()  = L._lEdges.back();
1222           if ( newEdgeVec.size() == 3 )
1223           {
1224             newEdgeVec[1] = L._lEdges[ isR ? (L._lEdges.size() - 2) : 1 ];
1225             newEdgeVec[1]._len2dTo3dRatio *= lastIntersection._param2;
1226           }
1227           L._lEdges.swap( newEdgeVec );
1228           if ( !isR ) std::swap( lastIntersection._param1 , lastIntersection._param2 );
1229           L._lEdges.front()._len2dTo3dRatio *= lastIntersection._param1; // ??
1230           L._lEdges.back ()._len2dTo3dRatio *= lastIntersection._param2;
1231         }
1232         else if ( iLE != 1 )
1233         {
1234           // eIt points to the _LayerEdge not intersecting with segCommon
1235           if ( isR )
1236             LR._lEdges.erase( LR._lEdges.begin()+1, eIt );
1237           else
1238             LL._lEdges.erase( eIt, --LL._lEdges.end() );
1239           // eIt = isR ? L._lEdges.begin()+1 : L._lEdges.end()-2;
1240           // for ( size_t i = 1; i < iLE; ++i, eIt += dIt )
1241           //   eIt->_isBlocked = true;
1242         }
1243       }
1244     }
1245     else // ------------------------------------------ CONCAVE ANGLE
1246     {
1247       if ( nbAdvancableL == 1 )
1248       {
1249         // make that the _LayerEdge at VERTEX is not shared by LL and LR:
1250         // different normals is a sign that they are not shared
1251         _LayerEdge& notSharedEdge = LL._advancable ? LR._lEdges[0] : LL._lEdges.back();
1252         _LayerEdge&    sharedEdge = LR._advancable ? LR._lEdges[0] : LL._lEdges.back();
1253
1254         notSharedEdge._normal2D.SetCoord( 0.,0. );
1255         sharedEdge._normal2D     = normAvg;
1256         sharedEdge._isBlocked    = false;
1257         notSharedEdge._isBlocked = true;
1258       }
1259     }
1260   }
1261 }
1262
1263 //================================================================================
1264 /*!
1265  * \brief initialize data of a _LayerEdge
1266  */
1267 //================================================================================
1268
1269 void _ViscousBuilder2D::setLayerEdgeData( _LayerEdge&                 lEdge,
1270                                           const double                u,
1271                                           Handle(Geom2d_Curve)&       pcurve,
1272                                           Handle(Geom_Curve)&         curve,
1273                                           const gp_Pnt                pOut,
1274                                           const bool                  reverse,
1275                                           GeomAPI_ProjectPointOnSurf* faceProj)
1276 {
1277   gp_Pnt2d uv;
1278   if ( faceProj && !curve.IsNull() )
1279   {
1280     uv = pcurve->Value( u );
1281     gp_Vec tangent; gp_Pnt p; gp_Vec du, dv;
1282     curve->D1( u, p, tangent );
1283     if ( reverse )
1284       tangent.Reverse();
1285     _surface->D1( uv.X(), uv.Y(), p, du, dv );
1286     gp_Vec faceNorm = du ^ dv;
1287     gp_Vec normal   = faceNorm ^ tangent;
1288     normal.Normalize();
1289     p = pOut.XYZ() + normal.XYZ() * /*1e-2 * */_hyps[0]->GetTotalThickness() / _hyps[0]->GetNumberLayers();
1290     faceProj->Perform( p );
1291     if ( !faceProj->IsDone() || faceProj->NbPoints() < 1 )
1292       return setLayerEdgeData( lEdge, u, pcurve, curve, p, reverse, NULL );
1293     Quantity_Parameter U,V;
1294     faceProj->LowerDistanceParameters(U,V);
1295     lEdge._normal2D.SetCoord( U - uv.X(), V - uv.Y() );
1296     lEdge._normal2D.Normalize();
1297   }
1298   else
1299   {
1300     gp_Vec2d tangent;
1301     pcurve->D1( u, uv, tangent );
1302     tangent.Normalize();
1303     if ( reverse )
1304       tangent.Reverse();
1305     lEdge._normal2D.SetCoord( -tangent.Y(), tangent.X() );
1306   }
1307   lEdge._uvOut = lEdge._uvIn = uv.XY();
1308   lEdge._ray.SetLocation ( lEdge._uvOut );
1309   lEdge._ray.SetDirection( lEdge._normal2D );
1310   lEdge._isBlocked = false;
1311   lEdge._length2D  = 0;
1312 #ifdef _DEBUG_
1313   lEdge._ID        = _nbLE++;
1314 #endif
1315 }
1316
1317 //================================================================================
1318 /*!
1319  * \brief Compute and set _LayerEdge::_len2dTo3dRatio
1320  */
1321 //================================================================================
1322
1323 void _ViscousBuilder2D::setLenRatio( _LayerEdge& LE, const gp_Pnt& pOut )
1324 {
1325   const double probeLen2d = 1e-3;
1326
1327   gp_Pnt2d p2d = LE._uvOut + LE._normal2D * probeLen2d;
1328   gp_Pnt   p3d = _surface->Value( p2d.X(), p2d.Y() );
1329   double len3d = p3d.Distance( pOut );
1330   if ( len3d < std::numeric_limits<double>::min() )
1331     LE._len2dTo3dRatio = std::numeric_limits<double>::min();
1332   else
1333     LE._len2dTo3dRatio = probeLen2d / len3d;
1334 }
1335
1336 //================================================================================
1337 /*!
1338  * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1339  */
1340 //================================================================================
1341
1342 bool _ViscousBuilder2D::inflate()
1343 {
1344   // Limit size of inflation step by geometry size found by
1345   // itersecting _LayerEdge's with _Segment's
1346   double minSize = _maxThickness, maxSize = 0;
1347   vector< const _Segment* > foundSegs;
1348   _SegmentIntersection intersection;
1349   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1350   {
1351     _PolyLine& L1 = _polyLineVec[ iL1 ];
1352     for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1353     {
1354       _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1355       for ( size_t iLE = 1; iLE < L1._lEdges.size(); ++iLE )
1356       {
1357         foundSegs.clear();
1358         L2._segTree->GetSegmentsNear( L1._lEdges[iLE]._ray, foundSegs );
1359         for ( size_t i = 0; i < foundSegs.size(); ++i )
1360           if ( ! L1.IsAdjacent( *foundSegs[i], & L1._lEdges[iLE] ) &&
1361                intersection.Compute( *foundSegs[i], L1._lEdges[iLE]._ray ))
1362           {
1363             double distToL2 = intersection._param2 / L1._lEdges[iLE]._len2dTo3dRatio;
1364             double     size = distToL2 / ( 1 + L1._advancable + L2._advancable );
1365             if ( 1e-10 < size && size < minSize )
1366               minSize = size;
1367             if ( size > maxSize )
1368               maxSize = size;
1369           }
1370       }
1371     }
1372   }
1373   if ( minSize > maxSize ) // no collisions possible
1374     maxSize = _maxThickness;
1375 #ifdef __myDEBUG
1376   cout << "-- minSize = " << minSize << ", maxSize = " << maxSize << endl;
1377 #endif
1378
1379   double curThick = 0, stepSize = minSize;
1380   int nbSteps = 0;
1381   if ( maxSize > _maxThickness )
1382     maxSize = _maxThickness;
1383   while ( curThick < maxSize )
1384   {
1385     curThick += stepSize * 1.25;
1386     if ( curThick > _maxThickness )
1387       curThick = _maxThickness;
1388
1389     // Elongate _LayerEdge's
1390     for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1391     {
1392       _PolyLine& L = _polyLineVec[ iL ];
1393       if ( !L._advancable ) continue;
1394       const double lineThick = Min( curThick, getLineThickness( iL ));
1395       bool lenChange = false;
1396       for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1397         lenChange |= L._lEdges[iLE].SetNewLength( lineThick );
1398       // for ( int k=0; k<L._segments.size(); ++k)
1399       //   cout << "( " << L._segments[k].p1().X() << ", " <<L._segments[k].p1().Y() << " ) "
1400       //        << "( " << L._segments[k].p2().X() << ", " <<L._segments[k].p2().Y() << " ) "
1401       //        << endl;
1402       if ( lenChange )
1403         L._segTree.reset( new _SegmentTree( L._segments ));
1404     }
1405
1406     // Avoid intersection of _Segment's
1407     bool allBlocked = fixCollisions();
1408     if ( allBlocked )
1409     {
1410       break; // no more inflating possible
1411     }
1412     stepSize = Max( stepSize , _maxThickness / 10. );
1413     nbSteps++;
1414   }
1415
1416   // if (nbSteps == 0 )
1417   //   return error("failed at the very first inflation step");
1418
1419
1420   // remove _LayerEdge's of one line intersecting with each other
1421   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1422   {
1423     _PolyLine& L = _polyLineVec[ iL ];
1424     if ( !L._advancable ) continue;
1425
1426     // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
1427     if ( /*!L._leftLine->_advancable &&*/ L.IsCommonEdgeShared( *L._leftLine ) ) {
1428       L._lEdges[0] = L._leftLine->_lEdges.back();
1429     }
1430     if ( !L._rightLine->_advancable && L.IsCommonEdgeShared( *L._rightLine ) ) {
1431       L._lEdges.back() = L._rightLine->_lEdges[0];
1432     }
1433
1434     _SegmentIntersection intersection;
1435     for ( int isR = 0; ( isR < 2 && L._lEdges.size() > 2 ); ++isR )
1436     {
1437       int nbRemove = 0, deltaIt = isR ? -1 : +1;
1438       _PolyLine::TEdgeIterator eIt = isR ? L._lEdges.end()-1 : L._lEdges.begin();
1439       if ( eIt->_length2D == 0 ) continue;
1440       _Segment seg1( eIt->_uvOut, eIt->_uvIn );
1441       for ( eIt += deltaIt; nbRemove < (int)L._lEdges.size()-1; eIt += deltaIt )
1442       {
1443         _Segment seg2( eIt->_uvOut, eIt->_uvIn );
1444         if ( !intersection.Compute( seg1, seg2 ))
1445           break;
1446         ++nbRemove;
1447       }
1448       if ( nbRemove > 0 ) {
1449         if ( nbRemove == (int)L._lEdges.size()-1 ) // 1st and last _LayerEdge's intersect
1450         {
1451           --nbRemove;
1452           _LayerEdge& L0 = L._lEdges.front();
1453           _LayerEdge& L1 = L._lEdges.back();
1454           L0._length2D *= intersection._param1 * 0.5;
1455           L1._length2D *= intersection._param2 * 0.5;
1456           L0._uvIn = L0._uvOut + L0._normal2D * L0._length2D;
1457           L1._uvIn = L1._uvOut + L1._normal2D * L1._length2D;
1458           if ( L.IsCommonEdgeShared( *L._leftLine ))
1459             L._leftLine->_lEdges.back() = L0;
1460         }
1461         if ( isR )
1462           L._lEdges.erase( L._lEdges.end()-nbRemove-1,
1463                            L._lEdges.end()-nbRemove );
1464         else
1465           L._lEdges.erase( L._lEdges.begin()+1,
1466                            L._lEdges.begin()+1+nbRemove );
1467       }
1468     }
1469   }
1470   return true;
1471 }
1472
1473 //================================================================================
1474 /*!
1475  * \brief Remove intersection of _PolyLine's
1476  */
1477 //================================================================================
1478
1479 bool _ViscousBuilder2D::fixCollisions()
1480 {
1481   // look for intersections of _Segment's by intersecting _LayerEdge's with
1482   // _Segment's
1483   vector< const _Segment* > foundSegs;
1484   _SegmentIntersection intersection;
1485
1486   list< pair< _LayerEdge*, double > > edgeLenLimitList;
1487   list< _LayerEdge* >                 blockedEdgesList;
1488
1489   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1490   {
1491     _PolyLine& L1 = _polyLineVec[ iL1 ];
1492     //if ( !L1._advancable ) continue;
1493     for ( size_t iL2 = 0; iL2 < L1._reachableLines.size(); ++iL2 )
1494     {
1495       _PolyLine& L2 = * L1._reachableLines[ iL2 ];
1496       for ( size_t iLE = L1.FirstLEdge(); iLE < L1._lEdges.size(); ++iLE )
1497       {
1498         _LayerEdge& LE1 = L1._lEdges[iLE];
1499         if ( LE1._isBlocked ) continue;
1500         foundSegs.clear();
1501         L2._segTree->GetSegmentsNear( LE1._ray, foundSegs );
1502         for ( size_t i = 0; i < foundSegs.size(); ++i )
1503         {
1504           if ( ! L1.IsAdjacent( *foundSegs[i], &LE1 ) &&
1505                intersection.Compute( *foundSegs[i], LE1._ray ))
1506           {
1507             const double dist2DToL2 = intersection._param2;
1508             double         newLen2D = dist2DToL2 / 2;
1509             if ( newLen2D < 1.1 * LE1._length2D ) // collision!
1510             {
1511               if ( newLen2D > 0 || !L1._advancable )
1512               {
1513                 blockedEdgesList.push_back( &LE1 );
1514                 if ( L1._advancable && newLen2D > 0 )
1515                 {
1516                   edgeLenLimitList.push_back( make_pair( &LE1, newLen2D ));
1517                   blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine     ]);
1518                   blockedEdgesList.push_back( &L2._lEdges[ foundSegs[i]->_indexInLine + 1 ]);
1519                 }
1520                 else // here dist2DToL2 < 0 and LE1._length2D == 0
1521                 {
1522                   _LayerEdge* LE2[2] = { & L2._lEdges[ foundSegs[i]->_indexInLine     ],
1523                                          & L2._lEdges[ foundSegs[i]->_indexInLine + 1 ] };
1524                   _Segment outSeg2( LE2[0]->_uvOut, LE2[1]->_uvOut );
1525                   intersection.Compute( outSeg2, LE1._ray );
1526                   newLen2D = intersection._param2 / 2;
1527                   if ( newLen2D > 0 )
1528                   {
1529                     edgeLenLimitList.push_back( make_pair( LE2[0], newLen2D ));
1530                     edgeLenLimitList.push_back( make_pair( LE2[1], newLen2D ));
1531                   }
1532                 }
1533               }
1534             }
1535           }
1536         }
1537       }
1538     }
1539   }
1540
1541   // limit length of _LayerEdge's that are extrema of _PolyLine's
1542   // to avoid intersection of these _LayerEdge's
1543   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1544   {
1545     _PolyLine& L = _polyLineVec[ iL1 ];
1546     if ( L._lEdges.size() < 4 ) // all intermediate _LayerEdge's intersect with extremum ones
1547     {
1548       _LayerEdge& LEL = L._leftLine->_lEdges.back();
1549       _LayerEdge& LER = L._lEdges.back();
1550       _Segment segL( LEL._uvOut, LEL._uvIn );
1551       _Segment segR( LER._uvOut, LER._uvIn );
1552       double newLen2DL, newLen2DR;
1553       if ( intersection.Compute( segL, LER._ray ))
1554       {
1555         newLen2DR = intersection._param2 / 2;
1556         newLen2DL = LEL._length2D * intersection._param1 / 2;
1557       }
1558       else if ( intersection.Compute( segR, LEL._ray ))
1559       {
1560         newLen2DL = intersection._param2 / 2;
1561         newLen2DR = LER._length2D * intersection._param1 / 2;
1562       }
1563       else
1564       {
1565         continue;
1566       }
1567       if ( newLen2DL > 0 && newLen2DR > 0 )
1568       {
1569         if ( newLen2DL < 1.1 * LEL._length2D )
1570           edgeLenLimitList.push_back( make_pair( &LEL, newLen2DL ));
1571         if ( newLen2DR < 1.1 * LER._length2D )
1572           edgeLenLimitList.push_back( make_pair( &LER, newLen2DR ));
1573       }
1574     }
1575   }
1576
1577   // set limited length to _LayerEdge's
1578   list< pair< _LayerEdge*, double > >::iterator edge2Len = edgeLenLimitList.begin();
1579   for ( ; edge2Len != edgeLenLimitList.end(); ++edge2Len )
1580   {
1581     _LayerEdge* LE = edge2Len->first;
1582     if ( LE->_length2D > edge2Len->second )
1583     {
1584       LE->_isBlocked = false;
1585       LE->SetNewLength( edge2Len->second / LE->_len2dTo3dRatio );
1586     }
1587     LE->_isBlocked = true;
1588   }
1589
1590   // block inflation of _LayerEdge's
1591   list< _LayerEdge* >::iterator edge = blockedEdgesList.begin();
1592   for ( ; edge != blockedEdgesList.end(); ++edge )
1593     (*edge)->_isBlocked = true;
1594
1595   // find a not blocked _LayerEdge
1596   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
1597   {
1598     _PolyLine& L = _polyLineVec[ iL ];
1599     if ( !L._advancable ) continue;
1600     for ( size_t iLE = L.FirstLEdge(); iLE < L._lEdges.size(); ++iLE )
1601       if ( !L._lEdges[ iLE ]._isBlocked )
1602         return false;
1603   }
1604
1605   return true;
1606 }
1607
1608 //================================================================================
1609 /*!
1610  * \brief Create new edges and shrink edges existing on a non-advancable _PolyLine
1611  *        adjacent to an advancable one.
1612  */
1613 //================================================================================
1614
1615 bool _ViscousBuilder2D::shrink()
1616 {
1617   gp_Pnt2d uv; //gp_Vec2d tangent;
1618   _SegmentIntersection intersection;
1619   double sign;
1620
1621   for ( size_t iL1 = 0; iL1 < _polyLineVec.size(); ++iL1 )
1622   {
1623     _PolyLine& L = _polyLineVec[ iL1 ]; // line with no layers
1624     if ( L._advancable )
1625       continue;
1626     const int nbAdvancable = ( L._rightLine->_advancable + L._leftLine->_advancable );
1627     if ( nbAdvancable == 0 )
1628       continue;
1629
1630     const TopoDS_Vertex&  V1 = L._wire->FirstVertex( L._edgeInd );
1631     const TopoDS_Vertex&  V2 = L._wire->LastVertex ( L._edgeInd );
1632     const int           v1ID = getMeshDS()->ShapeToIndex( V1 );
1633     const int           v2ID = getMeshDS()->ShapeToIndex( V2 );
1634     const bool isShrinkableL = ! _noShrinkVert.count( v1ID ) && L._leftLine->_advancable;
1635     const bool isShrinkableR = ! _noShrinkVert.count( v2ID ) && L._rightLine->_advancable;
1636     if ( !isShrinkableL && !isShrinkableR )
1637       continue;
1638
1639     const TopoDS_Edge&        E = L._wire->Edge       ( L._edgeInd );
1640     const int            edgeID = L._wire->EdgeID     ( L._edgeInd );
1641     const double        edgeLen = L._wire->EdgeLength ( L._edgeInd );
1642     Handle(Geom2d_Curve) pcurve = L._wire->Curve2d    ( L._edgeInd );
1643     const bool     edgeReversed = ( E.Orientation() == TopAbs_REVERSED );
1644
1645     SMESH_MesherHelper helper( *_mesh ); // to create nodes and edges on E
1646     helper.SetSubShape( E );
1647     helper.SetElementsOnShape( true );
1648
1649     // Check a FACE adjacent to _face by E
1650     bool existingNodesFound = false;
1651     TopoDS_Face adjFace;
1652     PShapeIteratorPtr faceIt = _helper.GetAncestors( E, *_mesh, TopAbs_FACE );
1653     while ( const TopoDS_Shape* f = faceIt->next() )
1654       if ( !_face.IsSame( *f ))
1655       {
1656         adjFace = TopoDS::Face( *f );
1657         SMESH_ProxyMesh::Ptr pm = _ProxyMeshHolder::FindProxyMeshOfFace( adjFace, *_mesh );
1658         if ( !pm || pm->NbProxySubMeshes() == 0 /*|| !pm->GetProxySubMesh( E )*/)
1659         {
1660           // There are no viscous layers on an adjacent FACE, clear it's 2D mesh
1661           removeMeshFaces( adjFace );
1662           // if ( removeMeshFaces( adjFace ))
1663           //   _clearedFaces.push_back( adjFace ); // to re-compute after all
1664         }
1665         else
1666         {
1667           // There are viscous layers on the adjacent FACE; shrink must be already done;
1668           //
1669           // copy layer nodes
1670           //
1671           const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1672           int iPFrom = L._firstPntInd, iPTo = L._lastPntInd;
1673           if ( isShrinkableL )
1674           {
1675             const THypVL* hyp = getLineHypothesis( L._leftLine->_index );
1676             vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1677             for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1678               const UVPtStruct& uvPt = points[ iPFrom + i + 1 ];
1679               L._leftNodes.push_back( uvPt.node );
1680               uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1681             }
1682             iPFrom += hyp->GetNumberLayers();
1683           }
1684           if ( isShrinkableR )
1685           {
1686             const THypVL* hyp = getLineHypothesis( L._rightLine->_index );
1687             vector<gp_XY>& uvVec = L._lEdges.back()._uvRefined;
1688             for ( int i = 0; i < hyp->GetNumberLayers(); ++i ) {
1689               const UVPtStruct& uvPt = points[ iPTo - i - 1 ];
1690               L._rightNodes.push_back( uvPt.node );
1691               uvVec.push_back ( pcurve->Value( uvPt.param ).XY() );
1692             }
1693             iPTo -= hyp->GetNumberLayers();
1694           }
1695           // make proxy sub-mesh data of present nodes
1696           //
1697           UVPtStructVec nodeDataVec( & points[ iPFrom ], & points[ iPTo + 1 ]);
1698
1699           double normSize = nodeDataVec.back().normParam - nodeDataVec.front().normParam;
1700           for ( int iP = nodeDataVec.size()-1; iP >= 0 ; --iP )
1701             nodeDataVec[iP].normParam =
1702               ( nodeDataVec[iP].normParam - nodeDataVec[0].normParam ) / normSize;
1703
1704           const SMDS_MeshNode* n = nodeDataVec.front().node;
1705           if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1706             nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
1707           n = nodeDataVec.back().node;
1708           if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
1709             nodeDataVec.back().param = L._wire->LastU( L._edgeInd );
1710
1711           _ProxyMeshOfFace::_EdgeSubMesh* myEdgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
1712           myEdgeSM->SetUVPtStructVec( nodeDataVec );
1713
1714           existingNodesFound = true;
1715           break;
1716         }
1717       } // loop on FACEs sharing E
1718
1719     // Commented as a case with a seam EDGE (issue 0052461) is hard to support
1720     // because SMESH_ProxyMesh can't hold different sub-meshes for two
1721     // 2D representations of the seam. But such a case is not a real practice one.
1722     // Check if L is an already shrinked seam
1723     // if ( adjFace.IsNull() && _helper.IsRealSeam( edgeID ))
1724     // {
1725     //   for ( int iL2 = iL1-1; iL2 > -1; --iL2 )
1726     //   {
1727     //     _PolyLine& L2 = _polyLineVec[ iL2 ];
1728     //     if ( edgeID == L2._wire->EdgeID( L2._edgeInd ))
1729     //     {
1730     //       // copy layer nodes
1731     //       const int seamPar = _helper.GetPeriodicIndex();
1732     //       vector<gp_XY>& uvVec = L._lEdges.front()._uvRefined;
1733     //       if ( isShrinkableL )
1734     //       {
1735     //         L._leftNodes = L2._rightNodes;
1736     //         uvVec = L2._lEdges.back()._uvRefined;
1737     //       }
1738     //       if ( isShrinkableR )
1739     //       {
1740     //         L._rightNodes = L2._leftNodes;
1741     //         uvVec = L2._lEdges.front()._uvRefined;
1742     //       }
1743     //       for ( size_t i = 0; i < uvVec.size(); ++i )
1744     //       {
1745     //         gp_XY & uv = uvVec[i];
1746     //         uv.SetCoord( seamPar, _helper.GetOtherParam( uv.Coord( seamPar )));
1747     //       }
1748
1749     //       existingNodesFound = true;
1750     //       break;
1751     //     }
1752     //   }
1753     // }
1754
1755     if ( existingNodesFound )
1756       continue; // nothing more to do in this case
1757
1758     double u1 = L._wire->FirstU( L._edgeInd ), uf = u1;
1759     double u2 = L._wire->LastU ( L._edgeInd ), ul = u2;
1760
1761     // a ratio to pass 2D <--> 1D
1762     const double len1D = 1e-3;
1763     const double len2D = pcurve->Value(uf).Distance( pcurve->Value(uf+len1D));
1764     double len1dTo2dRatio = len1D / len2D;
1765
1766     // create a vector of proxy nodes
1767     const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
1768     UVPtStructVec nodeDataVec( & points[ L._firstPntInd ],
1769                                & points[ L._lastPntInd + 1 ]);
1770     nodeDataVec.front().param = u1; // U on vertex is correct on only one of shared edges
1771     nodeDataVec.back ().param = u2;
1772     nodeDataVec.front().normParam = 0;
1773     nodeDataVec.back ().normParam = 1;
1774
1775     // Get length of existing segments (from an edge start to a node) and their nodes
1776     vector< double > segLengths( nodeDataVec.size() - 1 );
1777     BRepAdaptor_Curve curve( E );
1778     for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
1779     {
1780       const double len = GCPnts_AbscissaPoint::Length( curve, uf, nodeDataVec[iP].param );
1781       segLengths[ iP-1 ] = len;
1782     }
1783
1784     // Move first and last parameters on EDGE (U of n1) according to layers' thickness
1785     // and create nodes of layers on EDGE ( -x-x-x )
1786
1787     // Before
1788     //  n1    n2    n3    n4
1789     //  x-----x-----x-----x-----
1790     //  |  e1    e2    e3    e4
1791
1792     // After
1793     //  n1          n2    n3
1794     //  x-x-x-x-----x-----x----
1795     //  | | | |  e1    e2    e3
1796
1797     int isRShrinkedForAdjacent;
1798     UVPtStructVec nodeDataForAdjacent;
1799     for ( int isR = 0; isR < 2; ++isR )
1800     {
1801       _PolyLine* L2 = isR ? L._rightLine : L._leftLine; // line with layers
1802       if ( !L2->_advancable &&
1803            !toShrinkForAdjacent( adjFace, E, L._wire->FirstVertex( L._edgeInd + isR )))
1804         continue;
1805       if ( isR ? !isShrinkableR : !isShrinkableL )
1806         continue;
1807
1808       double & u = isR ? u2 : u1; // param to move
1809       double  u0 = isR ? ul : uf; // init value of the param to move
1810       int  iPEnd = isR ? nodeDataVec.size() - 1 : 0;
1811
1812       _LayerEdge& nearLE = isR ? L._lEdges.back() : L._lEdges.front();
1813       _LayerEdge&  farLE = isR ? L._lEdges.front() : L._lEdges.back();
1814
1815       // try to find length of advancement along L by intersecting L with
1816       // an adjacent _Segment of L2
1817
1818       double& length2D = nearLE._length2D;
1819       double  length1D = 0;
1820       sign = ( isR ^ edgeReversed ) ? -1. : 1.;
1821
1822       bool isConvex = false;
1823       if ( L2->_advancable )
1824       {
1825         const uvPtStruct& tang2P1 = points[ isR ? L2->_firstPntInd   : L2->_lastPntInd ];
1826         const uvPtStruct& tang2P2 = points[ isR ? L2->_firstPntInd+1 : L2->_lastPntInd-1 ];
1827         gp_XY seg2Dir( tang2P2.u - tang2P1.u,
1828                        tang2P2.v - tang2P1.v );
1829         int iFSeg2 = isR ? 0 : L2->_segments.size() - 1;
1830         int iLSeg2 = isR ? 1 : L2->_segments.size() - 2;
1831         gp_XY uvLSeg2In  = L2->_lEdges[ iLSeg2 ]._uvIn;
1832         Handle(Geom2d_Line) seg2Line = new Geom2d_Line( uvLSeg2In, seg2Dir );
1833
1834         Geom2dAdaptor_Curve edgeCurve( pcurve, Min( uf, ul ), Max( uf, ul ));
1835         Geom2dAdaptor_Curve seg2Curve( seg2Line );
1836         Geom2dInt_GInter     curveInt( edgeCurve, seg2Curve, 1e-7, 1e-7 );
1837         isConvex = ( curveInt.IsDone() && !curveInt.IsEmpty() );
1838         if ( isConvex ) {
1839           /*                   convex VERTEX */
1840           length1D = Abs( u - curveInt.Point( 1 ).ParamOnFirst() );
1841           double maxDist2d = 2 * L2->_lEdges[ iLSeg2 ]._length2D;
1842           isConvex = ( length1D < maxDist2d * len1dTo2dRatio );
1843           /*                                          |L  seg2
1844            *                                          |  o---o---
1845            *                                          | /    |
1846            *                                          |/     |  L2
1847            *                                          x------x---      */
1848         }
1849         if ( !isConvex ) { /* concave VERTEX */   /*  o-----o---
1850                                                    *   \    |
1851                                                    *    \   |  L2
1852                                                    *     x--x---
1853                                                    *    /
1854                                                    * L /               */
1855           length2D = L2->_lEdges[ iFSeg2 ]._length2D;
1856           //if ( L2->_advancable ) continue;
1857         }
1858       }
1859       else // L2 is advancable but in the face adjacent by L
1860       {
1861         length2D = farLE._length2D;
1862         if ( length2D == 0 ) {
1863           _LayerEdge& neighborLE =
1864             ( isR ? L._leftLine->_lEdges.back() : L._rightLine->_lEdges.front() );
1865           length2D = neighborLE._length2D;
1866           if ( length2D == 0 )
1867             length2D = _maxThickness * nearLE._len2dTo3dRatio;
1868         }
1869       }
1870
1871       // move u to the internal boundary of layers
1872       //  u --> u
1873       //  x-x-x-x-----x-----x----
1874       double maxLen3D = Min( _maxThickness, edgeLen / ( 1 + nbAdvancable ));
1875       double maxLen2D = maxLen3D * nearLE._len2dTo3dRatio;
1876       if ( !length2D ) length2D = length1D / len1dTo2dRatio;
1877       if ( Abs( length2D ) > maxLen2D )
1878         length2D = maxLen2D;
1879       nearLE._uvIn = nearLE._uvOut + nearLE._normal2D * length2D;
1880
1881       u += length2D * len1dTo2dRatio * sign;
1882       nodeDataVec[ iPEnd ].param = u;
1883
1884       gp_Pnt2d newUV = pcurve->Value( u );
1885       nodeDataVec[ iPEnd ].u = newUV.X();
1886       nodeDataVec[ iPEnd ].v = newUV.Y();
1887
1888       // compute params of layers on L
1889       vector<double> heights;
1890       const THypVL* hyp = getLineHypothesis( L2->_index );
1891       calcLayersHeight( u - u0, heights, hyp );
1892       //
1893       vector< double > params( heights.size() );
1894       for ( size_t i = 0; i < params.size(); ++i )
1895         params[ i ] = u0 + heights[ i ];
1896
1897       // create nodes of layers and edges between them
1898       //  x-x-x-x---
1899       vector< const SMDS_MeshNode* >& layersNode = isR ? L._rightNodes : L._leftNodes;
1900       vector<gp_XY>& nodeUV = ( isR ? L._lEdges.back() : L._lEdges[0] )._uvRefined;
1901       nodeUV.resize    ( hyp->GetNumberLayers() );
1902       layersNode.resize( hyp->GetNumberLayers() );
1903       const SMDS_MeshNode* vertexNode = nodeDataVec[ iPEnd ].node;
1904       const SMDS_MeshNode *  prevNode = vertexNode;
1905       for ( size_t i = 0; i < params.size(); ++i )
1906       {
1907         const gp_Pnt p  = curve.Value( params[i] );
1908         layersNode[ i ] = helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, params[i] );
1909         nodeUV    [ i ] = pcurve->Value( params[i] ).XY();
1910         helper.AddEdge( prevNode, layersNode[ i ] );
1911         prevNode = layersNode[ i ];
1912       }
1913
1914       // store data of layer nodes made for adjacent FACE
1915       if ( !L2->_advancable )
1916       {
1917         isRShrinkedForAdjacent = isR;
1918         nodeDataForAdjacent.resize( hyp->GetNumberLayers() );
1919
1920         size_t iFrw = 0, iRev = nodeDataForAdjacent.size()-1, *i = isR ? &iRev : &iFrw;
1921         nodeDataForAdjacent[ *i ] = points[ isR ? L._lastPntInd : L._firstPntInd ];
1922         nodeDataForAdjacent[ *i ].param     = u0;
1923         nodeDataForAdjacent[ *i ].normParam = isR;
1924         for ( ++iFrw, --iRev; iFrw < layersNode.size(); ++iFrw, --iRev )
1925         {
1926           nodeDataForAdjacent[ *i ].node  = layersNode[ iFrw - 1 ];
1927           nodeDataForAdjacent[ *i ].u     = nodeUV    [ iFrw - 1 ].X();
1928           nodeDataForAdjacent[ *i ].v     = nodeUV    [ iFrw - 1 ].Y();
1929           nodeDataForAdjacent[ *i ].param = params    [ iFrw - 1 ];
1930         }
1931       }
1932       // replace a node on vertex by a node of last (most internal) layer
1933       // in a segment on E
1934       SMDS_ElemIteratorPtr segIt = vertexNode->GetInverseElementIterator( SMDSAbs_Edge );
1935       const SMDS_MeshNode* segNodes[3];
1936       while ( segIt->more() )
1937       {
1938         const SMDS_MeshElement* segment = segIt->next();
1939         if ( segment->getshapeId() != edgeID ) continue;
1940
1941         const int nbNodes = segment->NbNodes();
1942         for ( int i = 0; i < nbNodes; ++i )
1943         {
1944           const SMDS_MeshNode* n = segment->GetNode( i );
1945           segNodes[ i ] = ( n == vertexNode ? layersNode.back() : n );
1946         }
1947         getMeshDS()->ChangeElementNodes( segment, segNodes, nbNodes );
1948         break;
1949       }
1950       nodeDataVec[ iPEnd ].node = layersNode.back();
1951
1952     } // loop on the extremities of L
1953
1954     // Shrink edges to fit in between the layers at EDGE ends
1955
1956     double newLength = GCPnts_AbscissaPoint::Length( curve, u1, u2 );
1957     double lenRatio  = newLength / edgeLen * ( edgeReversed ? -1. : 1. );
1958     for ( size_t iP = 1; iP < nodeDataVec.size()-1; ++iP )
1959     {
1960       const SMDS_MeshNode* oldNode = nodeDataVec[iP].node;
1961
1962       GCPnts_AbscissaPoint discret( curve, segLengths[iP-1] * lenRatio, u1 );
1963       if ( !discret.IsDone() )
1964         throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
1965
1966       nodeDataVec[iP].param = discret.Parameter();
1967       if ( oldNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1968         throw SALOME_Exception(SMESH_Comment("ViscousBuilder2D: not SMDS_TOP_EDGE node position: ")
1969                                << oldNode->GetPosition()->GetTypeOfPosition()
1970                                << " of node " << oldNode->GetID());
1971       SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( oldNode->GetPosition() );
1972       pos->SetUParameter( nodeDataVec[iP].param );
1973
1974       gp_Pnt newP = curve.Value( nodeDataVec[iP].param );
1975       getMeshDS()->MoveNode( oldNode, newP.X(), newP.Y(), newP.Z() );
1976
1977       gp_Pnt2d newUV = pcurve->Value( nodeDataVec[iP].param ).XY();
1978       nodeDataVec[iP].u         = newUV.X();
1979       nodeDataVec[iP].v         = newUV.Y();
1980       nodeDataVec[iP].normParam = segLengths[iP-1] / edgeLen;
1981       // nodeDataVec[iP].x         = segLengths[iP-1] / edgeLen;
1982       // nodeDataVec[iP].y         = segLengths[iP-1] / edgeLen;
1983     }
1984
1985     // Add nodeDataForAdjacent to nodeDataVec
1986
1987     if ( !nodeDataForAdjacent.empty() )
1988     {
1989       const double par1      = isRShrinkedForAdjacent ? u2 : uf;
1990       const double par2      = isRShrinkedForAdjacent ? ul : u1;
1991       const double shrinkLen = GCPnts_AbscissaPoint::Length( curve, par1, par2 );
1992
1993       // compute new normParam for nodeDataVec
1994       for ( size_t iP = 0; iP < nodeDataVec.size()-1; ++iP )
1995         nodeDataVec[iP+1].normParam = segLengths[iP] / ( edgeLen + shrinkLen );
1996       double normDelta = 1 - nodeDataVec.back().normParam;
1997       if ( !isRShrinkedForAdjacent )
1998         for ( size_t iP = 0; iP < nodeDataVec.size(); ++iP )
1999           nodeDataVec[iP].normParam += normDelta;
2000
2001       // compute new normParam for nodeDataForAdjacent
2002       const double deltaR = isRShrinkedForAdjacent ? nodeDataVec.back().normParam : 0;
2003       for ( size_t iP = !isRShrinkedForAdjacent; iP < nodeDataForAdjacent.size(); ++iP )
2004       {
2005         double lenFromPar1 =
2006           GCPnts_AbscissaPoint::Length( curve, par1, nodeDataForAdjacent[iP].param );
2007         nodeDataForAdjacent[iP].normParam = deltaR + normDelta * lenFromPar1 / shrinkLen;
2008       }
2009       // concatenate nodeDataVec and nodeDataForAdjacent
2010       nodeDataVec.insert(( isRShrinkedForAdjacent ? nodeDataVec.end() : nodeDataVec.begin() ),
2011                          nodeDataForAdjacent.begin(), nodeDataForAdjacent.end() );
2012     }
2013
2014     // Extend nodeDataVec by a node located at the end of not shared _LayerEdge
2015     /*      n - to add to nodeDataVec
2016      *      o-----o---
2017      *      |\    |
2018      *      | o---o---
2019      *      | |x--x--- L2
2020      *      | /
2021      *      |/ L
2022      *      x
2023      *     /    */
2024     for ( int isR = 0; isR < 2; ++isR )
2025     {
2026       _PolyLine& L2 = *( isR ? L._rightLine : L._leftLine ); // line with layers
2027       if ( ! L2._advancable || L.IsCommonEdgeShared( L2 ) )
2028         continue;
2029       vector< const SMDS_MeshNode* >& layerNodes2 = isR ? L2._leftNodes : L2._rightNodes;
2030       _LayerEdge& LE2 = isR ? L2._lEdges.front() : L2._lEdges.back();
2031       if ( layerNodes2.empty() )
2032       {
2033         // refine the not shared _LayerEdge
2034         vector<double> layersHeight;
2035         calcLayersHeight( LE2._length2D, layersHeight, getLineHypothesis( L2._index ));
2036
2037         vector<gp_XY>& nodeUV2 = LE2._uvRefined;
2038         nodeUV2.resize    ( layersHeight.size() );
2039         layerNodes2.resize( layersHeight.size() );
2040         for ( size_t i = 0; i < layersHeight.size(); ++i )
2041         {
2042           gp_XY uv = LE2._uvOut + LE2._normal2D * layersHeight[i];
2043           gp_Pnt p = _surface->Value( uv.X(), uv.Y() );
2044           nodeUV2    [ i ] = uv;
2045           layerNodes2[ i ] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2046         }
2047       }
2048       UVPtStruct ptOfNode;
2049       ptOfNode.u         = LE2._uvRefined.back().X();
2050       ptOfNode.v         = LE2._uvRefined.back().Y();
2051       ptOfNode.node      = layerNodes2.back();
2052       ptOfNode.param     = isR ? ul : uf;
2053       ptOfNode.normParam = isR ? 1 : 0;
2054
2055       nodeDataVec.insert(( isR ? nodeDataVec.end() : nodeDataVec.begin() ), ptOfNode );
2056
2057       // recompute normParam of nodes in nodeDataVec
2058       newLength = GCPnts_AbscissaPoint::Length( curve,
2059                                                 nodeDataVec.front().param,
2060                                                 nodeDataVec.back().param);
2061       for ( size_t iP = 1; iP < nodeDataVec.size(); ++iP )
2062       {
2063         const double len = GCPnts_AbscissaPoint::Length( curve,
2064                                                          nodeDataVec.front().param,
2065                                                          nodeDataVec[iP].param );
2066         nodeDataVec[iP].normParam = len / newLength;
2067       }
2068     }
2069
2070     // create a proxy sub-mesh containing the moved nodes
2071     _ProxyMeshOfFace::_EdgeSubMesh* edgeSM = getProxyMesh()->GetEdgeSubMesh( edgeID );
2072     edgeSM->SetUVPtStructVec( nodeDataVec );
2073
2074     // set a sub-mesh event listener to remove just created edges when
2075     // "ViscousLayers2D" hypothesis is modified
2076     VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( E ), _face );
2077
2078   } // loop on _polyLineVec
2079
2080   return true;
2081 }
2082
2083 //================================================================================
2084 /*!
2085  * \brief Returns true if there will be a shrinked mesh on EDGE E of FACE adjFace
2086  *        near VERTEX V
2087  */
2088 //================================================================================
2089
2090 bool _ViscousBuilder2D::toShrinkForAdjacent( const TopoDS_Face&   adjFace,
2091                                              const TopoDS_Edge&   E,
2092                                              const TopoDS_Vertex& V)
2093 {
2094   if ( _noShrinkVert.count( getMeshDS()->ShapeToIndex( V )) || adjFace.IsNull() )
2095     return false;
2096
2097   vector< const StdMeshers_ViscousLayers2D* > hyps;
2098   vector< TopoDS_Shape >                      hypShapes;
2099   if ( VISCOUS_2D::findHyps( *_mesh, adjFace, hyps, hypShapes ))
2100   {
2101     VISCOUS_2D::_ViscousBuilder2D builder( *_mesh, adjFace, hyps, hypShapes );
2102     builder._faceSideVec = StdMeshers_FaceSide::GetFaceWires( adjFace, *_mesh, true, _error );
2103     builder.findEdgesWithLayers();
2104
2105     PShapeIteratorPtr edgeIt = _helper.GetAncestors( V, *_mesh, TopAbs_EDGE );
2106     while ( const TopoDS_Shape* edgeAtV = edgeIt->next() )
2107     {
2108       if ( !edgeAtV->IsSame( E ) &&
2109            _helper.IsSubShape( *edgeAtV, adjFace ) &&
2110            !builder._ignoreShapeIds.count( getMeshDS()->ShapeToIndex( *edgeAtV )))
2111       {
2112         return true;
2113       }
2114     }
2115   }
2116   return false;
2117 }
2118
2119 //================================================================================
2120 /*!
2121  * \brief Make faces
2122  */
2123 //================================================================================
2124
2125 bool _ViscousBuilder2D::refine()
2126 {
2127   // find out orientation of faces to create
2128   bool isReverse = 
2129     ( _helper.GetSubShapeOri( _mesh->GetShapeToMesh(), _face ) == TopAbs_REVERSED );
2130
2131   // store a proxyMesh in a sub-mesh
2132   // make faces on each _PolyLine
2133   vector< double > layersHeight;
2134   //double prevLen2D = -1;
2135   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2136   {
2137     _PolyLine& L = _polyLineVec[ iL ];
2138     if ( !L._advancable ) continue;
2139
2140     // replace an inactive (1st) _LayerEdge with an active one of a neighbour _PolyLine
2141     //size_t iLE = 0, nbLE = L._lEdges.size();
2142     const bool leftEdgeShared  = L.IsCommonEdgeShared( *L._leftLine );
2143     const bool rightEdgeShared = L.IsCommonEdgeShared( *L._rightLine );
2144     if ( /*!L._leftLine->_advancable &&*/ leftEdgeShared )
2145     {
2146       L._lEdges[0] = L._leftLine->_lEdges.back();
2147       //iLE += int( !L._leftLine->_advancable );
2148     }
2149     if ( !L._rightLine->_advancable && rightEdgeShared )
2150     {
2151       L._lEdges.back() = L._rightLine->_lEdges[0];
2152       //--nbLE;
2153     }
2154
2155     // limit length of neighbour _LayerEdge's to avoid sharp change of layers thickness
2156
2157     vector< double > segLen( L._lEdges.size() );
2158     segLen[0] = 0.0;
2159
2160     // check if length modification is usefull: look for _LayerEdge's
2161     // with length limited due to collisions
2162     bool lenLimited = false;
2163     for ( size_t iLE = 1; ( iLE < L._lEdges.size()-1 && !lenLimited ); ++iLE )
2164       lenLimited = L._lEdges[ iLE ]._isBlocked;
2165
2166     if ( lenLimited )
2167     {
2168       for ( size_t i = 1; i < segLen.size(); ++i )
2169       {
2170         // accumulate length of segments
2171         double sLen = (L._lEdges[i-1]._uvOut - L._lEdges[i]._uvOut ).Modulus();
2172         segLen[i] = segLen[i-1] + sLen;
2173       }
2174       const double totSegLen = segLen.back();
2175       // normalize the accumulated length
2176       for ( size_t iS = 1; iS < segLen.size(); ++iS )
2177         segLen[iS] /= totSegLen;
2178
2179       for ( int isR = 0; isR < 2; ++isR )
2180       {
2181         size_t iF = 0, iL = L._lEdges.size()-1;
2182         size_t *i = isR ? &iL : &iF;
2183         _LayerEdge* prevLE = & L._lEdges[ *i ];
2184         double weight = 0;
2185         for ( ++iF, --iL; iF < L._lEdges.size()-1; ++iF, --iL )
2186         {
2187           _LayerEdge& LE = L._lEdges[*i];
2188           if ( prevLE->_length2D > 0 )
2189           {
2190             gp_XY tangent ( LE._normal2D.Y(), -LE._normal2D.X() );
2191             weight += Abs( tangent * ( prevLE->_uvIn - LE._uvIn )) / totSegLen;
2192             // gp_XY prevTang( LE._uvOut - prevLE->_uvOut );
2193             // gp_XY prevNorm( -prevTang.Y(), prevTang.X() );
2194             gp_XY prevNorm = LE._normal2D;
2195             double prevProj = prevNorm * ( prevLE->_uvIn - prevLE->_uvOut );
2196             if ( prevProj > 0 ) {
2197               prevProj /= prevNorm.Modulus();
2198               if ( LE._length2D < prevProj )
2199                 weight += 0.75 * ( 1 - weight ); // length decrease is more preferable
2200               LE._length2D  = weight * LE._length2D + ( 1 - weight ) * prevProj;
2201               LE._uvIn = LE._uvOut + LE._normal2D * LE._length2D;
2202             }
2203           }
2204           prevLE = & LE;
2205         }
2206       }
2207     }
2208     // DEBUG:  to see _uvRefined. cout can be redirected to hide NETGEN output
2209     // cerr << "import smesh" << endl << "mesh = smesh.Mesh()"<< endl;
2210
2211     const vector<UVPtStruct>& points = L._wire->GetUVPtStruct();
2212
2213     // analyse extremities of the _PolyLine to find existing nodes
2214     const TopoDS_Vertex&  V1 = L._wire->FirstVertex( L._edgeInd );
2215     const TopoDS_Vertex&  V2 = L._wire->LastVertex ( L._edgeInd );
2216     const int           v1ID = getMeshDS()->ShapeToIndex( V1 );
2217     const int           v2ID = getMeshDS()->ShapeToIndex( V2 );
2218     const bool isShrinkableL = ! _noShrinkVert.count( v1ID );
2219     const bool isShrinkableR = ! _noShrinkVert.count( v2ID );
2220
2221     bool hasLeftNode     = ( !L._leftLine->_rightNodes.empty() && leftEdgeShared  );
2222     bool hasRightNode    = ( !L._rightLine->_leftNodes.empty() && rightEdgeShared );
2223     bool hasOwnLeftNode  = ( !L._leftNodes.empty() );
2224     bool hasOwnRightNode = ( !L._rightNodes.empty() );
2225     bool isClosedEdge    = ( points[ L._firstPntInd ].node == points[ L._lastPntInd ].node );
2226     const size_t
2227       nbN = L._lastPntInd - L._firstPntInd + 1,
2228       iN0 = ( hasLeftNode || hasOwnLeftNode || isClosedEdge || !isShrinkableL ),
2229       iNE = nbN - ( hasRightNode || hasOwnRightNode || !isShrinkableR );
2230
2231     // update _uvIn of end _LayerEdge's by existing nodes
2232     const SMDS_MeshNode *nL = 0, *nR = 0;
2233     if ( hasOwnLeftNode )    nL = L._leftNodes.back();
2234     else if ( hasLeftNode )  nL = L._leftLine->_rightNodes.back();
2235     if ( hasOwnRightNode )   nR = L._rightNodes.back();
2236     else if ( hasRightNode ) nR = L._rightLine->_leftNodes.back();
2237     if ( nL )
2238       L._lEdges[0]._uvIn = _helper.GetNodeUV( _face, nL, points[ L._firstPntInd + 1 ].node );
2239     if ( nR )
2240       L._lEdges.back()._uvIn = _helper.GetNodeUV( _face, nR, points[ L._lastPntInd - 1 ].node );
2241
2242     // compute normalized [0;1] node parameters of nodes on a _PolyLine
2243     vector< double > normPar( nbN );
2244     const double
2245       normF    = L._wire->FirstParameter( L._edgeInd ),
2246       normL    = L._wire->LastParameter ( L._edgeInd ),
2247       normDist = normL - normF;
2248     for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2249       normPar[ i - L._firstPntInd ] = ( points[i].normParam - normF ) / normDist;
2250
2251     // Calculate UV of most inner nodes
2252
2253     vector< gp_XY > innerUV( nbN );
2254
2255     // check if innerUV should be interpolated between _LayerEdge::_uvIn's
2256     const size_t nbLE = L._lEdges.size();
2257     bool needInterpol = ( nbN != nbLE );
2258     if ( !needInterpol )
2259     {
2260       // more check: compare length of inner and outer end segments
2261       double lenIn, lenOut;
2262       for ( int isR = 0; isR < 2 && !needInterpol; ++isR )
2263       {
2264         const _Segment& segIn = isR ? L._segments.back() : L._segments[0];
2265         const gp_XY&   uvIn1  = segIn.p1();
2266         const gp_XY&   uvIn2  = segIn.p2();
2267         const gp_XY&   uvOut1 = L._lEdges[ isR ? nbLE-1 : 0 ]._uvOut;
2268         const gp_XY&   uvOut2 = L._lEdges[ isR ? nbLE-2 : 1 ]._uvOut;
2269         if ( _is2DIsotropic )
2270         {
2271           lenIn  = ( uvIn1  - uvIn2  ).Modulus();
2272           lenOut = ( uvOut1 - uvOut2 ).Modulus();
2273         }
2274         else
2275         {
2276           lenIn  = _surface->Value( uvIn1.X(), uvIn1.Y() )
2277             .Distance( _surface->Value( uvIn2.X(), uvIn2.Y() ));
2278           lenOut  = _surface->Value( uvOut1.X(), uvOut1.Y() )
2279             .Distance( _surface->Value( uvOut2.X(), uvOut2.Y() ));
2280         }
2281         needInterpol = ( lenIn < 0.66 * lenOut );
2282       }
2283     }
2284
2285     if ( needInterpol )
2286     {
2287       // compute normalized accumulated length of inner segments
2288       size_t iS;
2289       if ( _is2DIsotropic )
2290         for ( iS = 1; iS < segLen.size(); ++iS )
2291         {
2292           double sLen = ( L._lEdges[iS-1]._uvIn - L._lEdges[iS]._uvIn ).Modulus();
2293           segLen[iS] = segLen[iS-1] + sLen;
2294         }
2295       else
2296         for ( iS = 1; iS < segLen.size(); ++iS )
2297         {
2298           const gp_XY& uv1 = L._lEdges[iS-1]._uvIn;
2299           const gp_XY& uv2 = L._lEdges[iS  ]._uvIn;
2300           gp_Pnt p1 = _surface->Value( uv1.X(), uv1.Y() );
2301           gp_Pnt p2 = _surface->Value( uv2.X(), uv2.Y() );
2302           double sLen = p1.Distance( p2 );
2303           segLen[iS] = segLen[iS-1] + sLen;
2304         }
2305       // normalize the accumulated length
2306       for ( iS = 1; iS < segLen.size(); ++iS )
2307         segLen[iS] /= segLen.back();
2308
2309       // calculate UV of most inner nodes according to the normalized node parameters
2310       iS = 0;
2311       for ( size_t i = 0; i < innerUV.size(); ++i )
2312       {
2313         while ( normPar[i] > segLen[iS+1] )
2314           ++iS;
2315         double r = ( normPar[i] - segLen[iS] ) / ( segLen[iS+1] - segLen[iS] );
2316         innerUV[ i ] = r * L._lEdges[iS+1]._uvIn + (1-r) * L._lEdges[iS]._uvIn;
2317       }
2318     }
2319     else // ! needInterpol
2320     {
2321       for ( size_t i = 0; i < nbLE; ++i )
2322         innerUV[ i ] = L._lEdges[i]._uvIn;
2323     }
2324
2325     // normalized height of layers
2326     const THypVL* hyp = getLineHypothesis( iL );
2327     calcLayersHeight( 1., layersHeight, hyp);
2328
2329     // Create layers of faces
2330
2331     // nodes to create 1 layer of faces
2332     vector< const SMDS_MeshNode* > outerNodes( nbN );
2333     vector< const SMDS_MeshNode* > innerNodes( nbN );
2334
2335     // initialize outerNodes by nodes of the L._wire
2336     for ( int i = L._firstPntInd; i <= L._lastPntInd; ++i )
2337       outerNodes[ i-L._firstPntInd ] = points[i].node;
2338
2339     L._leftNodes .reserve( hyp->GetNumberLayers() );
2340     L._rightNodes.reserve( hyp->GetNumberLayers() );
2341     int cur = 0, prev = -1; // to take into account orientation of _face
2342     if ( isReverse ) std::swap( cur, prev );
2343     for ( int iF = 0; iF < hyp->GetNumberLayers(); ++iF ) // loop on layers of faces
2344     {
2345       // create innerNodes of a current layer
2346       for ( size_t i = iN0; i < iNE; ++i )
2347       {
2348         gp_XY uvOut = points[ L._firstPntInd + i ].UV();
2349         gp_XY& uvIn = innerUV[ i ];
2350         gp_XY    uv = layersHeight[ iF ] * uvIn + ( 1.-layersHeight[ iF ]) * uvOut;
2351         gp_Pnt    p = _surface->Value( uv.X(), uv.Y() );
2352         innerNodes[i] = _helper.AddNode( p.X(), p.Y(), p.Z(), /*id=*/0, uv.X(), uv.Y() );
2353       }
2354       // use nodes created for adjacent _PolyLine's
2355       if ( hasOwnLeftNode )    innerNodes.front() = L._leftNodes [ iF ];
2356       else if ( hasLeftNode )  innerNodes.front() = L._leftLine->_rightNodes[ iF ];
2357       if ( hasOwnRightNode )   innerNodes.back()  = L._rightNodes[ iF ];
2358       else if ( hasRightNode ) innerNodes.back()  = L._rightLine->_leftNodes[ iF ];
2359       if ( isClosedEdge )      innerNodes.front() = innerNodes.back(); // circle
2360       if ( !isShrinkableL )    innerNodes.front() = outerNodes.front();
2361       if ( !isShrinkableR )    innerNodes.back()  = outerNodes.back();
2362       if ( !hasOwnLeftNode )   L._leftNodes.push_back( innerNodes.front() );
2363       if ( !hasOwnRightNode )  L._rightNodes.push_back( innerNodes.back() );
2364
2365       // create faces
2366       for ( size_t i = 1; i < innerNodes.size(); ++i )
2367         if ( SMDS_MeshElement* f = _helper.AddFace( outerNodes[ i+prev ], outerNodes[ i+cur ],
2368                                                     innerNodes[ i+cur  ], innerNodes[ i+prev ]))
2369           L._newFaces.insert( L._newFaces.end(), f );
2370
2371       outerNodes.swap( innerNodes );
2372     }
2373
2374     // faces between not shared _LayerEdge's (at concave VERTEX)
2375     for ( int isR = 0; isR < 2; ++isR )
2376     {
2377       if ( isR ? rightEdgeShared : leftEdgeShared )
2378         continue;
2379       vector< const SMDS_MeshNode* > &
2380         lNodes = (isR ? L._rightNodes : L._leftLine->_rightNodes ),
2381         rNodes = (isR ? L._rightLine->_leftNodes : L._leftNodes );
2382       if ( lNodes.empty() || rNodes.empty() || lNodes.size() != rNodes.size() )
2383         continue;
2384
2385       for ( size_t i = 1; i < lNodes.size(); ++i )
2386         _helper.AddFace( lNodes[ i+prev ], rNodes[ i+prev ],
2387                          rNodes[ i+cur ],  lNodes[ i+cur ]);
2388
2389       const UVPtStruct& ptOnVertex = points[ isR ? L._lastPntInd : L._firstPntInd ];
2390       if ( isReverse )
2391         _helper.AddFace( ptOnVertex.node, lNodes[ 0 ], rNodes[ 0 ]);
2392       else
2393         _helper.AddFace( ptOnVertex.node, rNodes[ 0 ], lNodes[ 0 ]);
2394     }
2395
2396     // Fill the _ProxyMeshOfFace
2397
2398     UVPtStructVec nodeDataVec( outerNodes.size() ); // outerNodes swapped with innerNodes
2399     for ( size_t i = 0; i < outerNodes.size(); ++i )
2400     {
2401       gp_XY uv = _helper.GetNodeUV( _face, outerNodes[i] );
2402       nodeDataVec[i].u         = uv.X();
2403       nodeDataVec[i].v         = uv.Y();
2404       nodeDataVec[i].node      = outerNodes[i];
2405       nodeDataVec[i].param     = points [i + L._firstPntInd].param;
2406       nodeDataVec[i].normParam = normPar[i];
2407       nodeDataVec[i].x         = normPar[i];
2408       nodeDataVec[i].y         = normPar[i];
2409     }
2410     nodeDataVec.front().param = L._wire->FirstU( L._edgeInd );
2411     nodeDataVec.back() .param = L._wire->LastU ( L._edgeInd );
2412
2413     _ProxyMeshOfFace::_EdgeSubMesh* edgeSM
2414       = getProxyMesh()->GetEdgeSubMesh( L._wire->EdgeID( L._edgeInd ));
2415     edgeSM->SetUVPtStructVec( nodeDataVec );
2416
2417   } // loop on _PolyLine's
2418
2419   // re-compute FACEs whose mesh was removed by shrink()
2420   for ( size_t i = 0; i < _clearedFaces.size(); ++i )
2421   {
2422     SMESH_subMesh* sm = _mesh->GetSubMesh( _clearedFaces[i] );
2423     if ( sm->GetComputeState() == SMESH_subMesh::READY_TO_COMPUTE )
2424       sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2425   }
2426
2427   return true;
2428 }
2429
2430 //================================================================================
2431 /*!
2432  * \brief Improve quality of the created mesh elements
2433  */
2434 //================================================================================
2435
2436 bool _ViscousBuilder2D::improve()
2437 {
2438   if ( !_proxyMesh )
2439     return false;
2440
2441   // fixed nodes on EDGE's
2442   std::set<const SMDS_MeshNode*> fixedNodes;
2443   for ( size_t iWire = 0; iWire < _faceSideVec.size(); ++iWire )
2444   {
2445     StdMeshers_FaceSidePtr      wire = _faceSideVec[ iWire ];
2446     const vector<UVPtStruct>& points = wire->GetUVPtStruct();
2447     for ( size_t i = 0; i < points.size(); ++i )
2448       fixedNodes.insert( fixedNodes.end(), points[i].node );
2449   }
2450   // fixed proxy nodes
2451   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2452   {
2453     _PolyLine&         L = _polyLineVec[ iL ];
2454     const TopoDS_Edge& E = L._wire->Edge( L._edgeInd );
2455     if ( const SMESH_ProxyMesh::SubMesh* sm = _proxyMesh->GetProxySubMesh( E ))
2456     {
2457       const UVPtStructVec& points = sm->GetUVPtStructVec();
2458       for ( size_t i = 0; i < points.size(); ++i )
2459         fixedNodes.insert( fixedNodes.end(), points[i].node );
2460     }
2461     for ( size_t i = 0; i < L._rightNodes.size(); ++i )
2462       fixedNodes.insert( fixedNodes.end(), L._rightNodes[i] );
2463   }
2464
2465   // smoothing
2466   SMESH_MeshEditor editor( _mesh );
2467   for ( size_t iL = 0; iL < _polyLineVec.size(); ++iL )
2468   {
2469     _PolyLine& L = _polyLineVec[ iL ];
2470     if ( L._isStraight2D ) continue;
2471     // SMESH_MeshEditor::SmoothMethod how =
2472     //   L._isStraight2D ? SMESH_MeshEditor::LAPLACIAN : SMESH_MeshEditor::CENTROIDAL;
2473     //editor.Smooth( L._newFaces, fixedNodes, how, /*nbIt = */3 );
2474     //editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::LAPLACIAN, /*nbIt = */1 );
2475     editor.Smooth( L._newFaces, fixedNodes, SMESH_MeshEditor::CENTROIDAL, /*nbIt = */3 );
2476   }
2477   return true;
2478 }
2479
2480 //================================================================================
2481 /*!
2482  * \brief Remove elements and nodes from a face
2483  */
2484 //================================================================================
2485
2486 bool _ViscousBuilder2D::removeMeshFaces(const TopoDS_Shape& face)
2487 {
2488   // we don't use SMESH_subMesh::ComputeStateEngine() because of a listener
2489   // which clears EDGEs together with _face.
2490   bool thereWereElems = false;
2491   SMESH_subMesh* sm = _mesh->GetSubMesh( face );
2492   if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2493   {
2494     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2495     thereWereElems = eIt->more();
2496     while ( eIt->more() ) getMeshDS()->RemoveFreeElement( eIt->next(), smDS );
2497     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2498     while ( nIt->more() ) getMeshDS()->RemoveFreeNode( nIt->next(), smDS );
2499   }
2500   sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2501
2502   return thereWereElems;
2503 }
2504
2505 //================================================================================
2506 /*!
2507  * \brief Returns a hypothesis for a _PolyLine
2508  */
2509 //================================================================================
2510
2511 const StdMeshers_ViscousLayers2D* _ViscousBuilder2D::getLineHypothesis(int iPL)
2512 {
2513   return iPL < (int)_hypOfEdge.size() ? _hypOfEdge[ iPL ] : _hyps[0];
2514 }
2515
2516 //================================================================================
2517 /*!
2518  * \brief Returns a layers thickness for a _PolyLine
2519  */
2520 //================================================================================
2521
2522 double _ViscousBuilder2D::getLineThickness(int iPL)
2523 {
2524   if ( const StdMeshers_ViscousLayers2D* h = getLineHypothesis( iPL ))
2525     return Min( _maxThickness, h->GetTotalThickness() );
2526   return _maxThickness;
2527 }
2528
2529 //================================================================================
2530 /*!
2531  * \brief Creates a _ProxyMeshOfFace and store it in a sub-mesh of FACE
2532  */
2533 //================================================================================
2534
2535 _ProxyMeshOfFace* _ViscousBuilder2D::getProxyMesh()
2536 {
2537   if ( _proxyMesh.get() )
2538     return (_ProxyMeshOfFace*) _proxyMesh.get();
2539
2540   _ProxyMeshOfFace* proxyMeshOfFace = new _ProxyMeshOfFace( *_mesh );
2541   _proxyMesh.reset( proxyMeshOfFace );
2542   new _ProxyMeshHolder( _face, _proxyMesh );
2543
2544   return proxyMeshOfFace;
2545 }
2546
2547 //================================================================================
2548 /*!
2549  * \brief Calculate height of layers for the given thickness. Height is measured
2550  *        from the outer boundary
2551  */
2552 //================================================================================
2553
2554 void _ViscousBuilder2D::calcLayersHeight(const double    totalThick,
2555                                          vector<double>& heights,
2556                                          const THypVL*   hyp)
2557 {
2558   const double fPowN = pow( hyp->GetStretchFactor(), hyp->GetNumberLayers() );
2559   heights.resize( hyp->GetNumberLayers() );
2560   double h0;
2561   if ( fPowN - 1 <= numeric_limits<double>::min() )
2562     h0 = totalThick / hyp->GetNumberLayers();
2563   else
2564     h0 = totalThick * ( hyp->GetStretchFactor() - 1 )/( fPowN - 1 );
2565
2566   double hSum = 0, hi = h0;
2567   for ( int i = 0; i < hyp->GetNumberLayers(); ++i )
2568   {
2569     hSum += hi;
2570     heights[ i ] = hSum;
2571     hi *= hyp->GetStretchFactor();
2572   }
2573 }
2574
2575 //================================================================================
2576 /*!
2577  * \brief Elongate this _LayerEdge
2578  */
2579 //================================================================================
2580
2581 bool _LayerEdge::SetNewLength( const double length3D )
2582 {
2583   if ( _isBlocked ) return false;
2584
2585   //_uvInPrev = _uvIn;
2586   _length2D = length3D * _len2dTo3dRatio;
2587   _uvIn     = _uvOut + _normal2D * _length2D;
2588   return true;
2589 }
2590
2591 //================================================================================
2592 /*!
2593  * \brief Return true if _LayerEdge at a common VERTEX between EDGEs with
2594  *  and w/o layer is common to the both _PolyLine's. If this is true, nodes
2595  *  of this _LayerEdge are inflated along a _PolyLine w/o layer, else the nodes
2596  *  are inflated along _normal2D of _LayerEdge of EDGE with layer
2597  */
2598 //================================================================================
2599
2600 bool _PolyLine::IsCommonEdgeShared( const _PolyLine& other )
2601 {
2602   const double tol = 1e-30;
2603
2604   if ( & other == _leftLine )
2605     return _lEdges[0]._normal2D.IsEqual( _leftLine->_lEdges.back()._normal2D, tol );
2606
2607   if ( & other == _rightLine )
2608     return _lEdges.back()._normal2D.IsEqual( _rightLine->_lEdges[0]._normal2D, tol );
2609
2610   return false;
2611 }
2612
2613 //================================================================================
2614 /*!
2615  * \brief Return \c true if the EDGE of this _PolyLine is concave
2616  */
2617 //================================================================================
2618
2619 bool _PolyLine::IsConcave() const
2620 {
2621   if ( _lEdges.size() < 2 )
2622     return false;
2623
2624   gp_Vec2d v1( _lEdges[0]._uvOut, _lEdges[1]._uvOut );
2625   gp_Vec2d v2( _lEdges[0]._uvOut, _lEdges[2]._uvOut );
2626   const double size2 = v2.Magnitude();
2627
2628   return ( v1 ^ v2 ) / size2 < -1e-3 * size2;
2629 }
2630
2631 //================================================================================
2632 /*!
2633  * \brief Constructor of SegmentTree
2634  */
2635 //================================================================================
2636
2637 _SegmentTree::_SegmentTree( const vector< _Segment >& segments ):
2638   SMESH_Quadtree()
2639 {
2640   _segments.resize( segments.size() );
2641   for ( size_t i = 0; i < segments.size(); ++i )
2642     _segments[i].Set( segments[i] );
2643
2644   compute();
2645 }
2646
2647 //================================================================================
2648 /*!
2649  * \brief Return the maximal bnd box
2650  */
2651 //================================================================================
2652
2653 _SegmentTree::box_type* _SegmentTree::buildRootBox()
2654 {
2655   _SegmentTree::box_type* box = new _SegmentTree::box_type;
2656   for ( size_t i = 0; i < _segments.size(); ++i )
2657   {
2658     box->Add( *_segments[i]._seg->_uv[0] );
2659     box->Add( *_segments[i]._seg->_uv[1] );
2660   }
2661   return box;
2662 }
2663
2664 //================================================================================
2665 /*!
2666  * \brief Redistrubute _segments among children
2667  */
2668 //================================================================================
2669
2670 void _SegmentTree::buildChildrenData()
2671 {
2672   for ( size_t i = 0; i < _segments.size(); ++i )
2673     for (int j = 0; j < nbChildren(); j++)
2674       if ( !myChildren[j]->getBox()->IsOut( *_segments[i]._seg->_uv[0],
2675                                             *_segments[i]._seg->_uv[1] ))
2676         ((_SegmentTree*)myChildren[j])->_segments.push_back( _segments[i]);
2677
2678   SMESHUtils::FreeVector( _segments ); // = _elements.clear() + free memory
2679
2680   for (int j = 0; j < nbChildren(); j++)
2681   {
2682     _SegmentTree* child = static_cast<_SegmentTree*>( myChildren[j]);
2683     child->myIsLeaf = ((int) child->_segments.size() <= maxNbSegInLeaf() );
2684   }
2685 }
2686
2687 //================================================================================
2688 /*!
2689  * \brief Return elements which can include the point
2690  */
2691 //================================================================================
2692
2693 void _SegmentTree::GetSegmentsNear( const _Segment&            seg,
2694                                     vector< const _Segment* >& found )
2695 {
2696   if ( getBox()->IsOut( *seg._uv[0], *seg._uv[1] ))
2697     return;
2698
2699   if ( isLeaf() )
2700   {
2701     for ( size_t i = 0; i < _segments.size(); ++i )
2702       if ( !_segments[i].IsOut( seg ))
2703         found.push_back( _segments[i]._seg );
2704   }
2705   else
2706   {
2707     for (int i = 0; i < nbChildren(); i++)
2708       ((_SegmentTree*) myChildren[i])->GetSegmentsNear( seg, found );
2709   }
2710 }
2711
2712
2713 //================================================================================
2714 /*!
2715  * \brief Return segments intersecting a ray
2716  */
2717 //================================================================================
2718
2719 void _SegmentTree::GetSegmentsNear( const gp_Ax2d&             ray,
2720                                     vector< const _Segment* >& found )
2721 {
2722   if ( getBox()->IsOut( ray ))
2723     return;
2724
2725   if ( isLeaf() )
2726   {
2727     for ( size_t i = 0; i < _segments.size(); ++i )
2728       if ( !_segments[i].IsOut( ray ))
2729         found.push_back( _segments[i]._seg );
2730   }
2731   else
2732   {
2733     for (int i = 0; i < nbChildren(); i++)
2734       ((_SegmentTree*) myChildren[i])->GetSegmentsNear( ray, found );
2735   }
2736 }
2737
2738 //================================================================================
2739 /*!
2740  * \brief Classify a _Segment
2741  */
2742 //================================================================================
2743
2744 bool _SegmentTree::_SegBox::IsOut( const _Segment& seg ) const
2745 {
2746   const double eps = std::numeric_limits<double>::min();
2747   for ( int iC = 0; iC < 2; ++iC )
2748   {
2749     if ( seg._uv[0]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps &&
2750          seg._uv[1]->Coord(iC+1) < _seg->_uv[ _iMin[iC]]->Coord(iC+1)+eps )
2751       return true;
2752     if ( seg._uv[0]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps &&
2753          seg._uv[1]->Coord(iC+1) > _seg->_uv[ 1-_iMin[iC]]->Coord(iC+1)-eps )
2754       return true;
2755   }
2756   return false;
2757 }
2758
2759 //================================================================================
2760 /*!
2761  * \brief Classify a ray
2762  */
2763 //================================================================================
2764
2765 bool _SegmentTree::_SegBox::IsOut( const gp_Ax2d& ray ) const
2766 {
2767   double distBoxCenter2Ray =
2768     ray.Direction().XY() ^ ( ray.Location().XY() - 0.5 * (*_seg->_uv[0] + *_seg->_uv[1]));
2769
2770   double boxSectionDiam =
2771     Abs( ray.Direction().X() ) * ( _seg->_uv[1-_iMin[1]]->Y() - _seg->_uv[_iMin[1]]->Y() ) +
2772     Abs( ray.Direction().Y() ) * ( _seg->_uv[1-_iMin[0]]->X() - _seg->_uv[_iMin[0]]->X() );
2773
2774   return Abs( distBoxCenter2Ray ) > 0.5 * boxSectionDiam;
2775 }