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