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