Salome HOME
Parallel version for 1d mesher number of segment
[modules/smesh.git] / src / SMESH / SMESH_Algo.cxx
1 // Copyright (C) 2007-2022  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
267   std::list<const SMESHDS_Hypothesis *> savedHyps; // don't delete the list if
268   savedHyps.swap( me->_usedHypList );              // it does not change (#16578)
269
270   me->_usedHypList.clear();
271   me->_assigedShapeList.clear();
272   if ( const SMESH_HypoFilter* filter = GetCompatibleHypoFilter( ignoreAuxiliary ))
273   {
274     aMesh.GetHypotheses( aShape, *filter, me->_usedHypList, true, & me->_assigedShapeList );
275     if ( ignoreAuxiliary && _usedHypList.size() > 1 )
276     {
277       me->_usedHypList.clear(); //only one compatible hypothesis allowed
278       me->_assigedShapeList.clear();
279     }
280   }
281   if ( _usedHypList == savedHyps )
282     savedHyps.swap( me->_usedHypList );
283
284   for(auto hyp:_usedHypList){
285     std::cout << hyp << std::endl;
286   }
287   return _usedHypList;
288 }
289
290 //================================================================================
291 /*!
292  * Return sub-shape to which hypotheses returned by GetUsedHypothesis() are assigned
293  */
294 //================================================================================
295
296 const std::list < TopoDS_Shape > & SMESH_Algo::GetAssignedShapes() const
297 {
298   return _assigedShapeList;
299 }
300
301 //=============================================================================
302 /*!
303  *  Compute length of an edge
304  */
305 //=============================================================================
306
307 double SMESH_Algo::EdgeLength(const TopoDS_Edge & E)
308 {
309   double UMin = 0, UMax = 0;
310   TopLoc_Location L;
311   Handle(Geom_Curve) C = BRep_Tool::Curve(E, L, UMin, UMax);
312   if ( C.IsNull() )
313     return 0.;
314   GeomAdaptor_Curve AdaptCurve(C, UMin, UMax); //range is important for periodic curves
315   double length = GCPnts_AbscissaPoint::Length(AdaptCurve, UMin, UMax);
316   return length;
317 }
318
319 //================================================================================
320 /*!
321  * \brief Just return false as the algorithm does not hold parameters values
322  */
323 //================================================================================
324
325 bool SMESH_Algo::SetParametersByMesh(const SMESH_Mesh* /*theMesh*/,
326                                      const TopoDS_Shape& /*theShape*/)
327 {
328   return false;
329 }
330 bool SMESH_Algo::SetParametersByDefaults(const TDefaults& , const SMESH_Mesh*)
331 {
332   return false;
333 }
334 //================================================================================
335 /*!
336  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
337  * \param theMesh - The mesh containing nodes
338  * \param theEdge - The geometrical edge of interest
339  * \param theParams - The resulting vector of sorted node parameters
340  * \retval bool - false if not all parameters are OK
341  */
342 //================================================================================
343
344 bool SMESH_Algo::GetNodeParamOnEdge(const SMESHDS_Mesh* theMesh,
345                                     const TopoDS_Edge&  theEdge,
346                                     vector< double > &  theParams)
347 {
348   theParams.clear();
349
350   if ( !theMesh || theEdge.IsNull() )
351     return false;
352
353   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
354   if ( !eSubMesh || !eSubMesh->GetElements()->more() )
355     return false; // edge is not meshed
356
357   //int nbEdgeNodes = 0;
358   set < double > paramSet;
359   if ( eSubMesh )
360   {
361     // loop on nodes of an edge: sort them by param on edge
362     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
363     while ( nIt->more() )
364     {
365       SMDS_EdgePositionPtr epos = nIt->next()->GetPosition();
366       if ( !epos )
367         return false;
368       if ( !paramSet.insert( epos->GetUParameter() ).second )
369         return false; // equal parameters
370     }
371   }
372   // add vertex nodes params
373   TopoDS_Vertex V1,V2;
374   TopExp::Vertices( theEdge, V1, V2);
375   if ( VertexNode( V1, theMesh ) &&
376        !paramSet.insert( BRep_Tool::Parameter(V1,theEdge) ).second )
377     return false; // there are equal parameters
378   if ( VertexNode( V2, theMesh ) &&
379        !paramSet.insert( BRep_Tool::Parameter(V2,theEdge) ).second )
380     return false; // there are equal parameters
381
382   // fill the vector
383   theParams.resize( paramSet.size() );
384   set < double >::iterator   par    = paramSet.begin();
385   vector< double >::iterator vecPar = theParams.begin();
386   for ( ; par != paramSet.end(); ++par, ++vecPar )
387     *vecPar = *par;
388
389   return theParams.size() > 1;
390 }
391
392 //================================================================================
393 /*!
394  * \brief Fill vector of node parameters on geometrical edge, including vertex nodes
395  * \param theMesh - The mesh containing nodes
396  * \param theEdge - The geometrical edge of interest
397  * \param theParams - The resulting vector of sorted node parameters
398  * \retval bool - false if not all parameters are OK
399  */
400 //================================================================================
401
402 bool SMESH_Algo::GetSortedNodesOnEdge(const SMESHDS_Mesh*                   theMesh,
403                                       const TopoDS_Edge&                    theEdge,
404                                       const bool                            ignoreMediumNodes,
405                                       map< double, const SMDS_MeshNode* > & theNodes,
406                                       const SMDSAbs_ElementType             typeToCheck)
407 {
408   theNodes.clear();
409
410   if ( !theMesh || theEdge.IsNull() )
411     return false;
412
413   SMESHDS_SubMesh * eSubMesh = theMesh->MeshElements( theEdge );
414   if ( !eSubMesh || ( eSubMesh->NbElements() == 0 && eSubMesh->NbNodes() == 0))
415     return false; // edge is not meshed
416
417   int nbNodes = 0;
418   set < double > paramSet;
419   if ( eSubMesh )
420   {
421     // loop on nodes of an edge: sort them by param on edge
422     SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
423     while ( nIt->more() )
424     {
425       const SMDS_MeshNode* node = nIt->next();
426       if ( ignoreMediumNodes && SMESH_MesherHelper::IsMedium( node, typeToCheck ))
427         continue;
428       SMDS_EdgePositionPtr epos = node->GetPosition();
429       if ( ! epos )
430         return false;
431       theNodes.insert( theNodes.end(), make_pair( epos->GetUParameter(), node ));
432       ++nbNodes;
433     }
434   }
435   // add vertex nodes
436   TopoDS_Vertex v1, v2;
437   TopExp::Vertices(theEdge, v1, v2);
438   const SMDS_MeshNode* n1 = VertexNode( v1, eSubMesh, 0 );
439   const SMDS_MeshNode* n2 = VertexNode( v2, eSubMesh, 0 );
440   const SMDS_MeshNode* nEnd[2] = { nbNodes ? theNodes.begin()->second  : 0,
441                                    nbNodes ? theNodes.rbegin()->second : 0 };
442   Standard_Real f, l;
443   BRep_Tool::Range(theEdge, f, l);
444   if ( v1.Orientation() != TopAbs_FORWARD )
445     std::swap( f, l );
446   if ( n1 && n1 != nEnd[0] && n1 != nEnd[1] && ++nbNodes )
447     theNodes.insert( make_pair( f, n1 ));
448   if ( n2 && n2 != nEnd[0] && n2 != nEnd[1] && ++nbNodes )
449     theNodes.insert( make_pair( l, n2 ));
450
451   return (int)theNodes.size() == nbNodes;
452 }
453
454 //================================================================================
455 /*!
456  * \brief Returns the filter recognizing only compatible hypotheses
457  *  \param ignoreAuxiliary - make filter ignore auxiliary hypotheses
458  *  \retval SMESH_HypoFilter* - the filter that can be NULL
459  */
460 //================================================================================
461
462 const SMESH_HypoFilter*
463 SMESH_Algo::GetCompatibleHypoFilter(const bool ignoreAuxiliary) const
464 {
465   if ( !_compatibleHypothesis.empty() )
466   {
467     if ( !_compatibleAllHypFilter )
468     {
469       SMESH_HypoFilter* filter = new SMESH_HypoFilter();
470       filter->Init( filter->HasName( _compatibleHypothesis[0] ));
471       for ( size_t i = 1; i < _compatibleHypothesis.size(); ++i )
472         filter->Or( filter->HasName( _compatibleHypothesis[ i ] ));
473
474       SMESH_HypoFilter* filterNoAux = new SMESH_HypoFilter( filter );
475       filterNoAux->AndNot( filterNoAux->IsAuxiliary() );
476
477       // _compatibleNoAuxHypFilter will detele _compatibleAllHypFilter!!!
478       SMESH_Algo* me = const_cast< SMESH_Algo* >( this );
479       me->_compatibleAllHypFilter   = filter;
480       me->_compatibleNoAuxHypFilter = filterNoAux;
481     }
482     return ignoreAuxiliary ? _compatibleNoAuxHypFilter : _compatibleAllHypFilter;
483   }
484   return 0;
485 }
486
487 //================================================================================
488 /*!
489  * \brief Return continuity of two edges
490  * \param E1 - the 1st edge
491  * \param E2 - the 2nd edge
492  * \retval GeomAbs_Shape - regularity at the junction between E1 and E2
493  */
494 //================================================================================
495
496 GeomAbs_Shape SMESH_Algo::Continuity(const TopoDS_Edge& theE1,
497                                      const TopoDS_Edge& theE2)
498 {
499   // avoid pb with internal edges
500   TopoDS_Edge E1 = theE1, E2 = theE2;
501   if (E1.Orientation() > TopAbs_REVERSED) // INTERNAL
502     E1.Orientation( TopAbs_FORWARD );
503   if (E2.Orientation() > TopAbs_REVERSED) // INTERNAL
504     E2.Orientation( TopAbs_FORWARD );
505
506   TopoDS_Vertex V, VV1[2], VV2[2];
507   TopExp::Vertices( E1, VV1[0], VV1[1], true );
508   TopExp::Vertices( E2, VV2[0], VV2[1], true );
509   if      ( VV1[1].IsSame( VV2[0] ))  { V = VV1[1]; }
510   else if ( VV1[0].IsSame( VV2[1] ))  { V = VV1[0]; }
511   else if ( VV1[1].IsSame( VV2[1] ))  { V = VV1[1]; E1.Reverse(); }
512   else if ( VV1[0].IsSame( VV2[0] ))  { V = VV1[0]; E1.Reverse(); }
513   else { return GeomAbs_C0; }
514
515   Standard_Real u1 = BRep_Tool::Parameter( V, E1 );
516   Standard_Real u2 = BRep_Tool::Parameter( V, E2 );
517   BRepAdaptor_Curve C1( E1 ), C2( E2 );
518   Standard_Real tol = BRep_Tool::Tolerance( V );
519   Standard_Real angTol = 2e-3;
520   try {
521     OCC_CATCH_SIGNALS;
522     return BRepLProp::Continuity(C1, C2, u1, u2, tol, angTol);
523   }
524   catch (Standard_Failure&) {
525   }
526   return GeomAbs_C0;
527 }
528
529 //================================================================================
530 /*!
531  * \brief Return true if an edge can be considered straight
532  */
533 //================================================================================
534
535 bool SMESH_Algo::IsStraight( const TopoDS_Edge & E,
536                              const bool          degenResult)
537 {
538   {
539     double f,l;
540     if ( BRep_Tool::Curve( E, f, l ).IsNull())
541       return degenResult;
542   }
543   BRepAdaptor_Curve curve( E );
544   switch( curve.GetType() )
545   {
546   case GeomAbs_Line:
547     return true;
548   case GeomAbs_Circle:
549   case GeomAbs_Ellipse:
550   case GeomAbs_Hyperbola:
551   case GeomAbs_Parabola:
552     return false;
553     // case GeomAbs_BezierCurve:
554     // case GeomAbs_BSplineCurve:
555     // case GeomAbs_OtherCurve:
556   default:;
557   }
558
559   // evaluate how far from a straight line connecting the curve ends
560   // stand internal points of the curve
561   double  f = curve.FirstParameter();
562   double  l = curve.LastParameter();
563   gp_Pnt pf = curve.Value( f );
564   gp_Pnt pl = curve.Value( l );
565   gp_Vec lineVec( pf, pl );
566   double lineLen2 = lineVec.SquareMagnitude();
567   if ( lineLen2 < std::numeric_limits< double >::min() )
568     return false; // E seems closed
569
570   double edgeTol = 10 * curve.Tolerance();
571   double lenTol2 = lineLen2 * 1e-4;
572   double tol2 = Min( edgeTol * edgeTol, lenTol2 );
573
574   const double nbSamples = 7;
575   for ( int i = 0; i < nbSamples; ++i )
576   {
577     double  r = ( i + 1 ) / nbSamples;
578     gp_Pnt pi = curve.Value( f * r + l * ( 1 - r ));
579     gp_Vec vi( pf, pi );
580     double h2 = lineVec.Crossed( vi ).SquareMagnitude() / lineLen2;
581     if ( h2 > tol2 )
582       return false;
583   }
584   return true;
585 }
586
587 //================================================================================
588 /*!
589  * \brief Return true if an edge has no 3D curve
590  */
591 //================================================================================
592
593 bool SMESH_Algo::isDegenerated( const TopoDS_Edge & E, const bool checkLength )
594 {
595   if ( checkLength )
596     return EdgeLength( E ) == 0;
597   double f,l;
598   TopLoc_Location loc;
599   Handle(Geom_Curve) C = BRep_Tool::Curve( E, loc, f,l );
600   return C.IsNull();
601 }
602
603 //================================================================================
604 /*!
605  * \brief Return the node built on a vertex
606  * \param V - the vertex
607  * \param meshDS - mesh
608  * \retval const SMDS_MeshNode* - found node or NULL
609  * \sa SMESH_MesherHelper::GetSubShapeByNode( const SMDS_MeshNode*, SMESHDS_Mesh* )
610  */
611 //================================================================================
612
613 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
614                                             const SMESHDS_Mesh*  meshDS)
615 {
616   if ( SMESHDS_SubMesh* sm = meshDS->MeshElements(V) ) {
617     SMDS_NodeIteratorPtr nIt= sm->GetNodes();
618     if (nIt->more())
619       return nIt->next();
620   }
621   return 0;
622 }
623
624 //=======================================================================
625 /*!
626  * \brief Return the node built on a vertex.
627  *        A node moved to other geometry by MergeNodes() is also returned.
628  * \param V - the vertex
629  * \param mesh - mesh
630  * \retval const SMDS_MeshNode* - found node or NULL
631  */
632 //=======================================================================
633
634 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex& V,
635                                             const SMESH_Mesh*    mesh)
636 {
637   const SMDS_MeshNode* node = VertexNode( V, mesh->GetMeshDS() );
638
639   if ( !node && mesh->HasModificationsToDiscard() )
640   {
641     PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( V, *mesh, TopAbs_EDGE );
642     while ( const TopoDS_Shape* edge = edgeIt->next() )
643       if ( SMESHDS_SubMesh* edgeSM = mesh->GetMeshDS()->MeshElements( *edge ))
644         if ( edgeSM->NbElements() > 0 )
645           return VertexNode( V, edgeSM, mesh, /*checkV=*/false );
646   }
647   return node;
648 }
649
650 //=======================================================================
651 /*!
652  * \brief Return the node built on a vertex.
653  *        A node moved to other geometry by MergeNodes() is also returned.
654  * \param V - the vertex
655  * \param edgeSM - sub-mesh of a meshed EDGE sharing the vertex
656  * \param checkV - if \c true, presence of a node on the vertex is checked
657  * \retval const SMDS_MeshNode* - found node or NULL
658  */
659 //=======================================================================
660
661 const SMDS_MeshNode* SMESH_Algo::VertexNode(const TopoDS_Vertex&   V,
662                                             const SMESHDS_SubMesh* edgeSM,
663                                             const SMESH_Mesh*      mesh,
664                                             const bool             checkV)
665 {
666   const SMDS_MeshNode* node = checkV ? VertexNode( V, edgeSM->GetParent() ) : 0;
667
668   if ( !node && edgeSM )
669   {
670     // find nodes not shared by mesh segments
671     typedef set< const SMDS_MeshNode* >                       TNodeSet;
672     typedef map< const SMDS_MeshNode*, const SMDS_MeshNode* > TNodeMap;
673     TNodeMap notSharedNodes;
674     TNodeSet otherShapeNodes;
675     vector< const SMDS_MeshNode* > segNodes(3);
676     SMDS_ElemIteratorPtr segIt = edgeSM->GetElements();
677     while ( segIt->more() )
678     {
679       const SMDS_MeshElement* seg = segIt->next();
680       if ( seg->GetType() != SMDSAbs_Edge )
681         return node;
682       segNodes.assign( seg->begin_nodes(), seg->end_nodes() );
683       for ( int i = 0; i < 2; ++i )
684       {
685         const SMDS_MeshNode* n1 = segNodes[i];
686         const SMDS_MeshNode* n2 = segNodes[1-i];
687         pair<TNodeMap::iterator, bool> it2new = notSharedNodes.insert( make_pair( n1, n2 ));
688         if ( !it2new.second ) // n encounters twice
689           notSharedNodes.erase( it2new.first );
690         if ( n1->getshapeId() != edgeSM->GetID() )
691           otherShapeNodes.insert( n1 );
692       }
693     }
694     if ( otherShapeNodes.size() == 1 && notSharedNodes.empty() ) // a closed EDGE
695       return *otherShapeNodes.begin();
696
697     if ( notSharedNodes.size() == 2 ) // two end nodes found
698     {
699       SMESHDS_Mesh*  meshDS = edgeSM->GetParent();
700       const TopoDS_Shape& E = meshDS->IndexToShape( edgeSM->GetID() );
701       if ( E.IsNull() || E.ShapeType() != TopAbs_EDGE )
702         return node;
703       const SMDS_MeshNode* n1 = notSharedNodes.begin ()->first;
704       const SMDS_MeshNode* n2 = notSharedNodes.rbegin()->first;
705       TopoDS_Shape S1 = SMESH_MesherHelper::GetSubShapeByNode( n1, meshDS );
706       if ( S1.ShapeType() == TopAbs_VERTEX && SMESH_MesherHelper::IsSubShape( S1, E ))
707         return n2;
708       TopoDS_Shape S2 = SMESH_MesherHelper::GetSubShapeByNode( n2, meshDS );
709       if ( S2.ShapeType() == TopAbs_VERTEX && SMESH_MesherHelper::IsSubShape( S2, E ))
710         return n1;
711       if ( edgeSM->NbElements() <= 2 || !mesh ) // one-two segments
712       {
713         gp_Pnt pV = BRep_Tool::Pnt( V );
714         double dist1 = pV.SquareDistance( SMESH_TNodeXYZ( n1 ));
715         double dist2 = pV.SquareDistance( SMESH_TNodeXYZ( n2 ));
716         return dist1 < dist2 ? n1 : n2;
717       }
718       if ( mesh )
719       {
720         SMESH_MesherHelper helper( const_cast<SMESH_Mesh&>( *mesh ));
721         const SMDS_MeshNode* n1i = notSharedNodes.begin ()->second;
722         const SMDS_MeshNode* n2i = notSharedNodes.rbegin()->second;
723         const TopoDS_Edge&  edge = TopoDS::Edge( E );
724         bool  posOK = true;
725         double pos1 = helper.GetNodeU( edge, n1i, n2i, &posOK );
726         double pos2 = helper.GetNodeU( edge, n2i, n1i, &posOK );
727         double posV = BRep_Tool::Parameter( V, edge );
728         if ( Abs( pos1 - posV ) < Abs( pos2 - posV )) return n1;
729         else                                          return n2;
730       }
731     }
732   }
733   return node;
734 }
735
736 //=======================================================================
737 //function : GetMeshError
738 //purpose  : Finds topological errors of a sub-mesh
739 //WARNING  : 1D check is NOT implemented so far
740 //=======================================================================
741
742 SMESH_Algo::EMeshError SMESH_Algo::GetMeshError(SMESH_subMesh* subMesh)
743 {
744   EMeshError err = MEr_OK;
745
746   SMESHDS_SubMesh* smDS = subMesh->GetSubMeshDS();
747   if ( !smDS )
748     return MEr_EMPTY;
749
750   switch ( subMesh->GetSubShape().ShapeType() )
751   {
752   case TopAbs_FACE: { // ====================== 2D =====================
753
754     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
755     if ( !fIt->more() )
756       return MEr_EMPTY;
757
758     // We check that only links on EDGEs encounter once, the rest links, twice
759     set< SMESH_TLink > links;
760     while ( fIt->more() )
761     {
762       const SMDS_MeshElement* f = fIt->next();
763       int nbNodes = f->NbCornerNodes(); // ignore medium nodes
764       for ( int i = 0; i < nbNodes; ++i )
765       {
766         const SMDS_MeshNode* n1 = f->GetNode( i );
767         const SMDS_MeshNode* n2 = f->GetNode(( i+1 ) % nbNodes);
768         std::pair< set< SMESH_TLink >::iterator, bool > it_added =
769           links.insert( SMESH_TLink( n1, n2 ));
770         if ( !it_added.second )
771           // As we do NOT(!) check if mesh is manifold, we believe that a link can
772           // encounter once or twice only (not three times), we erase a link as soon
773           // as it encounters twice to speed up search in the <links> map.
774           links.erase( it_added.first );
775       }
776     }
777     // the links remaining in the <links> should all be on EDGE
778     set< SMESH_TLink >::iterator linkIt = links.begin();
779     for ( ; linkIt != links.end(); ++linkIt )
780     {
781       const SMESH_TLink& link = *linkIt;
782       if ( link.node1()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE ||
783            link.node2()->GetPosition()->GetTypeOfPosition() > SMDS_TOP_EDGE )
784         return MEr_HOLES;
785     }
786     // TODO: to check orientation
787     break;
788   }
789   case TopAbs_SOLID: { // ====================== 3D =====================
790
791     SMDS_ElemIteratorPtr vIt = smDS->GetElements();
792     if ( !vIt->more() )
793       return MEr_EMPTY;
794
795     SMDS_VolumeTool vTool;
796     while ( !vIt->more() )
797     {
798       if (!vTool.Set( vIt->next() ))
799         continue; // strange
800
801       for ( int iF = 0; iF < vTool.NbFaces(); ++iF )
802         if ( vTool.IsFreeFace( iF ))
803         {
804           int nbN = vTool.NbFaceNodes( iF );
805           const SMDS_MeshNode** nodes =  vTool.GetFaceNodes( iF );
806           for ( int i = 0; i < nbN; ++i )
807             if ( nodes[i]->GetPosition()->GetTypeOfPosition() > SMDS_TOP_FACE )
808               return MEr_HOLES;
809         }
810     }
811     break;
812   }
813   default:;
814   }
815   return err;
816 }
817
818 //================================================================================
819 /*!
820  * \brief Sets event listener to submeshes if necessary
821  * \param subMesh - submesh where algo is set
822  *
823  * After being set, event listener is notified on each event of a submesh.
824  * By default non listener is set
825  */
826 //================================================================================
827
828 void SMESH_Algo::SetEventListener(SMESH_subMesh* /*subMesh*/)
829 {
830 }
831
832 //================================================================================
833 /*!
834  * \brief Allow algo to do something after persistent restoration
835  * \param subMesh - restored submesh
836  *
837  * This method is called only if a submesh has HYP_OK algo_state.
838  */
839 //================================================================================
840
841 void SMESH_Algo::SubmeshRestored(SMESH_subMesh* /*subMesh*/)
842 {
843 }
844
845 //================================================================================
846 /*!
847  * \brief Computes mesh without geometry
848  * \param aMesh - the mesh
849  * \param aHelper - helper that must be used for adding elements to \aaMesh
850  * \retval bool - is a success
851  */
852 //================================================================================
853
854 bool SMESH_Algo::Compute(SMESH_Mesh & /*aMesh*/, SMESH_MesherHelper* /*aHelper*/)
855 {
856   return error( COMPERR_BAD_INPUT_MESH, "Mesh built on shape expected");
857 }
858
859 //=======================================================================
860 //function : IsApplicableToShape
861 //purpose  : Return true if the algorithm can mesh a given shape
862 //=======================================================================
863
864 bool SMESH_Algo::IsApplicableToShape(const TopoDS_Shape & /*shape*/, bool /*toCheckAll*/) const
865 {
866   return true;
867 }
868
869 //=======================================================================
870 //function : CancelCompute
871 //purpose  : Sets _computeCanceled to true. It's usage depends on
872 //  *        implementation of a particular mesher.
873 //=======================================================================
874
875 void SMESH_Algo::CancelCompute()
876 {
877   _computeCanceled = true;
878   _error = COMPERR_CANCELED;
879 }
880
881 //================================================================================
882 /*
883  * If possible, returns progress of computation [0.,1.]
884  */
885 //================================================================================
886
887 double SMESH_Algo::GetProgress() const
888 {
889   return _progress;
890 }
891
892 //================================================================================
893 /*!
894  * \brief store error and comment and then return ( error == COMPERR_OK )
895  */
896 //================================================================================
897
898 bool SMESH_Algo::error(int error, const SMESH_Comment& comment)
899 {
900   _error   = error;
901   _comment = comment;
902   return ( error == COMPERR_OK );
903 }
904
905 //================================================================================
906 /*!
907  * \brief store error and return ( error == COMPERR_OK )
908  */
909 //================================================================================
910
911 bool SMESH_Algo::error(SMESH_ComputeErrorPtr error)
912 {
913   if ( error ) {
914     _error   = error->myName;
915     _comment = error->myComment;
916     if ( error->HasBadElems() )
917     {
918       SMESH_BadInputElements* badElems = static_cast<SMESH_BadInputElements*>( error.get() );
919       _badInputElements = badElems->GetElements();
920       _mesh             = badElems->GetMesh();
921     }
922     return error->IsOK();
923   }
924   return true;
925 }
926
927 //================================================================================
928 /*!
929  * \brief return compute error
930  */
931 //================================================================================
932
933 SMESH_ComputeErrorPtr SMESH_Algo::GetComputeError() const
934 {
935   if ( !_badInputElements.empty() && _mesh )
936   {
937     SMESH_BadInputElements* err = new SMESH_BadInputElements( _mesh, _error, _comment, this );
938     // hope this method is called by only SMESH_subMesh after this->Compute()
939     err->myBadElements.splice( err->myBadElements.end(),
940                                (list<const SMDS_MeshElement*>&) _badInputElements );
941     return SMESH_ComputeErrorPtr( err );
942   }
943   return SMESH_ComputeError::New( _error, _comment, this );
944 }
945
946 //================================================================================
947 /*!
948  * \brief initialize compute error before call of Compute()
949  */
950 //================================================================================
951
952 void SMESH_Algo::InitComputeError()
953 {
954   _error = COMPERR_OK;
955   _comment.clear();
956   for ( const SMDS_MeshElement* & elem : _badInputElements )
957     if ( !elem->IsNull() && elem->GetID() < 1 )
958       delete elem;
959   _badInputElements.clear();
960   _mesh = 0;
961
962   _computeCanceled = false;
963   _progressTic     = 0;
964   _progress        = 0.;
965 }
966
967 //================================================================================
968 /*!
969  * \brief Return compute progress by nb of calls of this method
970  */
971 //================================================================================
972
973 double SMESH_Algo::GetProgressByTic() const
974 {
975   int computeCost = 0;
976   for ( size_t i = 0; i < _smToCompute.size(); ++i )
977     computeCost += _smToCompute[i]->GetComputeCost();
978
979   const_cast<SMESH_Algo*>( this )->_progressTic++;
980
981   double x = 5 * _progressTic;
982   x = ( x < computeCost ) ? ( x / computeCost ) : 1.;
983   return 0.9 * sin( x * M_PI / 2 );
984 }
985
986 //================================================================================
987 /*!
988  * \brief store a bad input element preventing computation,
989  *        which may be a temporary one i.e. not residing the mesh,
990  *        then it will be deleted by InitComputeError()
991  */
992 //================================================================================
993
994 void SMESH_Algo::addBadInputElement(const SMDS_MeshElement* elem)
995 {
996   if ( elem )
997     _badInputElements.push_back( elem );
998 }
999
1000 //=======================================================================
1001 //function : addBadInputElements
1002 //purpose  : store a bad input elements or nodes preventing computation
1003 //=======================================================================
1004
1005 void SMESH_Algo::addBadInputElements(const SMESHDS_SubMesh* sm,
1006                                      const bool             addNodes)
1007 {
1008   if ( sm )
1009   {
1010     if ( addNodes )
1011     {
1012       SMDS_NodeIteratorPtr nIt = sm->GetNodes();
1013       while ( nIt->more() ) addBadInputElement( nIt->next() );
1014     }
1015     else
1016     {
1017       SMDS_ElemIteratorPtr eIt = sm->GetElements();
1018       while ( eIt->more() ) addBadInputElement( eIt->next() );
1019     }
1020     _mesh = sm->GetParent();
1021   }
1022 }
1023
1024 //=============================================================================
1025 /*!
1026  *
1027  */
1028 //=============================================================================
1029
1030 // int SMESH_Algo::NumberOfWires(const TopoDS_Shape& S)
1031 // {
1032 //   int i = 0;
1033 //   for (TopExp_Explorer exp(S,TopAbs_WIRE); exp.More(); exp.Next())
1034 //     i++;
1035 //   return i;
1036 // }
1037
1038 //=============================================================================
1039 /*!
1040  *
1041  */
1042 //=============================================================================
1043
1044 smIdType SMESH_Algo::NumberOfPoints(SMESH_Mesh& aMesh, const TopoDS_Wire& W)
1045 {
1046   smIdType nbPoints = 0;
1047   for (TopExp_Explorer exp(W,TopAbs_EDGE); exp.More(); exp.Next()) {
1048     const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1049     smIdType nb = aMesh.GetSubMesh(E)->GetSubMeshDS()->NbNodes();
1050     if(_quadraticMesh)
1051       nb = nb/2;
1052     nbPoints += nb + 1; // internal points plus 1 vertex of 2 (last point ?)
1053   }
1054   return nbPoints;
1055 }
1056
1057
1058 //================================================================================
1059 /*!
1060  * Method in which an algorithm generating a structured mesh
1061  * fixes positions of in-face nodes after there movement
1062  * due to insertion of viscous layers.
1063  */
1064 //================================================================================
1065
1066 bool SMESH_2D_Algo::FixInternalNodes(const SMESH_ProxyMesh& mesh,
1067                                      const TopoDS_Face&     face)
1068 {
1069   const SMESHDS_SubMesh* smDS = mesh.GetSubMesh(face);
1070   if ( !smDS || smDS->NbElements() < 1 )
1071     return false;
1072
1073   SMESH_MesherHelper helper( *mesh.GetMesh() );
1074   helper.SetSubShape( face );
1075
1076   // get all faces from a proxy sub-mesh
1077   typedef SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > TIterator;
1078   TIDSortedElemSet allFaces( TIterator( smDS->GetElements() ), TIterator() );
1079   TIDSortedElemSet avoidSet, firstRowQuads;
1080
1081   // indices of nodes to pass to a neighbour quad using SMESH_MeshAlgos::FindFaceInSet()
1082   int iN1, iN2;
1083
1084   // get two first rows of nodes by passing through the first row of faces
1085   vector< vector< const SMDS_MeshNode* > > nodeRows;
1086   int iRow1 = 0, iRow2 = 1;
1087   const SMDS_MeshElement* quad;
1088   {
1089     // look for a corner quadrangle and it's corner node
1090     const SMDS_MeshElement* cornerQuad = 0;
1091     int                     cornerNodeInd = -1;
1092     SMDS_ElemIteratorPtr fIt = smDS->GetElements();
1093     while ( !cornerQuad && fIt->more() )
1094     {
1095       cornerQuad = fIt->next();
1096       if ( cornerQuad->NbCornerNodes() != 4 )
1097         return false;
1098       SMDS_NodeIteratorPtr nIt = cornerQuad->nodeIterator();
1099       for ( int i = 0; i < 4; ++i )
1100       {
1101         int nbInverseQuads = 0;
1102         SMDS_ElemIteratorPtr fIt = nIt->next()->GetInverseElementIterator(SMDSAbs_Face);
1103         while ( fIt->more() )
1104           nbInverseQuads += allFaces.count( fIt->next() );
1105         if ( nbInverseQuads == 1 )
1106           cornerNodeInd = i, i = 4;
1107       }
1108       if ( cornerNodeInd < 0 )
1109         cornerQuad = 0;
1110     }
1111     if ( !cornerQuad || cornerNodeInd < 0 )
1112       return false;
1113
1114     iN1     = helper.WrapIndex( cornerNodeInd + 1, 4 );
1115     iN2     = helper.WrapIndex( cornerNodeInd + 2, 4 );
1116     int iN3 = helper.WrapIndex( cornerNodeInd + 3, 4 );
1117     nodeRows.resize(2);
1118     nodeRows[iRow1].push_back( cornerQuad->GetNode( cornerNodeInd ));
1119     nodeRows[iRow1].push_back( cornerQuad->GetNode( iN1 ));
1120     nodeRows[iRow2].push_back( cornerQuad->GetNode( iN3 ));
1121     nodeRows[iRow2].push_back( cornerQuad->GetNode( iN2 ));
1122     firstRowQuads.insert( cornerQuad );
1123
1124     // pass through the rest quads in a face row
1125     quad = cornerQuad;
1126     while ( quad )
1127     {
1128       avoidSet.clear();
1129       avoidSet.insert( quad );
1130       if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1].back(),
1131                                                    nodeRows[iRow2].back(),
1132                                                    allFaces, avoidSet, &iN1, &iN2)))
1133       {
1134         nodeRows[iRow1].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1135         nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1136         if ( quad->NbCornerNodes() != 4 )
1137           return false;
1138       }
1139     }
1140     if ( nodeRows[iRow1].size() < 3 )
1141       return true; // there is nothing to fix
1142   }
1143
1144   nodeRows.reserve( smDS->NbElements() / nodeRows[iRow1].size() );
1145
1146   // get the rest node rows
1147   while ( true )
1148   {
1149     ++iRow1, ++iRow2;
1150
1151     // get the first quad in the next face row
1152     if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][0],
1153                                                  nodeRows[iRow1][1],
1154                                                  allFaces, /*avoid=*/firstRowQuads,
1155                                                  &iN1, &iN2)))
1156     {
1157       if ( quad->NbCornerNodes() != 4 )
1158         return false;
1159       nodeRows.resize( iRow2+1 );
1160       nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN2 + 2, 4 )));
1161       nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1162       firstRowQuads.insert( quad );
1163     }
1164     else
1165     {
1166       break; // no more rows
1167     }
1168
1169     // pass through the rest quads in a face row
1170     while ( quad )
1171     {
1172       avoidSet.clear();
1173       avoidSet.insert( quad );
1174       if (( quad = SMESH_MeshAlgos::FindFaceInSet( nodeRows[iRow1][ nodeRows[iRow2].size()-1 ],
1175                                                    nodeRows[iRow2].back(),
1176                                                    allFaces, avoidSet, &iN1, &iN2)))
1177       {
1178         if ( quad->NbCornerNodes() != 4 )
1179           return false;
1180         nodeRows[iRow2].push_back( quad->GetNode( helper.WrapIndex( iN1 + 2, 4 )));
1181       }
1182     }
1183     if ( nodeRows[iRow1].size() != nodeRows[iRow2].size() )
1184       return false;
1185   }
1186   if ( nodeRows.size() < 3 )
1187     return true; // there is nothing to fix
1188
1189   // get params of the first (bottom) and last (top) node rows
1190   UVPtStructVec uvB( nodeRows[0].size() ), uvT( nodeRows[0].size() );
1191   bool uvOk = false, *toCheck = helper.GetPeriodicIndex() ? &uvOk : nullptr;
1192   const bool isFix3D = helper.HasDegeneratedEdges();
1193   for ( int isBot = 0; isBot < 2; ++isBot )
1194   {
1195     iRow1 = isBot ? 0 : nodeRows.size()-1;
1196     iRow2 = isBot ? 1 : nodeRows.size()-2;
1197     UVPtStructVec &                  uvps = isBot ? uvB : uvT;
1198     vector< const SMDS_MeshNode* >& nodes = nodeRows[ iRow1 ];
1199     const size_t rowLen = nodes.size();
1200     for ( size_t i = 0; i < rowLen; ++i )
1201     {
1202       uvps[i].node = nodes[i];
1203       uvps[i].x = 0;
1204       if ( !isFix3D )
1205       {
1206         size_t i2 = i;
1207         if ( i == 0          ) i2 = 1;
1208         if ( i == rowLen - 1 ) i2 = rowLen - 2;
1209         gp_XY uv = helper.GetNodeUV( face, uvps[i].node, nodeRows[iRow2][i2], toCheck );
1210         uvps[i].u = uv.Coord(1);
1211         uvps[i].v = uv.Coord(2);
1212       }
1213     }
1214     // calculate x (normalized param)
1215     for ( size_t i = 1; i < nodes.size(); ++i )
1216       uvps[i].x = uvps[i-1].x + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1217     for ( size_t i = 1; i < nodes.size(); ++i )
1218       uvps[i].x /= uvps.back().x;
1219   }
1220
1221   // get params of the left and right node rows
1222   UVPtStructVec uvL( nodeRows.size() ), uvR( nodeRows.size() );
1223   for ( int isLeft = 0; isLeft < 2; ++isLeft )
1224   {
1225     UVPtStructVec &  uvps = isLeft ? uvL : uvR;
1226     const int       iCol1 = isLeft ? 0 : nodeRows[0].size() - 1;
1227     const int       iCol2 = isLeft ? 1 : nodeRows[0].size() - 2;
1228     const size_t   nbRows = nodeRows.size();
1229     for ( size_t i = 0; i < nbRows; ++i )
1230     {
1231       uvps[i].node = nodeRows[i][iCol1];
1232       uvps[i].y = 0;
1233       if ( !isFix3D )
1234       {
1235         size_t i2 = i;
1236         if ( i == 0          ) i2 = 1;
1237         if ( i == nbRows - 1 ) i2 = nbRows - 2;
1238         gp_XY uv = helper.GetNodeUV( face, uvps[i].node, nodeRows[i2][iCol2], toCheck );
1239         uvps[i].u = uv.Coord(1);
1240         uvps[i].v = uv.Coord(2);
1241       }
1242     }
1243     // calculate y (normalized param)
1244     for ( size_t i = 1; i < nodeRows.size(); ++i )
1245       uvps[i].y = uvps[i-1].y + SMESH_TNodeXYZ( uvps[i-1].node ).Distance( uvps[i].node );
1246     for ( size_t i = 1; i < nodeRows.size(); ++i )
1247       uvps[i].y /= uvps.back().y;
1248   }
1249
1250   // update node coordinates
1251   SMESHDS_Mesh*   meshDS = mesh.GetMeshDS();
1252   if ( !isFix3D )
1253   {
1254     Handle(Geom_Surface) S = BRep_Tool::Surface( face );
1255     gp_XY a0 ( uvB.front().u, uvB.front().v );
1256     gp_XY a1 ( uvB.back().u,  uvB.back().v );
1257     gp_XY a2 ( uvT.back().u,  uvT.back().v );
1258     gp_XY a3 ( uvT.front().u, uvT.front().v );
1259     for ( size_t iRow = 1; iRow < nodeRows.size()-1; ++iRow )
1260     {
1261       gp_XY p1 ( uvR[ iRow ].u, uvR[ iRow ].v );
1262       gp_XY p3 ( uvL[ iRow ].u, uvL[ iRow ].v );
1263       const double y0 = uvL[ iRow ].y;
1264       const double y1 = uvR[ iRow ].y;
1265       for ( size_t iCol = 1; iCol < nodeRows[0].size()-1; ++iCol )
1266       {
1267         gp_XY p0 ( uvB[ iCol ].u, uvB[ iCol ].v );
1268         gp_XY p2 ( uvT[ iCol ].u, uvT[ iCol ].v );
1269         const double x0 = uvB[ iCol ].x;
1270         const double x1 = uvT[ iCol ].x;
1271         double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1272         double y = y0 + x * (y1 - y0);
1273         gp_XY uv = helper.calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
1274         gp_Pnt p = S->Value( uv.Coord(1), uv.Coord(2));
1275         const SMDS_MeshNode* n = nodeRows[iRow][iCol];
1276         meshDS->MoveNode( n, p.X(), p.Y(), p.Z() );
1277         if ( SMDS_FacePositionPtr pos = n->GetPosition() )
1278           pos->SetParameters( uv.Coord(1), uv.Coord(2) );
1279       }
1280     }
1281   }
1282   else
1283   {
1284     Handle(ShapeAnalysis_Surface) S = helper.GetSurface( face );
1285     SMESH_NodeXYZ a0 ( uvB.front().node );
1286     SMESH_NodeXYZ a1 ( uvB.back().node );
1287     SMESH_NodeXYZ a2 ( uvT.back().node );
1288     SMESH_NodeXYZ a3 ( uvT.front().node );
1289     for ( size_t iRow = 1; iRow < nodeRows.size()-1; ++iRow )
1290     {
1291       SMESH_NodeXYZ p1 ( uvR[ iRow ].node );
1292       SMESH_NodeXYZ p3 ( uvL[ iRow ].node );
1293       const double y0 = uvL[ iRow ].y;
1294       const double y1 = uvR[ iRow ].y;
1295       for ( size_t iCol = 1; iCol < nodeRows[0].size()-1; ++iCol )
1296       {
1297         SMESH_NodeXYZ p0 ( uvB[ iCol ].node );
1298         SMESH_NodeXYZ p2 ( uvT[ iCol ].node );
1299         const double x0 = uvB[ iCol ].x;
1300         const double x1 = uvT[ iCol ].x;
1301         double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1302         double y = y0 + x * (y1 - y0);
1303         gp_Pnt p = helper.calcTFI( x, y, a0,a1,a2,a3, p0,p1,p2,p3 );
1304         gp_Pnt2d uv = S->ValueOfUV( p, Precision::Confusion() );
1305         p = S->Value( uv );
1306         const SMDS_MeshNode* n = nodeRows[iRow][iCol];
1307         meshDS->MoveNode( n, p.X(), p.Y(), p.Z() );
1308         if ( SMDS_FacePositionPtr pos = n->GetPosition() )
1309           pos->SetParameters( uv.Coord(1), uv.Coord(2) );
1310       }
1311     }
1312   }
1313   return true;
1314 }
1315
1316 //=======================================================================
1317 //function : IsApplicableToShape
1318 //purpose  : Return true if the algorithm can mesh a given shape
1319 //=======================================================================
1320
1321 bool SMESH_1D_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool /*toCheckAll*/) const
1322 {
1323   return ( !shape.IsNull() && TopExp_Explorer( shape, TopAbs_EDGE ).More() );
1324 }
1325
1326 //=======================================================================
1327 //function : IsApplicableToShape
1328 //purpose  : Return true if the algorithm can mesh a given shape
1329 //=======================================================================
1330
1331 bool SMESH_2D_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool /*toCheckAll*/) const
1332 {
1333   return ( !shape.IsNull() && TopExp_Explorer( shape, TopAbs_FACE ).More() );
1334 }
1335
1336 //=======================================================================
1337 //function : IsApplicableToShape
1338 //purpose  : Return true if the algorithm can mesh a given shape
1339 //=======================================================================
1340
1341 bool SMESH_3D_Algo::IsApplicableToShape(const TopoDS_Shape & shape, bool /*toCheckAll*/) const
1342 {
1343   return ( !shape.IsNull() && TopExp_Explorer( shape, TopAbs_SOLID ).More() );
1344 }