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