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