Salome HOME
Merge V9_dev branch into master
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementation of SMESH idl descriptions
24 //  File   : SMESH_Algo.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27
28 #include "SMESH_Algo.hxx"
29
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_FacePosition.hxx"
32 #include "SMDS_MeshElement.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESHDS_SubMesh.hxx"
37 #include "SMESH_Comment.hxx"
38 #include "SMESH_Gen.hxx"
39 #include "SMESH_HypoFilter.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshAlgos.hxx"
42 #include "SMESH_TypeDefs.hxx"
43 #include "SMESH_subMesh.hxx"
44
45 #include <BRepAdaptor_Curve.hxx>
46 #include <BRepLProp.hxx>
47 #include <BRep_Tool.hxx>
48 #include <GCPnts_AbscissaPoint.hxx>
49 #include <GeomAdaptor_Curve.hxx>
50 #include <Geom_Surface.hxx>
51 #include <LDOMParser.hxx>
52 #include <TopExp.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopLoc_Location.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopoDS.hxx>
58 #include <TopoDS_Edge.hxx>
59 #include <TopoDS_Face.hxx>
60 #include <TopoDS_Vertex.hxx>
61 #include <TopoDS_Wire.hxx>
62 #include <gp_Pnt.hxx>
63 #include <gp_Pnt2d.hxx>
64 #include <gp_Vec.hxx>
65
66 #include <Standard_ErrorHandler.hxx>
67 #include <Standard_Failure.hxx>
68
69 #include "utilities.h"
70
71 #include <algorithm>
72 #include <limits>
73 #include "SMESH_ProxyMesh.hxx"
74 #include "SMESH_MesherHelper.hxx"
75
76 using namespace std;
77
78 //================================================================================
79 /*!
80  * \brief Returns \a true if two algorithms (described by \a this and the given
81  *        algo data) are compatible by their output and input types of elements.
82  */
83 //================================================================================
84
85 bool SMESH_Algo::Features::IsCompatible( const SMESH_Algo::Features& algo2 ) const
86 {
87   if ( _dim > algo2._dim ) return algo2.IsCompatible( *this );
88   // algo2 is of higher dimension
89   if ( _outElemTypes.empty() || algo2._inElemTypes.empty() )
90     return false;
91   bool compatible = true;
92   set<SMDSAbs_GeometryType>::const_iterator myOutType = _outElemTypes.begin();
93   for ( ; myOutType != _outElemTypes.end() && compatible; ++myOutType )
94     compatible = algo2._inElemTypes.count( *myOutType );
95   return compatible;
96 }
97
98 //================================================================================
99 /*!
100  * \brief Return Data of the algorithm
101  */
102 //================================================================================
103
104 const SMESH_Algo::Features& SMESH_Algo::GetFeatures( const std::string& algoType )
105 {
106   static map< string, SMESH_Algo::Features > theFeaturesByName;
107   if ( theFeaturesByName.empty() )
108   {
109     // Read Plugin.xml files
110     vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
111     LDOMParser xmlParser;
112     for ( size_t iXML = 0; iXML < xmlPaths.size(); ++iXML )
113     {
114       bool error = xmlParser.parse( xmlPaths[iXML].c_str() );
115       if ( error )
116       {
117         TCollection_AsciiString data;
118         INFOS( xmlParser.GetError(data) );
119         continue;
120       }
121       // <algorithm type="Regular_1D"
122       //            ...
123       //            input="EDGE"
124       //            output="QUAD,TRIA">
125       //
126       LDOM_Document xmlDoc = xmlParser.getDocument();
127       LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
128       for ( int i = 0; i < algoNodeList.getLength(); ++i )
129       {
130         LDOM_Node     algoNode           = algoNodeList.item( i );
131         LDOM_Element& algoElem           = (LDOM_Element&) algoNode;
132         TCollection_AsciiString algoType = algoElem.getAttribute("type");
133         TCollection_AsciiString input    = algoElem.getAttribute("input");
134         TCollection_AsciiString output   = algoElem.getAttribute("output");
135         TCollection_AsciiString dim      = algoElem.getAttribute("dim");
136         TCollection_AsciiString label    = algoElem.getAttribute("label-id");
137         if ( algoType.IsEmpty() ) continue;
138
139         Features & data = theFeaturesByName[ algoType.ToCString() ];
140         data._dim   = dim.IntegerValue();
141         data._label = label.ToCString();
142         for ( int isInput = 0; isInput < 2; ++isInput )
143         {
144           TCollection_AsciiString&   typeStr = isInput ? input : output;
145           set<SMDSAbs_GeometryType>& typeSet = isInput ? data._inElemTypes : data._outElemTypes;
146           int beg = 1, end;
147           while ( beg <= typeStr.Length() )
148           {
149             while ( beg < typeStr.Length() && !isalpha( typeStr.Value( beg ) ))
150               ++beg;
151             end = beg;
152             while ( end < typeStr.Length() && isalpha( typeStr.Value( end + 1 ) ))
153               ++end;
154             if ( end > beg )
155             {
156               TCollection_AsciiString typeName = typeStr.SubString( beg, end );
157               if      ( typeName == "EDGE" ) typeSet.insert( SMDSGeom_EDGE );
158               else if ( typeName == "TRIA" ) typeSet.insert( SMDSGeom_TRIANGLE );
159               else if ( typeName == "QUAD" ) typeSet.insert( SMDSGeom_QUADRANGLE );
160             }
161             beg = end + 1;
162           }
163         }
164       }
165     }
166   }
167   return theFeaturesByName[ algoType ];
168 }
169
170 //=============================================================================
171 /*!
172  *  
173  */
174 //=============================================================================
175
176 SMESH_Algo::SMESH_Algo (int hypId, SMESH_Gen * gen)
177   : SMESH_Hypothesis(hypId, gen)
178 {
179   _compatibleAllHypFilter = _compatibleNoAuxHypFilter = NULL;
180   _onlyUnaryInput = _requireDiscreteBoundary = _requireShape = true;
181   _quadraticMesh = _supportSubmeshes = false;
182   _error = COMPERR_OK;
183   for ( int i = 0; i < 4; ++i )
184     _neededLowerHyps[ i ] = false;
185 }
186
187 //=============================================================================
188 /*!
189  *  
190  */
191 //=============================================================================
192
193 SMESH_Algo::~SMESH_Algo()
194 {
195   delete _compatibleNoAuxHypFilter;
196   // delete _compatibleAllHypFilter; -- _compatibleNoAuxHypFilter does it!!!
197 }
198
199 //=============================================================================
200 /*!
201  *  
202  */
203 //=============================================================================
204
205 SMESH_0D_Algo::SMESH_0D_Algo(int hypId, SMESH_Gen* gen)
206   : SMESH_Algo(hypId, gen)
207 {
208   _shapeType = (1 << TopAbs_VERTEX);
209   _type = ALGO_0D;
210 }
211 SMESH_1D_Algo::SMESH_1D_Algo(int hypId, SMESH_Gen* gen)
212   : SMESH_Algo(hypId, gen)
213 {
214   _shapeType = (1 << TopAbs_EDGE);
215   _type = ALGO_1D;
216 }
217 SMESH_2D_Algo::SMESH_2D_Algo(int hypId, SMESH_Gen* gen)
218   : SMESH_Algo(hypId, gen)
219 {
220   _shapeType = (1 << TopAbs_FACE);
221   _type = ALGO_2D;
222 }
223 SMESH_3D_Algo::SMESH_3D_Algo(int hypId, SMESH_Gen* gen)
224   : SMESH_Algo(hypId, gen)
225 {
226   _shapeType = (1 << TopAbs_SOLID);
227   _type = ALGO_3D;
228 }
229
230 //=============================================================================
231 /*!
232  * Usually an algorithm has nothing to save
233  */
234 //=============================================================================
235
236 ostream & SMESH_Algo::SaveTo(ostream & save) { return save; }
237 istream & SMESH_Algo::LoadFrom(istream & load) { return load; }
238
239 //=============================================================================
240 /*!
241  *  
242  */
243 //=============================================================================
244
245 const vector < string > &SMESH_Algo::GetCompatibleHypothesis()
246 {
247   return _compatibleHypothesis;
248 }
249
250 //=============================================================================
251 /*!
252  *  List the hypothesis used by the algorithm associated to the shape.
253  *  Hypothesis associated to father shape -are- taken into account (see
254  *  GetAppliedHypothesis). Relevant hypothesis have a name (type) listed in
255  *  the algorithm. This method could be surcharged by specific algorithms, in 
256  *  case of several hypothesis simultaneously applicable.
257  */
258 //=============================================================================
259
260 const list <const SMESHDS_Hypothesis *> &
261 SMESH_Algo::GetUsedHypothesis(SMESH_Mesh &         aMesh,
262                               const TopoDS_Shape & aShape,
263                               const bool           ignoreAuxiliary) const
264 {
265   SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
266   me->_usedHypList.clear();
267   if ( const SMESH_HypoFilter* filter = GetCompatibleHypoFilter( ignoreAuxiliary ))
268   {
269     aMesh.GetHypotheses( aShape, *filter, me->_usedHypList, true );
270     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
271       me->_usedHypList.clear(); //only one compatible hypothesis allowed
272   }
273   return _usedHypList;
274 }
275
276 //=============================================================================
277 /*!
278  *  List the relevant hypothesis associated to the shape. Relevant hypothesis
279  *  have a name (type) listed in the algorithm. Hypothesis associated to
280  *  father shape -are not- taken into account (see GetUsedHypothesis)
281  */
282 //=============================================================================
283
284 const list<const SMESHDS_Hypothesis *> &
285 SMESH_Algo::GetAppliedHypothesis(SMESH_Mesh &         aMesh,
286                                  const TopoDS_Shape & aShape,
287                                  const bool           ignoreAuxiliary) const
288 {
289   SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
290   me->_appliedHypList.clear();
291   if ( const SMESH_HypoFilter* filter = GetCompatibleHypoFilter( ignoreAuxiliary ))
292     aMesh.GetHypotheses( aShape, *filter, me->_appliedHypList, false );
293
294   return _appliedHypList;
295 }
296
297 //=============================================================================
298 /*!
299  *  Compute length of an edge
300  */
301 //=============================================================================
302
303 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
304 {
305   double UMin = 0, UMax = 0;
306   TopLoc_Location L;
307   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
308   if ( C.IsNull() )
309     return 0.;
310   GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
311   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
312   return length;
313 }
314
315 //================================================================================
316 /*!
317  * \brief Just return false as the algorithm does not hold parameters values
318  */
319 //================================================================================
320
321 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
322                                      const TopoDS_Shape& /*theShape*/)
323 {
324   return false;
325 }
326 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
327 {
328   return false;
329 }
330 //================================================================================
331 /*!
332  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
333  * \param theMesh - The mesh containing nodes
334  * \param theEdge - The geometrical edge of interest
335  * \param theParams - The resulting vector of sorted node parameters
336  * \retval bool - false if not all parameters are OK
337  */
338 //================================================================================
339
340 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
341                                     const TopoDS_Edge&  theEdge,
342                                     vector< double > &  theParams)
343 {
344   theParams.clear();
345
346   if ( !theMesh || theEdge.IsNull() )
347     return false;
348
349   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
350   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
351     return false; // edge is not meshed
352
353   //int nbEdgeNodes = 0;
354   set < double > paramSet;
355   if ( eSubMesh )
356   {
357     // loop on nodes of an edge: sort them by param on edge
358     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
359     while ( nIt->more() )
360     {
361       SMDS_EdgePositionPtr epos = nIt->next()->GetPosition();
362       if ( !epos )
363         return false;
364       if ( !paramSet.insert( epos->GetUParameter() ).second )
365         return false; // equal parameters
366     }
367   }
368   // add vertex nodes params
369   TopoDS_Vertex V1,V2;
370   TopExp::Vertices( theEdge, V1, V2);
371   if ( VertexNode( V1, theMesh ) &&
372        !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
373     return false; // there are equal parameters
374   if ( VertexNode( V2, theMesh ) &&
375        !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
376     return false; // there are equal parameters
377
378   // fill the vector
379   theParams.resize( paramSet.size() );
380   set < double >::iterator   par    = paramSet.begin();
381   vector< double >::iterator vecPar = theParams.begin();
382   for ( ; par != paramSet.end(); ++par, ++vecPar )
383     *vecPar = *par;
384
385   return theParams.size() > 1;
386 }
387
388 //================================================================================
389 /*!
390  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
391  * \param theMesh - The mesh containing nodes
392  * \param theEdge - The geometrical edge of interest
393  * \param theParams - The resulting vector of sorted node parameters
394  * \retval bool - false if not all parameters are OK
395  */
396 //================================================================================
397
398 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
399                                       const TopoDS_Edge&                    theEdge,
400                                       const bool                            ignoreMediumNodes,
401                                       map< double, const SMDS_MeshNode* > & theNodes,
402                                       const SMDSAbs_ElementType             typeToCheck)
403 {
404   theNodes.clear();
405
406   if ( !theMesh || theEdge.IsNull() )
407     return false;
408
409   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
410   if ( !eSubMesh || ( eSubMesh->NbElements() == 0 && eSubMesh->NbNodes() == 0))
411     return false; // edge is not meshed
412
413   int nbNodes = 0;
414   set < double > paramSet;
415   if ( eSubMesh )
416   {
417     // loop on nodes of an edge: sort them by param on edge
418     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
419     while ( nIt->more() )
420     {
421       const SMDS_MeshNode* node = nIt->next();
422       if ( ignoreMediumNodes && SMESH_MesherHelper::IsMedium( node, typeToCheck ))
423         continue;
424       SMDS_EdgePositionPtr epos = node->GetPosition();
425       if ( ! epos )
426         return false;
427       theNodes.insert( theNodes.end(), make_pair( epos->GetUParameter(), node ));
428       ++nbNodes;
429     }
430   }
431   // add vertex nodes
432   TopoDS_Vertex v1, v2;
433   TopExp::Vertices(theEdge, v1, v2);
434   const SMDS_MeshNode* n1 = VertexNode( v1, eSubMesh, 0 );
435   const SMDS_MeshNode* n2 = VertexNode( v2, eSubMesh, 0 );
436   const SMDS_MeshNode* nEnd[2] = { nbNodes ? theNodes.begin()->second  : 0,
437                                    nbNodes ? theNodes.rbegin()->second : 0 };
438   Standard_Real f, l;
439   BRep_Tool::Range(theEdge, f, l);
440   if ( v1.Orientation() != TopAbs_FORWARD )
441     std::swap( f, l );
442   if ( n1 && n1 != nEnd[0] && n1 != nEnd[1] && ++nbNodes )
443     theNodes.insert( make_pair( f, n1 ));
444   if ( n2 && n2 != nEnd[0] && n2 != nEnd[1] && ++nbNodes )
445     theNodes.insert( make_pair( l, n2 ));
446
447   return (int)theNodes.size() == nbNodes;
448 }
449
450 //================================================================================
451 /*!
452  * \brief Returns the filter recognizing only compatible hypotheses
453  *  \param ignoreAuxiliary - make filter ignore auxiliary hypotheses
454  *  \retval SMESH_HypoFilter* - the filter that can be NULL
455  */
456 //================================================================================
457
458 const SMESH_HypoFilter*
459 SMESH_Algo::GetCompatibleHypoFilter(const bool ignoreAuxiliary) const
460 {
461   if ( !_compatibleHypothesis.empty() )
462   {
463     if ( !_compatibleAllHypFilter )
464     {
465       SMESH_HypoFilter* filter = new SMESH_HypoFilter();
466       filter->Init( filter->HasName( _compatibleHypothesis[0] ));
467       for ( size_t i = 1; i < _compatibleHypothesis.size(); ++i )
468         filter->Or( filter->HasName( _compatibleHypothesis[ i ] ));
469
470       SMESH_HypoFilter* filterNoAux = new SMESH_HypoFilter( filter );
471       filterNoAux->AndNot( filterNoAux->IsAuxiliary() );
472
473       // _compatibleNoAuxHypFilter will detele _compatibleAllHypFilter!!!
474       SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
475       me->_compatibleAllHypFilter   = filter;
476       me->_compatibleNoAuxHypFilter = filterNoAux;
477     }
478     return ignoreAuxiliary ? _compatibleNoAuxHypFilter : _compatibleAllHypFilter;
479   }
480   return 0;
481 }
482
483 //================================================================================
484 /*!
485  * \brief Return continuity of two edges
486  * \param E1 - the 1st edge
487  * \param E2 - the 2nd edge
488  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
489  */
490 //================================================================================
491
492 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge& theE1,
493                                      const TopoDS_Edge& theE2)
494 {
495   // avoid pb with internal edges
496   TopoDS_Edge E1 = theE1, E2 = theE2;
497   if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
498     E1.Orientation( TopAbs_FORWARD );
499   if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
500     E2.Orientation( TopAbs_FORWARD );
501
502   TopoDS_Vertex V, VV1[2], VV2[2];
503   TopExp::Vertices( E1, VV1[0], VV1[1], true );
504   TopExp::Vertices( E2, VV2[0], VV2[1], true );
505   if      ( VV1[1].IsSame( VV2[0] ))  { V = VV1[1]; }
506   else if ( VV1[0].IsSame( VV2[1] ))  { V = VV1[0]; }
507   else if ( VV1[1].IsSame( VV2[1] ))  { V = VV1[1]; E1.Reverse(); }
508   else if ( VV1[0].IsSame( VV2[0] ))  { V = VV1[0]; E1.Reverse(); }
509   else { return GeomAbs_C0; }
510
511   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
512   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
513   BRepAdaptor_Curve C1( E1 ), C2( E2 );
514   Standard_Real tol = BRep_Tool::Tolerance( V );
515   Standard_Real angTol = 2e-3;
516   try {
517     OCC_CATCH_SIGNALS;
518     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
519   }
520   catch (Standard_Failure) {
521   }
522   return GeomAbs_C0;
523 }
524
525 //================================================================================
526 /*!
527  * \brief Return true if an edge can be considered straight
528  */
529 //================================================================================
530
531 bool SMESH_Algo::IsStraight( const TopoDS_Edge & E,
532                              const bool          degenResult)
533 {
534   {
535     double f,l;
536     if ( BRep_Tool::Curve( E, f, l ).IsNull())
537       return degenResult;
538   }
539   BRepAdaptor_Curve curve( E );
540   switch( curve.GetType() )
541   {
542   case GeomAbs_Line:
543     return true;
544   case GeomAbs_Circle:
545   case GeomAbs_Ellipse:
546   case GeomAbs_Hyperbola:
547   case GeomAbs_Parabola:
548     return false;
549     // case GeomAbs_BezierCurve:
550     // case GeomAbs_BSplineCurve:
551     // case GeomAbs_OtherCurve:
552   default:;
553   }
554
555   // evaluate how far from a straight line connecting the curve ends
556   // stand internal points of the curve
557   double  f = curve.FirstParameter();
558   double  l = curve.LastParameter();
559   gp_Pnt pf = curve.Value( f );
560   gp_Pnt pl = curve.Value( l );
561   gp_Vec lineVec( pf, pl );
562   double lineLen2 = lineVec.SquareMagnitude();
563   if ( lineLen2 < std::numeric_limits< double >::min() )
564     return false; // E seems closed
565
566   double edgeTol = 10 * curve.Tolerance();
567   double lenTol2 = lineLen2 * 1e-4; 
568   double tol2 = Min( edgeTol * edgeTol, lenTol2 );
569
570   const double nbSamples = 7;
571   for ( int i = 0; i < nbSamples; ++i )
572   {
573     double  r = ( i + 1 ) / nbSamples;
574     gp_Pnt pi = curve.Value( f * r + l * ( 1 - r ));
575     gp_Vec vi( pf, pi );
576     double h2 = lineVec.Crossed( vi ).SquareMagnitude() / lineLen2;
577     if ( h2 > tol2 )
578       return false;
579   }
580   return true;
581 }
582
583 //================================================================================
584 /*!
585  * \brief Return true if an edge has no 3D curve
586  */
587 //================================================================================
588
589 bool SMESH_Algo::isDegenerated( const TopoDS_Edge & E, const bool checkLength )
590 {
591   if ( checkLength )
592     return EdgeLength( E ) == 0;
593   double f,l;
594   TopLoc_Location loc;
595   Handle(Geom_Curve) C = BRep_Tool::Curve( E, loc, f,l );
596   return C.IsNull();
597 }
598
599 //================================================================================
600 /*!
601  * \brief Return the node built on a vertex
602  * \param V - the vertex
603  * \param meshDS - mesh
604  * \retval const SMDS_MeshNode* - found node or NULL
605  * \sa SMESH_MesherHelper::GetSubShapeByNode( const SMDS_MeshNode*, SMESHDS_Mesh* )
606  */
607 //================================================================================
608
609 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
610                                             const SMESHDS_Mesh*  meshDS)
611 {
612   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
613     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
614     if (nIt->more())
615       return nIt->next();
616   }
617   return 0;
618 }
619
620 //=======================================================================
621 /*!
622  * \brief Return the node built on a vertex.
623  *        A node moved to other geometry by MergeNodes() is also returned.
624  * \param V - the vertex
625  * \param mesh - mesh
626  * \retval const SMDS_MeshNode* - found node or NULL
627  */
628 //=======================================================================
629
630 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
631                                             const SMESH_Mesh*    mesh)
632 {
633   const SMDS_MeshNode* node = VertexNode( V, mesh->GetMeshDS() );
634
635   if ( !node && mesh->HasModificationsToDiscard() )
636   {
637     PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *mesh, TopAbs_EDGE );
638     while ( const TopoDS_Shape* edge = edgeIt->next() )
639       if ( SMESHDS_SubMesh* edgeSM = mesh->GetMeshDS()->MeshElements( *edge ))
640         if ( edgeSM->NbElements() > 0 )
641           return VertexNode( V, edgeSM, mesh, /*checkV=*/false );
642   }
643   return node;
644 }
645
646 //=======================================================================
647 /*!
648  * \brief Return the node built on a vertex.
649  *        A node moved to other geometry by MergeNodes() is also returned.
650  * \param V - the vertex
651  * \param edgeSM - sub-mesh of a meshed EDGE sharing the vertex
652  * \param checkV - if \c true, presence of a node on the vertex is checked
653  * \retval const SMDS_MeshNode* - found node or NULL
654  */
655 //=======================================================================
656
657 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex&   V,
658                                             const SMESHDS_SubMesh* edgeSM,
659                                             const SMESH_Mesh*      mesh,
660                                             const bool             checkV)
661 {
662   const SMDS_MeshNode* node = checkV ? VertexNode( V, edgeSM->GetParent() ) : 0;
663
664   if ( !node && edgeSM )
665   {
666     // find nodes not shared by mesh segments
667     typedef set< const SMDS_MeshNode* >                       TNodeSet;
668     typedef map< const SMDS_MeshNode*, const SMDS_MeshNode* > TNodeMap;
669     TNodeMap notSharedNodes;
670     TNodeSet otherShapeNodes;
671     vector< const SMDS_MeshNode* > segNodes(3);
672     SMDS_ElemIteratorPtr segIt = edgeSM->GetElements();
673     while ( segIt->more() )
674     {
675       const SMDS_MeshElement* seg = segIt->next();
676       if ( seg->GetType() != SMDSAbs_Edge )
677         return node;
678       segNodes.assign( seg->begin_nodes(), seg->end_nodes() );
679       for ( int i = 0; i < 2; ++i )
680       {
681         const SMDS_MeshNode* n1 = segNodes[i];
682         const SMDS_MeshNode* n2 = segNodes[1-i];
683         pair<TNodeMap::iterator, bool> it2new = notSharedNodes.insert( make_pair( n1, n2 ));
684         if ( !it2new.second ) // n encounters twice
685           notSharedNodes.erase( it2new.first );
686         if ( n1->getshapeId() != edgeSM->GetID() )
687           otherShapeNodes.insert( n1 );
688       }
689     }
690     if ( otherShapeNodes.size() == 1 && notSharedNodes.empty() ) // a closed EDGE
691       return *otherShapeNodes.begin();
692
693     if ( notSharedNodes.size() == 2 ) // two end nodes found
694     {
695       SMESHDS_Mesh*  meshDS = edgeSM->GetParent();
696       const TopoDS_Shape& E = meshDS->IndexToShape( edgeSM->GetID() );
697       if ( E.IsNull() || E.ShapeType() != TopAbs_EDGE )
698         return node;
699       const SMDS_MeshNode* n1 = notSharedNodes.begin ()->first;
700       const SMDS_MeshNode* n2 = notSharedNodes.rbegin()->first;
701       TopoDS_Shape S1 = SMESH_MesherHelper::GetSubShapeByNode( n1, meshDS );
702       if ( S1.ShapeType() == TopAbs_VERTEX && SMESH_MesherHelper::IsSubShape( S1, E ))
703         return n2;
704       TopoDS_Shape S2 = SMESH_MesherHelper::GetSubShapeByNode( n2, meshDS );
705       if ( S2.ShapeType() == TopAbs_VERTEX && SMESH_MesherHelper::IsSubShape( S2, E ))
706         return n1;
707       if ( edgeSM->NbElements() <= 2 || !mesh ) // one-two segments
708       {
709         gp_Pnt pV = BRep_Tool::Pnt( V );
710         double dist1 = pV.SquareDistance( SMESH_TNodeXYZ( n1 ));
711         double dist2 = pV.SquareDistance( SMESH_TNodeXYZ( n2 ));
712         return dist1 < dist2 ? n1 : n2;
713       }
714       if ( mesh )
715       {
716         SMESH_MesherHelper helper( const_cast<SMESH_Mesh&>( *mesh ));
717         const SMDS_MeshNode* n1i = notSharedNodes.begin ()->second;
718         const SMDS_MeshNode* n2i = notSharedNodes.rbegin()->second;
719         const TopoDS_Edge&  edge = TopoDS::Edge( E );
720         bool  posOK = true;
721         double pos1 = helper.GetNodeU( edge, n1i, n2i, &posOK );
722         double pos2 = helper.GetNodeU( edge, n2i, n1i, &posOK );
723         double posV = BRep_Tool::Parameter( V, edge );
724         if ( Abs( pos1 - posV ) < Abs( pos2 - posV )) return n1;
725         else                                          return n2;
726       }
727     }
728   }
729   return node;
730 }
731
732 //=======================================================================
733 //function : GetMeshError
734 //purpose  : Finds topological errors of a sub-mesh
735 //WARNING  : 1D check is NOT implemented so far
736 //=======================================================================
737
738 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
739 {
740   EMeshError err = MEr_OK;
741
742   SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
743   if ( !smDS )
744     return MEr_EMPTY;
745
746   switch ( subMesh->GetSubShape().ShapeType() )
747   {
748   case TopAbs_FACE: { // ====================== 2D =====================
749
750     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
751     if ( !fIt->more() )
752       return MEr_EMPTY;
753
754     // We check that only links on EDGEs encouter once, the rest links, twice
755     set< SMESH_TLink > links;
756     while ( fIt->more() )
757     {
758       const SMDS_MeshElement* f = fIt->next();
759       int nbNodes = f->NbCornerNodes(); // ignore medium nodes
760       for ( int i = 0; i < nbNodes; ++i )
761       {
762         const SMDS_MeshNode* n1 = f->GetNode( i );
763         const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
764         std::pair< set< SMESH_TLink >::iterator, bool > it_added =
765           links.insert( SMESH_TLink( n1, n2 ));
766         if ( !it_added.second )
767           // As we do NOT(!) check if mesh is manifold, we believe that a link can
768           // encounter once or twice only (not three times), we erase a link as soon
769           // as it encounters twice to speed up search in the <links> map.
770           links.erase( it_added.first );
771       }
772     }
773     // the links remaining in the <links> should all be on EDGE
774     set< SMESH_TLink >::iterator linkIt = links.begin();
775     for ( ; linkIt != links.end(); ++linkIt )
776     {
777       const SMESH_TLink& link = *linkIt;
778       if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
779            link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
780         return MEr_HOLES;
781     }
782     // TODO: to check orientation
783     break;
784   }
785   case TopAbs_SOLID: { // ====================== 3D =====================
786
787     SMDS_ElemIteratorPtr vIt = smDS->GetElements();
788     if ( !vIt->more() )
789       return MEr_EMPTY;
790
791     SMDS_VolumeTool vTool;
792     while ( !vIt->more() )
793     {
794       if (!vTool.Set( vIt->next() ))
795         continue; // strange
796
797       for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
798         if ( vTool.IsFreeFace( iF ))
799         {
800           int nbN = vTool.NbFaceNodes( iF );
801           const SMDS_MeshNode** nodes =  vTool.GetFaceNodes( iF );
802           for ( int i = 0; i < nbN; ++i )
803             if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
804               return MEr_HOLES;
805         }
806     }
807     break;
808   }
809   default:;
810   }
811   return err;
812 }
813
814 //================================================================================
815 /*!
816  * \brief Sets event listener to submeshes if necessary
817  * \param subMesh - submesh where algo is set
818  * 
819  * After being set, event listener is notified on each event of a submesh.
820  * By default non listener is set
821  */
822 //================================================================================
823
824 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
825 {
826 }
827
828 //================================================================================
829 /*!
830  * \brief Allow algo to do something after persistent restoration
831  * \param subMesh - restored submesh
832  *
833  * This method is called only if a submesh has HYP_OK algo_state.
834  */
835 //================================================================================
836
837 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
838 {
839 }
840
841 //================================================================================
842 /*!
843  * \brief Computes mesh without geometry
844  * \param aMesh - the mesh
845  * \param aHelper - helper that must be used for adding elements to \aaMesh
846  * \retval bool - is a success
847  */
848 //================================================================================
849
850 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
851 {
852   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
853 }
854
855 //=======================================================================
856 //function : IsApplicableToShape
857 //purpose  : Return true if the algorithm can mesh a given shape
858 //=======================================================================
859
860 bool SMESH_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool toCheckAll) const
861 {
862   return true;
863 }
864
865 //=======================================================================
866 //function : CancelCompute
867 //purpose  : Sets _computeCanceled to true. It's usage depends on
868 //  *        implementation of a particular mesher.
869 //=======================================================================
870
871 void SMESH_Algo::CancelCompute()
872 {
873   _computeCanceled = true;
874   _error = COMPERR_CANCELED;
875 }
876
877 //================================================================================
878 /*
879  * If possible, returns progress of computation [0.,1.]
880  */
881 //================================================================================
882
883 double SMESH_Algo::GetProgress() const
884 {
885   return _progress;
886 }
887
888 //================================================================================
889 /*!
890  * \brief store error and comment and then return ( error == COMPERR_OK )
891  */
892 //================================================================================
893
894 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
895 {
896   _error   = error;
897   _comment = comment;
898   return ( error == COMPERR_OK );
899 }
900
901 //================================================================================
902 /*!
903  * \brief store error and return ( error == COMPERR_OK )
904  */
905 //================================================================================
906
907 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
908 {
909   if ( error ) {
910     _error   = error->myName;
911     _comment = error->myComment;
912     if ( error->HasBadElems() )
913     {
914       SMESH_BadInputElements* badElems = static_cast<SMESH_BadInputElements*>( error.get() );
915       _badInputElements = badElems->GetElements();
916       _mesh             = badElems->GetMesh();
917     }
918     return error->IsOK();
919   }
920   return true;
921 }
922
923 //================================================================================
924 /*!
925  * \brief return compute error
926  */
927 //================================================================================
928
929 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
930 {
931   if ( !_badInputElements.empty() && _mesh )
932   {
933     SMESH_BadInputElements* err = new SMESH_BadInputElements( _mesh, _error, _comment, this );
934     // hope this method is called by only SMESH_subMesh after this->Compute()
935     err->myBadElements.splice( err->myBadElements.end(),
936                                (list<const SMDS_MeshElement*>&) _badInputElements );
937     return SMESH_ComputeErrorPtr( err );
938   }
939   return SMESH_ComputeError::New( _error, _comment, this );
940 }
941
942 //================================================================================
943 /*!
944  * \brief initialize compute error before call of Compute()
945  */
946 //================================================================================
947
948 void SMESH_Algo::InitComputeError()
949 {
950   _error = COMPERR_OK;
951   _comment.clear();
952   list<const SMDS_MeshElement*>::iterator elem = _badInputElements.begin();
953   for ( ; elem != _badInputElements.end(); ++elem )
954     if ( (*elem)->GetID() < 1 )
955       delete *elem;
956   _badInputElements.clear();
957   _mesh = 0;
958
959   _computeCanceled = false;
960   _progressTic     = 0;
961   _progress        = 0.;
962 }
963
964 //================================================================================
965 /*!
966  * \brief Return compute progress by nb of calls of this method
967  */
968 //================================================================================
969
970 double SMESH_Algo::GetProgressByTic() const
971 {
972   int computeCost = 0;
973   for ( size_t i = 0; i < _smToCompute.size(); ++i )
974     computeCost += _smToCompute[i]->GetComputeCost();
975
976   const_cast<SMESH_Algo*>( this )->_progressTic++;
977
978   double x = 5 * _progressTic;
979   x = ( x < computeCost ) ? ( x / computeCost ) : 1.;
980   return 0.9 * sin( x * M_PI / 2 );
981 }
982
983 //================================================================================
984 /*!
985  * \brief store a bad input element preventing computation,
986  *        which may be a temporary one i.e. not residing the mesh,
987  *        then it will be deleted by InitComputeError()
988  */
989 //================================================================================
990
991 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
992 {
993   if ( elem )
994     _badInputElements.push_back( elem );
995 }
996
997 //=======================================================================
998 //function : addBadInputElements
999 //purpose  : store a bad input elements or nodes preventing computation
1000 //=======================================================================
1001
1002 void SMESH_Algo::addBadInputElements(const SMESHDS_SubMesh* sm,
1003                                      const bool             addNodes)
1004 {
1005   if ( sm )
1006   {
1007     if ( addNodes )
1008     {
1009       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
1010       while ( nIt->more() ) addBadInputElement( nIt->next() );
1011     }
1012     else
1013     {
1014       SMDS_ElemIteratorPtr eIt = sm->GetElements();
1015       while ( eIt->more() ) addBadInputElement( eIt->next() );
1016     }
1017   }
1018 }
1019
1020 //=============================================================================
1021 /*!
1022  *  
1023  */
1024 //=============================================================================
1025
1026 // int SMESH_Algo::NumberOfWires(const TopoDS_Shape& S)
1027 // {
1028 //   int i = 0;
1029 //   for (TopExp_Explorer exp(S,TopAbs_WIRE); exp.More(); exp.Next())
1030 //     i++;
1031 //   return i;
1032 // }
1033
1034 //=============================================================================
1035 /*!
1036  *  
1037  */
1038 //=============================================================================
1039
1040 int SMESH_Algo::NumberOfPoints(SMESH_Mesh& aMesh, const TopoDS_Wire& W)
1041 {
1042   int nbPoints = 0;
1043   for (TopExp_Explorer exp(W,TopAbs_EDGE); exp.More(); exp.Next()) {
1044     const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1045     int nb = aMesh.GetSubMesh(E)->GetSubMeshDS()->NbNodes();
1046     if(_quadraticMesh)
1047       nb = nb/2;
1048     nbPoints += nb + 1; // internal points plus 1 vertex of 2 (last point ?)
1049   }
1050   return nbPoints;
1051 }
1052
1053
1054 //================================================================================
1055 /*!
1056  * Method in which an algorithm generating a structured mesh
1057  * fixes positions of in-face nodes after there movement
1058  * due to insertion of viscous layers.
1059  */
1060 //================================================================================
1061
1062 bool SMESH_2D_Algo::FixInternalNodes(const SMESH_ProxyMesh& mesh,
1063                                      const TopoDS_Face&     face)
1064 {
1065   const SMESHDS_SubMesh* smDS = mesh.GetSubMesh(face);
1066   if ( !smDS || smDS->NbElements() < 1 )
1067     return false;
1068
1069   SMESH_MesherHelper helper( *mesh.GetMesh() );
1070
1071   // get all faces from a proxy sub-mesh
1072   typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TIterator;
1073   TIDSortedElemSet allFaces( TIterator( smDS->GetElements() ), TIterator() );
1074   TIDSortedElemSet avoidSet, firstRowQuads;
1075
1076   // indices of nodes to pass to a neighbour quad using SMESH_MeshAlgos::FindFaceInSet()
1077   int iN1, iN2;
1078
1079   // get two first rows of nodes by passing through the first row of faces
1080   vector< vector< const SMDS_MeshNode* > > nodeRows;
1081   int iRow1 = 0, iRow2 = 1;
1082   const SMDS_MeshElement* quad;
1083   {
1084     // look for a corner quadrangle and it's corner node
1085     const SMDS_MeshElement* cornerQuad = 0;
1086     int                     cornerNodeInd = -1;
1087     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
1088     while ( !cornerQuad && fIt->more() )
1089     {
1090       cornerQuad = fIt->next();
1091       if ( cornerQuad->NbCornerNodes() != 4 )
1092         return false;
1093       SMDS_NodeIteratorPtr nIt = cornerQuad->nodeIterator();
1094       for ( int i = 0; i < 4; ++i )
1095       {
1096         int nbInverseQuads = 0;
1097         SMDS_ElemIteratorPtr fIt = nIt->next()->GetInverseElementIterator(SMDSAbs_Face);
1098         while ( fIt->more() )
1099           nbInverseQuads += allFaces.count( fIt->next() );
1100         if ( nbInverseQuads == 1 )
1101           cornerNodeInd = i, i = 4;
1102       }
1103       if ( cornerNodeInd < 0 )
1104         cornerQuad = 0;
1105     }
1106     if ( !cornerQuad || cornerNodeInd < 0 )
1107       return false;
1108
1109     iN1     = helper.WrapIndex( cornerNodeInd + 1, 4 );
1110     iN2     = helper.WrapIndex( cornerNodeInd + 2, 4 );
1111     int iN3 = helper.WrapIndex( cornerNodeInd + 3, 4 );
1112     nodeRows.resize(2);
1113     nodeRows[iRow1].push_back( cornerQuad->GetNode( cornerNodeInd ));
1114     nodeRows[iRow1].push_back( cornerQuad->GetNode( iN1 ));
1115     nodeRows[iRow2].push_back( cornerQuad->GetNode( iN3 ));
1116     nodeRows[iRow2].push_back( cornerQuad->GetNode( iN2 ));
1117     firstRowQuads.insert( cornerQuad );
1118
1119     // pass through the rest quads in a face row
1120     quad = cornerQuad;
1121     while ( quad )
1122     {
1123       avoidSet.clear();
1124       avoidSet.insert( quad );
1125       if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1].back(),
1126                                                    nodeRows[iRow2].back(),
1127                                                    allFaces, avoidSet, &iN1, &iN2)))
1128       {
1129         nodeRows[iRow1].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1130         nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1131         if ( quad->NbCornerNodes() != 4 )
1132           return false;
1133       }
1134     }
1135     if ( nodeRows[iRow1].size() < 3 )
1136       return true; // there is nothing to fix
1137   }
1138
1139   nodeRows.reserve( smDS->NbElements() / nodeRows[iRow1].size() );
1140
1141   // get the rest node rows
1142   while ( true )
1143   {
1144     ++iRow1, ++iRow2;
1145
1146     // get the first quad in the next face row 
1147     if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][0],
1148                                                  nodeRows[iRow1][1],
1149                                                  allFaces, /*avoid=*/firstRowQuads,
1150                                                  &iN1, &iN2)))
1151     {
1152       if ( quad->NbCornerNodes() != 4 )
1153         return false;
1154       nodeRows.resize( iRow2+1 );
1155       nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1156       nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1157       firstRowQuads.insert( quad );
1158     }
1159     else
1160     {
1161       break; // no more rows
1162     }
1163
1164     // pass through the rest quads in a face row
1165     while ( quad )
1166     {
1167       avoidSet.clear();
1168       avoidSet.insert( quad );
1169       if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][ nodeRows[iRow2].size()-1 ],
1170                                                    nodeRows[iRow2].back(),
1171                                                    allFaces, avoidSet, &iN1, &iN2)))
1172       {
1173         if ( quad->NbCornerNodes() != 4 )
1174           return false;
1175         nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1176       }
1177     }
1178     if ( nodeRows[iRow1].size() != nodeRows[iRow2].size() )
1179       return false;
1180   }
1181   if ( nodeRows.size() < 3 )
1182     return true; // there is nothing to fix
1183
1184   // get params of the first (bottom) and last (top) node rows
1185   UVPtStructVec uvB( nodeRows[0].size() ), uvT( nodeRows[0].size() );
1186   for ( int isBot = 0; isBot < 2; ++isBot )
1187   {
1188     UVPtStructVec &                  uvps = isBot ? uvB : uvT;
1189     vector< const SMDS_MeshNode* >& nodes = nodeRows[ isBot ? 0 : nodeRows.size()-1 ];
1190     for ( size_t i = 0; i < nodes.size(); ++i )
1191     {
1192       uvps[i].node = nodes[i];
1193       gp_XY uv = helper.GetNodeUV( face, uvps[i].node );
1194       uvps[i].u = uv.Coord(1);
1195       uvps[i].v = uv.Coord(2);
1196       uvps[i].x = 0;
1197     }
1198     // calculate x (normalized param)
1199     for ( size_t i = 1; i < nodes.size(); ++i )
1200       uvps[i].x = uvps[i-1].x + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1201     for ( size_t i = 1; i < nodes.size(); ++i )
1202       uvps[i].x /= uvps.back().x;
1203   }
1204
1205   // get params of the left and right node rows
1206   UVPtStructVec uvL( nodeRows.size() ), uvR( nodeRows.size() );
1207   for ( int isLeft = 0; isLeft < 2; ++isLeft )
1208   {
1209     UVPtStructVec & uvps = isLeft ? uvL : uvR;
1210     const int       iCol = isLeft ? 0 : nodeRows[0].size() - 1;
1211     for ( size_t i = 0; i < nodeRows.size(); ++i )
1212     {
1213       uvps[i].node = nodeRows[i][iCol];
1214       gp_XY uv = helper.GetNodeUV( face, uvps[i].node );
1215       uvps[i].u = uv.Coord(1);
1216       uvps[i].v = uv.Coord(2);
1217       uvps[i].y = 0;
1218     }
1219     // calculate y (normalized param)
1220     for ( size_t i = 1; i < nodeRows.size(); ++i )
1221       uvps[i].y = uvps[i-1].y + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1222     for ( size_t i = 1; i < nodeRows.size(); ++i )
1223       uvps[i].y /= uvps.back().y;
1224   }
1225
1226   // update node coordinates
1227   SMESHDS_Mesh*   meshDS = mesh.GetMeshDS();
1228   Handle(Geom_Surface) S = BRep_Tool::Surface( face );
1229   gp_XY a0 ( uvB.front().u, uvB.front().v );
1230   gp_XY a1 ( uvB.back().u,  uvB.back().v );
1231   gp_XY a2 ( uvT.back().u,  uvT.back().v );
1232   gp_XY a3 ( uvT.front().u, uvT.front().v );
1233   for ( size_t iRow = 1; iRow < nodeRows.size()-1; ++iRow )
1234   {
1235     gp_XY p1 ( uvR[ iRow ].u, uvR[ iRow ].v );
1236     gp_XY p3 ( uvL[ iRow ].u, uvL[ iRow ].v );
1237     const double y0 = uvL[ iRow ].y;
1238     const double y1 = uvR[ iRow ].y;
1239     for ( size_t iCol = 1; iCol < nodeRows[0].size()-1; ++iCol )
1240     {
1241       gp_XY p0 ( uvB[ iCol ].u, uvB[ iCol ].v );
1242       gp_XY p2 ( uvT[ iCol ].u, uvT[ iCol ].v );
1243       const double x0 = uvB[ iCol ].x;
1244       const double x1 = uvT[ iCol ].x;
1245       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1246       double y = y0 + x * (y1 - y0);
1247       gp_XY uv = helper.calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
1248       gp_Pnt p = S->Value( uv.Coord(1), uv.Coord(2));
1249       const SMDS_MeshNode* n = nodeRows[iRow][iCol];
1250       meshDS->MoveNode( n, p.X(), p.Y(), p.Z() );
1251       if ( SMDS_FacePositionPtr pos = n->GetPosition() )
1252         pos->SetParameters( uv.Coord(1), uv.Coord(2) );
1253     }
1254   }
1255   return true;
1256 }