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