Salome HOME
SALOME_TESTS/Grids/smesh/bugs_07/H5
[modules/smesh.git] / src / StdMeshers / StdMeshers_Quadrangle_2D.cxx
1 // Copyright (C) 2007-2014  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 //  File   : StdMeshers_Quadrangle_2D.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26
27 #include "StdMeshers_Quadrangle_2D.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshNode.hxx"
33 #include "SMESH_Block.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_HypoFilter.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MeshAlgos.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_subMesh.hxx"
41 #include "StdMeshers_FaceSide.hxx"
42 #include "StdMeshers_QuadrangleParams.hxx"
43 #include "StdMeshers_ViscousLayers2D.hxx"
44
45 #include <BRepBndLib.hxx>
46 #include <BRepClass_FaceClassifier.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_Box.hxx>
49 #include <GeomAPI_ProjectPointOnSurf.hxx>
50 #include <Geom_Surface.hxx>
51 #include <NCollection_DefineArray2.hxx>
52 #include <Precision.hxx>
53 #include <Quantity_Parameter.hxx>
54 #include <TColStd_SequenceOfInteger.hxx>
55 #include <TColStd_SequenceOfReal.hxx>
56 #include <TColgp_SequenceOfXY.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_DataMapOfShapeReal.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
62 #include <TopoDS.hxx>
63
64 #include "utilities.h"
65 #include "Utils_ExceptHandlers.hxx"
66
67 #ifndef StdMeshers_Array2OfNode_HeaderFile
68 #define StdMeshers_Array2OfNode_HeaderFile
69 typedef const SMDS_MeshNode* SMDS_MeshNodePtr;
70 DEFINE_BASECOLLECTION (StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
71 DEFINE_ARRAY2(StdMeshers_Array2OfNode,
72               StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
73 #endif
74
75 using namespace std;
76
77 typedef gp_XY gp_UV;
78 typedef SMESH_Comment TComm;
79
80 //=============================================================================
81 /*!
82  *
83  */
84 //=============================================================================
85
86 StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D (int hypId, int studyId,
87                                                     SMESH_Gen* gen)
88   : SMESH_2D_Algo(hypId, studyId, gen),
89     myQuadranglePreference(false),
90     myTrianglePreference(false),
91     myTriaVertexID(-1),
92     myNeedSmooth(false),
93     myCheckOri(false),
94     myParams( NULL ),
95     myQuadType(QUAD_STANDARD),
96     myHelper( NULL )
97 {
98   MESSAGE("StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D");
99   _name = "Quadrangle_2D";
100   _shapeType = (1 << TopAbs_FACE);
101   _compatibleHypothesis.push_back("QuadrangleParams");
102   _compatibleHypothesis.push_back("QuadranglePreference");
103   _compatibleHypothesis.push_back("TrianglePreference");
104   _compatibleHypothesis.push_back("ViscousLayers2D");
105 }
106
107 //=============================================================================
108 /*!
109  *
110  */
111 //=============================================================================
112
113 StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D()
114 {
115   MESSAGE("StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D");
116 }
117
118 //=============================================================================
119 /*!
120  *  
121  */
122 //=============================================================================
123
124 bool StdMeshers_Quadrangle_2D::CheckHypothesis
125                          (SMESH_Mesh&                          aMesh,
126                           const TopoDS_Shape&                  aShape,
127                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
128 {
129   myTriaVertexID         = -1;
130   myQuadType             = QUAD_STANDARD;
131   myQuadranglePreference = false;
132   myTrianglePreference   = false;
133   myHelper               = (SMESH_MesherHelper*)NULL;
134   myParams               = NULL;
135   myQuadList.clear();
136
137   bool isOk = true;
138   aStatus   = SMESH_Hypothesis::HYP_OK;
139
140   const list <const SMESHDS_Hypothesis * >& hyps =
141     GetUsedHypothesis(aMesh, aShape, false);
142   const SMESHDS_Hypothesis * aHyp = 0;
143
144   bool isFirstParams = true;
145
146   // First assigned hypothesis (if any) is processed now
147   if (hyps.size() > 0) {
148     aHyp = hyps.front();
149     if (strcmp("QuadrangleParams", aHyp->GetName()) == 0)
150     {
151       myParams = (const StdMeshers_QuadrangleParams*)aHyp;
152       myTriaVertexID = myParams->GetTriaVertex();
153       myQuadType     = myParams->GetQuadType();
154       if (myQuadType == QUAD_QUADRANGLE_PREF ||
155           myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
156         myQuadranglePreference = true;
157       else if (myQuadType == QUAD_TRIANGLE_PREF)
158         myTrianglePreference = true;
159     }
160     else if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
161       isFirstParams = false;
162       myQuadranglePreference = true;
163     }
164     else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
165       isFirstParams = false;
166       myTrianglePreference = true; 
167     }
168     else {
169       isFirstParams = false;
170     }
171   }
172
173   // Second(last) assigned hypothesis (if any) is processed now
174   if (hyps.size() > 1) {
175     aHyp = hyps.back();
176     if (isFirstParams) {
177       if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
178         myQuadranglePreference = true;
179         myTrianglePreference = false; 
180         myQuadType = QUAD_STANDARD;
181       }
182       else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
183         myQuadranglePreference = false;
184         myTrianglePreference = true; 
185         myQuadType = QUAD_STANDARD;
186       }
187     }
188     else {
189       const StdMeshers_QuadrangleParams* aHyp2 = 
190         (const StdMeshers_QuadrangleParams*)aHyp;
191       myTriaVertexID = aHyp2->GetTriaVertex();
192
193       if (!myQuadranglePreference && !myTrianglePreference) { // priority of hypos
194         myQuadType = aHyp2->GetQuadType();
195         if (myQuadType == QUAD_QUADRANGLE_PREF ||
196             myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
197           myQuadranglePreference = true;
198         else if (myQuadType == QUAD_TRIANGLE_PREF)
199           myTrianglePreference = true;
200       }
201     }
202   }
203
204   return isOk;
205 }
206
207 //=============================================================================
208 /*!
209  *  
210  */
211 //=============================================================================
212
213 bool StdMeshers_Quadrangle_2D::Compute (SMESH_Mesh&         aMesh,
214                                         const TopoDS_Shape& aShape)
215 {
216   const TopoDS_Face& F = TopoDS::Face(aShape);
217   aMesh.GetSubMesh( F );
218
219   // do not initialize my fields before this as StdMeshers_ViscousLayers2D
220   // can call Compute() recursively
221   SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
222   if ( !proxyMesh )
223     return false;
224
225   myProxyMesh = proxyMesh;
226
227   SMESH_MesherHelper helper (aMesh);
228   myHelper = &helper;
229
230   _quadraticMesh = myHelper->IsQuadraticSubMesh(aShape);
231   myNeedSmooth = false;
232   myCheckOri   = false;
233
234   FaceQuadStruct::Ptr quad = CheckNbEdges( aMesh, F, /*considerMesh=*/true );
235   if (!quad)
236     return false;
237   myQuadList.clear();
238   myQuadList.push_back( quad );
239
240   if ( !getEnforcedUV() )
241     return false;
242
243   updateDegenUV( quad );
244
245   int n1 = quad->side[0].NbPoints();
246   int n2 = quad->side[1].NbPoints();
247   int n3 = quad->side[2].NbPoints();
248   int n4 = quad->side[3].NbPoints();
249
250   enum { NOT_COMPUTED = -1, COMPUTE_FAILED = 0, COMPUTE_OK = 1 };
251   int res = NOT_COMPUTED;
252   if (myQuadranglePreference)
253   {
254     int nfull = n1+n2+n3+n4;
255     if ((nfull % 2) == 0 && ((n1 != n3) || (n2 != n4)))
256     {
257       // special path genarating only quandrangle faces
258       res = computeQuadPref( aMesh, F, quad );
259     }
260   }
261   else if (myQuadType == QUAD_REDUCED)
262   {
263     int n13    = n1 - n3;
264     int n24    = n2 - n4;
265     int n13tmp = n13/2; n13tmp = n13tmp*2;
266     int n24tmp = n24/2; n24tmp = n24tmp*2;
267     if ((n1 == n3 && n2 != n4 && n24tmp == n24) ||
268         (n2 == n4 && n1 != n3 && n13tmp == n13))
269     {
270       res = computeReduced( aMesh, F, quad );
271     }
272     else
273     {
274       if ( n1 != n3 && n2 != n4 )
275         error( COMPERR_WARNING,
276                "To use 'Reduced' transition, "
277                "two opposite sides should have same number of segments, "
278                "but actual number of segments is different on all sides. "
279                "'Standard' transion has been used.");
280       else
281         error( COMPERR_WARNING,
282                "To use 'Reduced' transition, "
283                "two opposite sides should have an even difference in number of segments. "
284                "'Standard' transion has been used.");
285     }
286   }
287
288   if ( res == NOT_COMPUTED )
289   {
290     if ( n1 != n3 || n2 != n4 )
291       res = computeTriangles( aMesh, F, quad );
292     else
293       res = computeQuadDominant( aMesh, F );
294   }
295
296   if ( res == COMPUTE_OK && myNeedSmooth )
297     smooth( quad );
298
299   if ( res == COMPUTE_OK )
300     res = check();
301
302   return ( res == COMPUTE_OK );
303 }
304
305 //================================================================================
306 /*!
307  * \brief Compute quadrangles and triangles on the quad
308  */
309 //================================================================================
310
311 bool StdMeshers_Quadrangle_2D::computeTriangles(SMESH_Mesh&         aMesh,
312                                                 const TopoDS_Face&  aFace,
313                                                 FaceQuadStruct::Ptr quad)
314 {
315   int nb = quad->side[0].grid->NbPoints();
316   int nr = quad->side[1].grid->NbPoints();
317   int nt = quad->side[2].grid->NbPoints();
318   int nl = quad->side[3].grid->NbPoints();
319
320   // rotate the quad to have nbNodeOut sides on TOP [and LEFT]
321   if ( nb > nt )
322     quad->shift( nl > nr ? 3 : 2, true );
323   else if ( nr > nl )
324     quad->shift( 1, true );
325   else if ( nl > nr )
326     quad->shift( nt > nb ? 0 : 3, true );
327
328   if ( !setNormalizedGrid( quad ))
329     return false;
330
331   if ( quad->nbNodeOut( QUAD_TOP_SIDE    ))
332   {
333     splitQuad( quad, 0, quad->jSize-2 );
334   }
335   if ( quad->nbNodeOut( QUAD_BOTTOM_SIDE )) // this should not happen
336   {
337     splitQuad( quad, 0, 1 );
338   }
339   FaceQuadStruct::Ptr newQuad = myQuadList.back();
340   if ( quad != newQuad ) // split done
341   {
342     { // update left side limit till where to make triangles
343       FaceQuadStruct::Ptr botQuad = // a bottom part
344         ( quad->side[ QUAD_LEFT_SIDE ].from == 0 ) ? quad : newQuad;
345       if ( botQuad->nbNodeOut( QUAD_LEFT_SIDE ) > 0 )
346         botQuad->side[ QUAD_LEFT_SIDE ].to += botQuad->nbNodeOut( QUAD_LEFT_SIDE );
347       else if ( botQuad->nbNodeOut( QUAD_RIGHT_SIDE ) > 0 )
348         botQuad->side[ QUAD_RIGHT_SIDE ].to += botQuad->nbNodeOut( QUAD_RIGHT_SIDE );
349     }
350     // make quad be a greatest one
351     if ( quad->side[ QUAD_LEFT_SIDE ].NbPoints() == 2 ||
352          quad->side[ QUAD_RIGHT_SIDE ].NbPoints() == 2  )
353       quad = newQuad;
354     if ( !setNormalizedGrid( quad ))
355       return false;
356   }
357
358   if ( quad->nbNodeOut( QUAD_RIGHT_SIDE ))
359   {
360     splitQuad( quad, quad->iSize-2, 0 );
361   }
362   if ( quad->nbNodeOut( QUAD_LEFT_SIDE  ))
363   {
364     splitQuad( quad, 1, 0 );
365
366     if ( quad->nbNodeOut( QUAD_TOP_SIDE ))
367     {
368       newQuad = myQuadList.back();
369       if ( newQuad == quad ) // too narrow to split
370       {
371         // update left side limit till where to make triangles
372         quad->side[ QUAD_LEFT_SIDE ].to--;
373       }
374       else
375       {
376         FaceQuadStruct::Ptr leftQuad =
377           ( quad->side[ QUAD_BOTTOM_SIDE ].from == 0 ) ? quad : newQuad;
378         leftQuad->nbNodeOut( QUAD_TOP_SIDE ) = 0;
379       }
380     }
381   }
382
383   if ( ! computeQuadDominant( aMesh, aFace ))
384     return false;
385
386   // try to fix zero-area triangles near straight-angle corners
387
388   return true;
389 }
390
391 //================================================================================
392 /*!
393  * \brief Compute quadrangles and possibly triangles on all quads of myQuadList
394  */
395 //================================================================================
396
397 bool StdMeshers_Quadrangle_2D::computeQuadDominant(SMESH_Mesh&         aMesh,
398                                                    const TopoDS_Face&  aFace)
399 {
400   if ( !addEnforcedNodes() )
401     return false;
402
403   std::list< FaceQuadStruct::Ptr >::iterator quad = myQuadList.begin();
404   for ( ; quad != myQuadList.end(); ++quad )
405     if ( !computeQuadDominant( aMesh, aFace, *quad ))
406       return false;
407
408   return true;
409 }
410
411 //================================================================================
412 /*!
413  * \brief Compute quadrangles and possibly triangles
414  */
415 //================================================================================
416
417 bool StdMeshers_Quadrangle_2D::computeQuadDominant(SMESH_Mesh&         aMesh,
418                                                    const TopoDS_Face&  aFace,
419                                                    FaceQuadStruct::Ptr quad)
420 {
421   // --- set normalized grid on unit square in parametric domain
422
423   if ( !setNormalizedGrid( quad ))
424     return false;
425
426   // --- create nodes on points, and create quadrangles
427
428   int nbhoriz  = quad->iSize;
429   int nbvertic = quad->jSize;
430
431   // internal mesh nodes
432   SMESHDS_Mesh *  meshDS = aMesh.GetMeshDS();
433   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
434   int i,j,    geomFaceID = meshDS->ShapeToIndex(aFace);
435   for (i = 1; i < nbhoriz - 1; i++)
436     for (j = 1; j < nbvertic - 1; j++)
437     {
438       UVPtStruct& uvPnt = quad->UVPt( i, j );
439       gp_Pnt P          = S->Value( uvPnt.u, uvPnt.v );
440       uvPnt.node        = meshDS->AddNode(P.X(), P.Y(), P.Z());
441       meshDS->SetNodeOnFace( uvPnt.node, geomFaceID, uvPnt.u, uvPnt.v );
442     }
443   
444   // mesh faces
445
446   //             [2]
447   //      --.--.--.--.--.--  nbvertic
448   //     |                 | ^
449   //     |                 | ^
450   // [3] |                 | ^ j  [1]
451   //     |                 | ^
452   //     |                 | ^
453   //      ---.----.----.---  0
454   //     0 > > > > > > > > nbhoriz
455   //              i
456   //             [0]
457   
458   int ilow = 0;
459   int iup = nbhoriz - 1;
460   if (quad->nbNodeOut(3)) { ilow++; } else { if (quad->nbNodeOut(1)) iup--; }
461   
462   int jlow = 0;
463   int jup = nbvertic - 1;
464   if (quad->nbNodeOut(0)) { jlow++; } else { if (quad->nbNodeOut(2)) jup--; }
465   
466   // regular quadrangles
467   for (i = ilow; i < iup; i++) {
468     for (j = jlow; j < jup; j++) {
469       const SMDS_MeshNode *a, *b, *c, *d;
470       a = quad->uv_grid[ j      * nbhoriz + i    ].node;
471       b = quad->uv_grid[ j      * nbhoriz + i + 1].node;
472       c = quad->uv_grid[(j + 1) * nbhoriz + i + 1].node;
473       d = quad->uv_grid[(j + 1) * nbhoriz + i    ].node;
474       SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
475       if (face) {
476         meshDS->SetMeshElementOnShape(face, geomFaceID);
477       }
478     }
479   }
480
481   // Boundary elements (must always be on an outer boundary of the FACE)
482   
483   const vector<UVPtStruct>& uv_e0 = quad->side[0].grid->GetUVPtStruct();
484   const vector<UVPtStruct>& uv_e1 = quad->side[1].grid->GetUVPtStruct();
485   const vector<UVPtStruct>& uv_e2 = quad->side[2].grid->GetUVPtStruct();
486   const vector<UVPtStruct>& uv_e3 = quad->side[3].grid->GetUVPtStruct();
487
488   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
489     return error(COMPERR_BAD_INPUT_MESH);
490
491   double eps = Precision::Confusion();
492
493   int nbdown  = (int) uv_e0.size();
494   int nbup    = (int) uv_e2.size();
495   int nbright = (int) uv_e1.size();
496   int nbleft  = (int) uv_e3.size();
497
498   if (quad->nbNodeOut(0) && nbvertic == 2) // this should not occure
499   {
500     // Down edge is out
501     // 
502     // |___|___|___|___|___|___|
503     // |   |   |   |   |   |   |
504     // |___|___|___|___|___|___|
505     // |   |   |   |   |   |   |
506     // |___|___|___|___|___|___| __ first row of the regular grid
507     // .  .  .  .  .  .  .  .  . __ down edge nodes
508     // 
509     // >->->->->->->->->->->->-> -- direction of processing
510       
511     int g = 0; // number of last processed node in the regular grid
512     
513     // number of last node of the down edge to be processed
514     int stop = nbdown - 1;
515     // if right edge is out, we will stop at a node, previous to the last one
516     //if (quad->nbNodeOut(1)) stop--;
517     if ( quad->nbNodeOut( QUAD_RIGHT_SIDE ))
518       quad->UVPt( nbhoriz-1, 1 ).node = uv_e1[1].node;
519     if ( quad->nbNodeOut( QUAD_LEFT_SIDE ))
520       quad->UVPt( 0, 1 ).node = uv_e3[1].node;
521
522     // for each node of the down edge find nearest node
523     // in the first row of the regular grid and link them
524     for (i = 0; i < stop; i++) {
525       const SMDS_MeshNode *a, *b, *c, *d;
526       a = uv_e0[i].node;
527       b = uv_e0[i + 1].node;
528       gp_Pnt pb (b->X(), b->Y(), b->Z());
529       
530       // find node c in the regular grid, which will be linked with node b
531       int near = g;
532       if (i == stop - 1) {
533         // right bound reached, link with the rightmost node
534         near = iup;
535         c = quad->uv_grid[nbhoriz + iup].node;
536       }
537       else {
538         // find in the grid node c, nearest to the b
539         double mind = RealLast();
540         for (int k = g; k <= iup; k++) {
541           
542           const SMDS_MeshNode *nk;
543           if (k < ilow) // this can be, if left edge is out
544             nk = uv_e3[1].node; // get node from the left edge
545           else
546             nk = quad->uv_grid[nbhoriz + k].node; // get one of middle nodes
547
548           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
549           double dist = pb.Distance(pnk);
550           if (dist < mind - eps) {
551             c = nk;
552             near = k;
553             mind = dist;
554           } else {
555             break;
556           }
557         }
558       }
559
560       if (near == g) { // make triangle
561         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
562         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
563       }
564       else { // make quadrangle
565         if (near - 1 < ilow)
566           d = uv_e3[1].node;
567         else
568           d = quad->uv_grid[nbhoriz + near - 1].node;
569         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
570         
571         if (!myTrianglePreference){
572           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
573           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
574         }
575         else {
576           splitQuadFace(meshDS, geomFaceID, a, b, c, d);
577         }
578
579         // if node d is not at position g - make additional triangles
580         if (near - 1 > g) {
581           for (int k = near - 1; k > g; k--) {
582             c = quad->uv_grid[nbhoriz + k].node;
583             if (k - 1 < ilow)
584               d = uv_e3[1].node;
585             else
586               d = quad->uv_grid[nbhoriz + k - 1].node;
587             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
588             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
589           }
590         }
591         g = near;
592       }
593     }
594   } else {
595     if (quad->nbNodeOut(2) && nbvertic == 2)
596     {
597       // Up edge is out
598       // 
599       // <-<-<-<-<-<-<-<-<-<-<-<-< -- direction of processing
600       // 
601       // .  .  .  .  .  .  .  .  . __ up edge nodes
602       //  ___ ___ ___ ___ ___ ___  __ first row of the regular grid
603       // |   |   |   |   |   |   |
604       // |___|___|___|___|___|___|
605       // |   |   |   |   |   |   |
606       // |___|___|___|___|___|___|
607       // |   |   |   |   |   |   |
608
609       int g = nbhoriz - 1; // last processed node in the regular grid
610
611       ilow = 0;
612       iup = nbhoriz - 1;
613
614       int stop = 0;
615       if ( quad->side[3].grid->Edge(0).IsNull() ) // left side is simulated one
616       {
617         // quad divided at I but not at J, as nbvertic==nbright==2
618         stop++; // we stop at a second node
619       }
620       else
621       {
622         if ( quad->nbNodeOut( QUAD_RIGHT_SIDE ))
623           quad->UVPt( nbhoriz-1, 0 ).node = uv_e1[ nbright-2 ].node;
624         if ( quad->nbNodeOut( QUAD_LEFT_SIDE ))
625           quad->UVPt( 0, 0 ).node = uv_e3[ nbleft-2 ].node;
626
627         if ( nbright > 2 ) // there was a split at J
628           quad->nbNodeOut( QUAD_LEFT_SIDE ) = 0;
629       }
630       const SMDS_MeshNode *a, *b, *c, *d;
631       i = nbup - 1;
632       // avoid creating zero-area triangles near a straight-angle corner
633       {
634         a = uv_e2[i].node;
635         b = uv_e2[i-1].node;
636         c = uv_e1[nbright-2].node;
637         SMESH_TNodeXYZ pa( a ), pb( b ), pc( c );
638         double area = 0.5 * (( pb - pa ) ^ ( pc - pa )).Modulus();
639         if ( Abs( area ) < 1e-20 )
640         {
641           --g;
642           d = quad->UVPt( g, nbvertic-2 ).node;
643           if ( myTrianglePreference )
644           {
645             if ( SMDS_MeshFace* face = myHelper->AddFace(a, d, c))
646               meshDS->SetMeshElementOnShape(face, geomFaceID);
647           }
648           else
649           {
650             if ( SMDS_MeshFace* face = myHelper->AddFace(a, b, d, c))
651             {
652               meshDS->SetMeshElementOnShape(face, geomFaceID);
653               SMESH_ComputeErrorPtr& err = aMesh.GetSubMesh( aFace )->GetComputeError();
654               if ( !err || err->IsOK() || err->myName < COMPERR_WARNING )
655               {
656                 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
657                                                    "Bad quality quad created"));
658                 err->myBadElements.push_back( face );
659               }
660             }
661             --i;
662           }
663         }
664       }
665       // for each node of the up edge find nearest node
666       // in the first row of the regular grid and link them
667       for ( ; i > stop; i--) {
668         a = uv_e2[i].node;
669         b = uv_e2[i - 1].node;
670         gp_Pnt pb (b->X(), b->Y(), b->Z());
671
672         // find node c in the grid, which will be linked with node b
673         int near = g;
674         if (i == stop + 1) { // left bound reached, link with the leftmost node
675           c = quad->uv_grid[nbhoriz*(nbvertic - 2) + ilow].node;
676           near = ilow;
677         } else {
678           // find node c in the grid, nearest to the b
679           double mind = RealLast();
680           for (int k = g; k >= ilow; k--) {
681             const SMDS_MeshNode *nk;
682             if (k > iup)
683               nk = uv_e1[nbright - 2].node;
684             else
685               nk = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
686             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
687             double dist = pb.Distance(pnk);
688             if (dist < mind - eps) {
689               c = nk;
690               near = k;
691               mind = dist;
692             } else {
693               break;
694             }
695           }
696         }
697
698         if (near == g) { // make triangle
699           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
700           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
701         }
702         else { // make quadrangle
703           if (near + 1 > iup)
704             d = uv_e1[nbright - 2].node;
705           else
706             d = quad->uv_grid[nbhoriz*(nbvertic - 2) + near + 1].node;
707           //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
708           if (!myTrianglePreference){
709             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
710             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
711           }
712           else {
713             splitQuadFace(meshDS, geomFaceID, a, b, c, d);
714           }
715
716           if (near + 1 < g) { // if d is not at g - make additional triangles
717             for (int k = near + 1; k < g; k++) {
718               c = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
719               if (k + 1 > iup)
720                 d = uv_e1[nbright - 2].node;
721               else
722                 d = quad->uv_grid[nbhoriz*(nbvertic - 2) + k + 1].node;
723               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
724               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
725             }
726           }
727           g = near;
728         }
729       }
730     }
731   }
732
733   // right or left boundary quadrangles
734   if (quad->nbNodeOut( QUAD_RIGHT_SIDE ) && nbhoriz == 2) // this should not occure
735   {
736     int g = 0; // last processed node in the grid
737     int stop = nbright - 1;
738     i = 0;
739     if (quad->side[ QUAD_RIGHT_SIDE ].from != i    ) i++;
740     if (quad->side[ QUAD_RIGHT_SIDE ].to   != stop ) stop--;
741     for ( ; i < stop; i++) {
742       const SMDS_MeshNode *a, *b, *c, *d;
743       a = uv_e1[i].node;
744       b = uv_e1[i + 1].node;
745       gp_Pnt pb (b->X(), b->Y(), b->Z());
746
747       // find node c in the grid, nearest to the b
748       int near = g;
749       if (i == stop - 1) { // up bondary reached
750         c = quad->uv_grid[nbhoriz*(jup + 1) - 2].node;
751         near = jup;
752       } else {
753         double mind = RealLast();
754         for (int k = g; k <= jup; k++) {
755           const SMDS_MeshNode *nk;
756           if (k < jlow)
757             nk = uv_e0[nbdown - 2].node;
758           else
759             nk = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
760           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
761           double dist = pb.Distance(pnk);
762           if (dist < mind - eps) {
763             c = nk;
764             near = k;
765             mind = dist;
766           } else {
767             break;
768           }
769         }
770       }
771
772       if (near == g) { // make triangle
773         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
774         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
775       }
776       else { // make quadrangle
777         if (near - 1 < jlow)
778           d = uv_e0[nbdown - 2].node;
779         else
780           d = quad->uv_grid[nbhoriz*near - 2].node;
781         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
782
783         if (!myTrianglePreference){
784           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
785           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
786         }
787         else {
788           splitQuadFace(meshDS, geomFaceID, a, b, c, d);
789         }
790
791         if (near - 1 > g) { // if d not is at g - make additional triangles
792           for (int k = near - 1; k > g; k--) {
793             c = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
794             if (k - 1 < jlow)
795               d = uv_e0[nbdown - 2].node;
796             else
797               d = quad->uv_grid[nbhoriz*k - 2].node;
798             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
799             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
800           }
801         }
802         g = near;
803       }
804     }
805   } else {
806     if (quad->nbNodeOut(3) && nbhoriz == 2) {
807 //      MESSAGE("left edge is out");
808       int g = nbvertic - 1; // last processed node in the grid
809       int stop = 0;
810       i = quad->side[ QUAD_LEFT_SIDE ].to-1; // nbleft - 1;
811
812       const SMDS_MeshNode *a, *b, *c, *d;
813       // avoid creating zero-area triangles near a straight-angle corner
814       {
815         a = uv_e3[i].node;
816         b = uv_e3[i-1].node;
817         c = quad->UVPt( 1, g ).node;
818         SMESH_TNodeXYZ pa( a ), pb( b ), pc( c );
819         double area = 0.5 * (( pb - pa ) ^ ( pc - pa )).Modulus();
820         if ( Abs( area ) < 1e-20 )
821         {
822           --g;
823           d = quad->UVPt( 1, g ).node;
824           if ( myTrianglePreference )
825           {
826             if ( SMDS_MeshFace* face = myHelper->AddFace(a, d, c))
827               meshDS->SetMeshElementOnShape(face, geomFaceID);
828           }
829           else
830           {
831             if ( SMDS_MeshFace* face = myHelper->AddFace(a, b, d, c))
832             {
833               meshDS->SetMeshElementOnShape(face, geomFaceID);
834               SMESH_ComputeErrorPtr& err = aMesh.GetSubMesh( aFace )->GetComputeError();
835               if ( !err || err->IsOK() || err->myName < COMPERR_WARNING )
836               {
837                 err.reset( new SMESH_ComputeError( COMPERR_WARNING,
838                                                    "Bad quality quad created"));
839                 err->myBadElements.push_back( face );
840               }
841             }
842             --i;
843           }
844         }
845       }
846       for (; i > stop; i--) // loop on nodes on the left side
847       {
848         a = uv_e3[i].node;
849         b = uv_e3[i - 1].node;
850         gp_Pnt pb (b->X(), b->Y(), b->Z());
851
852         // find node c in the grid, nearest to the b
853         int near = g;
854         if (i == stop + 1) { // down bondary reached
855           c = quad->uv_grid[nbhoriz*jlow + 1].node;
856           near = jlow;
857         }
858         else {
859           double mind = RealLast();
860           for (int k = g; k >= jlow; k--) {
861             const SMDS_MeshNode *nk;
862             if (k > jup)
863               nk = quad->uv_grid[nbhoriz*jup + 1].node; //uv_e2[1].node;
864             else
865               nk = quad->uv_grid[nbhoriz*k + 1].node;
866             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
867             double dist = pb.Distance(pnk);
868             if (dist < mind - eps) {
869               c = nk;
870               near = k;
871               mind = dist;
872             } else {
873               break;
874             }
875           }
876         }
877
878         if (near == g) { // make triangle
879           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
880           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
881         }
882         else { // make quadrangle
883           if (near + 1 > jup)
884             d = quad->uv_grid[nbhoriz*jup + 1].node; //uv_e2[1].node;
885           else
886             d = quad->uv_grid[nbhoriz*(near + 1) + 1].node;
887           if (!myTrianglePreference) {
888             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
889             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
890           }
891           else {
892             splitQuadFace(meshDS, geomFaceID, a, b, c, d);
893           }
894
895           if (near + 1 < g) { // if d not is at g - make additional triangles
896             for (int k = near + 1; k < g; k++) {
897               c = quad->uv_grid[nbhoriz*k + 1].node;
898               if (k + 1 > jup)
899                 d = quad->uv_grid[nbhoriz*jup + 1].node; //uv_e2[1].node;
900               else
901                 d = quad->uv_grid[nbhoriz*(k + 1) + 1].node;
902               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
903               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
904             }
905           }
906           g = near;
907         }
908       }
909     }
910   }
911
912   bool isOk = true;
913   return isOk;
914 }
915
916
917 //=============================================================================
918 /*!
919  *  Evaluate
920  */
921 //=============================================================================
922
923 bool StdMeshers_Quadrangle_2D::Evaluate(SMESH_Mesh&         aMesh,
924                                         const TopoDS_Shape& aFace,
925                                         MapShapeNbElems&    aResMap)
926
927 {
928   aMesh.GetSubMesh(aFace);
929
930   std::vector<int> aNbNodes(4);
931   bool IsQuadratic = false;
932   if (!checkNbEdgesForEvaluate(aMesh, aFace, aResMap, aNbNodes, IsQuadratic)) {
933     std::vector<int> aResVec(SMDSEntity_Last);
934     for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
935     SMESH_subMesh * sm = aMesh.GetSubMesh(aFace);
936     aResMap.insert(std::make_pair(sm,aResVec));
937     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
938     smError.reset(new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
939     return false;
940   }
941
942   if (myQuadranglePreference) {
943     int n1 = aNbNodes[0];
944     int n2 = aNbNodes[1];
945     int n3 = aNbNodes[2];
946     int n4 = aNbNodes[3];
947     int nfull = n1+n2+n3+n4;
948     int ntmp = nfull/2;
949     ntmp = ntmp*2;
950     if (nfull==ntmp && ((n1!=n3) || (n2!=n4))) {
951       // special path for using only quandrangle faces
952       return evaluateQuadPref(aMesh, aFace, aNbNodes, aResMap, IsQuadratic);
953       //return true;
954     }
955   }
956
957   int nbdown  = aNbNodes[0];
958   int nbup    = aNbNodes[2];
959
960   int nbright = aNbNodes[1];
961   int nbleft  = aNbNodes[3];
962
963   int nbhoriz  = Min(nbdown, nbup);
964   int nbvertic = Min(nbright, nbleft);
965
966   int dh = Max(nbdown, nbup) - nbhoriz;
967   int dv = Max(nbright, nbleft) - nbvertic;
968
969   //int kdh = 0;
970   //if (dh>0) kdh = 1;
971   //int kdv = 0;
972   //if (dv>0) kdv = 1;
973
974   int nbNodes = (nbhoriz-2)*(nbvertic-2);
975   //int nbFaces3 = dh + dv + kdh*(nbvertic-1)*2 + kdv*(nbhoriz-1)*2;
976   int nbFaces3 = dh + dv;
977   //if (kdh==1 && kdv==1) nbFaces3 -= 2;
978   //if (dh>0 && dv>0) nbFaces3 -= 2;
979   //int nbFaces4 = (nbhoriz-1-kdh)*(nbvertic-1-kdv);
980   int nbFaces4 = (nbhoriz-1)*(nbvertic-1);
981
982   std::vector<int> aVec(SMDSEntity_Last);
983   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
984   if (IsQuadratic) {
985     aVec[SMDSEntity_Quad_Triangle] = nbFaces3;
986     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4;
987     int nbbndedges = nbdown + nbup + nbright + nbleft -4;
988     int nbintedges = (nbFaces4*4 + nbFaces3*3 - nbbndedges) / 2;
989     aVec[SMDSEntity_Node] = nbNodes + nbintedges;
990     if (aNbNodes.size()==5) {
991       aVec[SMDSEntity_Quad_Triangle] = nbFaces3 + aNbNodes[3] -1;
992       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4 - aNbNodes[3] +1;
993     }
994   }
995   else {
996     aVec[SMDSEntity_Node] = nbNodes;
997     aVec[SMDSEntity_Triangle] = nbFaces3;
998     aVec[SMDSEntity_Quadrangle] = nbFaces4;
999     if (aNbNodes.size()==5) {
1000       aVec[SMDSEntity_Triangle] = nbFaces3 + aNbNodes[3] - 1;
1001       aVec[SMDSEntity_Quadrangle] = nbFaces4 - aNbNodes[3] + 1;
1002     }
1003   }
1004   SMESH_subMesh * sm = aMesh.GetSubMesh(aFace);
1005   aResMap.insert(std::make_pair(sm,aVec));
1006
1007   return true;
1008 }
1009
1010 //================================================================================
1011 /*!
1012  * \brief Return true if the algorithm can mesh this shape
1013  *  \param [in] aShape - shape to check
1014  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
1015  *              else, returns OK if at least one shape is OK
1016  */
1017 //================================================================================
1018
1019 bool StdMeshers_Quadrangle_2D::IsApplicable( const TopoDS_Shape & aShape, bool toCheckAll )
1020 {
1021   int nbFoundFaces = 0;
1022   for (TopExp_Explorer exp( aShape, TopAbs_FACE ); exp.More(); exp.Next(), ++nbFoundFaces )
1023   {
1024     const TopoDS_Shape& aFace = exp.Current();
1025     int nbWire = SMESH_MesherHelper::Count( aFace, TopAbs_WIRE, false );
1026     if ( nbWire != 1 ) {
1027       if ( toCheckAll ) return false;
1028       continue;
1029     }
1030
1031     int nbNoDegenEdges = 0;
1032     TopExp_Explorer eExp( aFace, TopAbs_EDGE );
1033     for ( ; eExp.More() && nbNoDegenEdges < 3; eExp.Next() ) {
1034       if ( !SMESH_Algo::isDegenerated( TopoDS::Edge( eExp.Current() )))
1035         ++nbNoDegenEdges;
1036     }
1037     if ( toCheckAll  && nbNoDegenEdges <  3 ) return false;
1038     if ( !toCheckAll && nbNoDegenEdges >= 3 ) return true;
1039   }
1040   return ( toCheckAll && nbFoundFaces != 0 );
1041 }
1042
1043 //================================================================================
1044 /*!
1045  * \brief Return true if only two given edges meat at their common vertex
1046  */
1047 //================================================================================
1048
1049 static bool twoEdgesMeatAtVertex(const TopoDS_Edge& e1,
1050                                  const TopoDS_Edge& e2,
1051                                  SMESH_Mesh &       mesh)
1052 {
1053   TopoDS_Vertex v;
1054   if (!TopExp::CommonVertex(e1, e2, v))
1055     return false;
1056   TopTools_ListIteratorOfListOfShape ancestIt(mesh.GetAncestors(v));
1057   for (; ancestIt.More() ; ancestIt.Next())
1058     if (ancestIt.Value().ShapeType() == TopAbs_EDGE)
1059       if (!e1.IsSame(ancestIt.Value()) && !e2.IsSame(ancestIt.Value()))
1060         return false;
1061   return true;
1062 }
1063
1064 //=============================================================================
1065 /*!
1066  *  
1067  */
1068 //=============================================================================
1069
1070 FaceQuadStruct::Ptr StdMeshers_Quadrangle_2D::CheckNbEdges(SMESH_Mesh &         aMesh,
1071                                                            const TopoDS_Shape & aShape,
1072                                                            const bool           considerMesh)
1073 {
1074   if ( !myQuadList.empty() && myQuadList.front()->face.IsSame( aShape ))
1075     return myQuadList.front();
1076
1077   TopoDS_Face F = TopoDS::Face(aShape);
1078   if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
1079   const bool ignoreMediumNodes = _quadraticMesh;
1080
1081   // verify 1 wire only
1082   list< TopoDS_Edge > edges;
1083   list< int > nbEdgesInWire;
1084   int nbWire = SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1085   if (nbWire != 1) {
1086     error(COMPERR_BAD_SHAPE, TComm("Wrong number of wires: ") << nbWire);
1087     return FaceQuadStruct::Ptr();
1088   }
1089
1090   // find corner vertices of the quad
1091   vector<TopoDS_Vertex> corners;
1092   int nbDegenEdges, nbSides = getCorners( F, aMesh, edges, corners, nbDegenEdges, considerMesh );
1093   if ( nbSides == 0 )
1094   {
1095     return FaceQuadStruct::Ptr();
1096   }
1097   FaceQuadStruct::Ptr quad( new FaceQuadStruct );
1098   quad->side.reserve(nbEdgesInWire.front());
1099   quad->face = F;
1100
1101   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
1102   if ( nbSides == 3 ) // 3 sides and corners[0] is a vertex with myTriaVertexID
1103   {
1104     for ( int iSide = 0; iSide < 3; ++iSide )
1105     {
1106       list< TopoDS_Edge > sideEdges;
1107       TopoDS_Vertex nextSideV = corners[( iSide + 1 ) % 3 ];
1108       while ( edgeIt != edges.end() &&
1109               !nextSideV.IsSame( SMESH_MesherHelper::IthVertex( 0, *edgeIt )))
1110         if ( SMESH_Algo::isDegenerated( *edgeIt ))
1111           ++edgeIt;
1112         else
1113           sideEdges.push_back( *edgeIt++ );
1114       if ( !sideEdges.empty() )
1115         quad->side.push_back( StdMeshers_FaceSide::New(F, sideEdges, &aMesh, iSide < QUAD_TOP_SIDE,
1116                                                        ignoreMediumNodes, myProxyMesh));
1117       else
1118         --iSide;
1119     }
1120     const vector<UVPtStruct>& UVPSleft  = quad->side[0].GetUVPtStruct(true,0);
1121     /*  vector<UVPtStruct>& UVPStop   = */quad->side[1].GetUVPtStruct(false,1);
1122     /*  vector<UVPtStruct>& UVPSright = */quad->side[2].GetUVPtStruct(true,1);
1123     const SMDS_MeshNode* aNode = UVPSleft[0].node;
1124     gp_Pnt2d aPnt2d = UVPSleft[0].UV();
1125     quad->side.push_back( StdMeshers_FaceSide::New( quad->side[1].grid.get(), aNode, &aPnt2d ));
1126     myNeedSmooth = ( nbDegenEdges > 0 );
1127     return quad;
1128   }
1129   else // 4 sides
1130   {
1131     myNeedSmooth = ( corners.size() == 4 && nbDegenEdges > 0 );
1132     int iSide = 0, nbUsedDegen = 0, nbLoops = 0;
1133     for ( ; edgeIt != edges.end(); ++nbLoops )
1134     {
1135       list< TopoDS_Edge > sideEdges;
1136       TopoDS_Vertex nextSideV = corners[( iSide + 1 - nbUsedDegen ) % corners.size() ];
1137       while ( edgeIt != edges.end() &&
1138               !nextSideV.IsSame( myHelper->IthVertex( 0, *edgeIt )))
1139       {
1140         if ( SMESH_Algo::isDegenerated( *edgeIt ) )
1141         {
1142           if ( myNeedSmooth )
1143           {
1144             ++edgeIt; // no side on the degenerated EDGE
1145           }
1146           else
1147           {
1148             if ( sideEdges.empty() )
1149             {
1150               ++nbUsedDegen;
1151               sideEdges.push_back( *edgeIt++ ); // a degenerated side
1152               break;
1153             }
1154             else
1155             {
1156               break; // do not append a degenerated EDGE to a regular side
1157             }
1158           }
1159         }
1160         else
1161         {
1162           sideEdges.push_back( *edgeIt++ );
1163         }
1164       }
1165       if ( !sideEdges.empty() )
1166       {
1167         quad->side.push_back( StdMeshers_FaceSide::New( F, sideEdges, &aMesh, iSide < QUAD_TOP_SIDE,
1168                                                         ignoreMediumNodes, myProxyMesh ));
1169         ++iSide;
1170       }
1171       else if ( !SMESH_Algo::isDegenerated( *edgeIt ) && // closed EDGE
1172                 myHelper->IthVertex( 0, *edgeIt ).IsSame( myHelper->IthVertex( 1, *edgeIt )))
1173       {
1174         quad->side.push_back( StdMeshers_FaceSide::New( F, *edgeIt++, &aMesh, iSide < QUAD_TOP_SIDE,
1175                                                         ignoreMediumNodes, myProxyMesh));
1176         ++iSide;
1177       }
1178       if ( quad->side.size() == 4 )
1179         break;
1180       if ( nbLoops > 8 )
1181       {
1182         error(TComm("Bug: infinite loop in StdMeshers_Quadrangle_2D::CheckNbEdges()"));
1183         quad.reset();
1184         break;
1185       }
1186     }
1187     if ( quad && quad->side.size() != 4 )
1188     {
1189       error(TComm("Bug: ") << quad->side.size()  << " sides found instead of 4");
1190       quad.reset();
1191     }
1192   }
1193
1194   return quad;
1195 }
1196
1197
1198 //=============================================================================
1199 /*!
1200  *  
1201  */
1202 //=============================================================================
1203
1204 bool StdMeshers_Quadrangle_2D::checkNbEdgesForEvaluate(SMESH_Mesh&          aMesh,
1205                                                        const TopoDS_Shape & aShape,
1206                                                        MapShapeNbElems&     aResMap,
1207                                                        std::vector<int>&    aNbNodes,
1208                                                        bool&                IsQuadratic)
1209
1210 {
1211   const TopoDS_Face & F = TopoDS::Face(aShape);
1212
1213   // verify 1 wire only, with 4 edges
1214   list< TopoDS_Edge > edges;
1215   list< int > nbEdgesInWire;
1216   int nbWire = SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1217   if (nbWire != 1) {
1218     return false;
1219   }
1220
1221   aNbNodes.resize(4);
1222
1223   int nbSides = 0;
1224   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
1225   SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1226   MapShapeNbElemsItr anIt = aResMap.find(sm);
1227   if (anIt==aResMap.end()) {
1228     return false;
1229   }
1230   std::vector<int> aVec = (*anIt).second;
1231   IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1232   if (nbEdgesInWire.front() == 3) { // exactly 3 edges
1233     if (myTriaVertexID>0) {
1234       SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1235       TopoDS_Vertex V = TopoDS::Vertex(meshDS->IndexToShape(myTriaVertexID));
1236       if (!V.IsNull()) {
1237         TopoDS_Edge E1,E2,E3;
1238         for (; edgeIt != edges.end(); ++edgeIt) {
1239           TopoDS_Edge E =  TopoDS::Edge(*edgeIt);
1240           TopoDS_Vertex VF, VL;
1241           TopExp::Vertices(E, VF, VL, true);
1242           if (VF.IsSame(V))
1243             E1 = E;
1244           else if (VL.IsSame(V))
1245             E3 = E;
1246           else
1247             E2 = E;
1248         }
1249         SMESH_subMesh * sm = aMesh.GetSubMesh(E1);
1250         MapShapeNbElemsItr anIt = aResMap.find(sm);
1251         if (anIt==aResMap.end()) return false;
1252         std::vector<int> aVec = (*anIt).second;
1253         if (IsQuadratic)
1254           aNbNodes[0] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1255         else
1256           aNbNodes[0] = aVec[SMDSEntity_Node] + 2;
1257         sm = aMesh.GetSubMesh(E2);
1258         anIt = aResMap.find(sm);
1259         if (anIt==aResMap.end()) return false;
1260         aVec = (*anIt).second;
1261         if (IsQuadratic)
1262           aNbNodes[1] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1263         else
1264           aNbNodes[1] = aVec[SMDSEntity_Node] + 2;
1265         sm = aMesh.GetSubMesh(E3);
1266         anIt = aResMap.find(sm);
1267         if (anIt==aResMap.end()) return false;
1268         aVec = (*anIt).second;
1269         if (IsQuadratic)
1270           aNbNodes[2] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1271         else
1272           aNbNodes[2] = aVec[SMDSEntity_Node] + 2;
1273         aNbNodes[3] = aNbNodes[1];
1274         aNbNodes.resize(5);
1275         nbSides = 4;
1276       }
1277     }
1278   }
1279   if (nbEdgesInWire.front() == 4) { // exactly 4 edges
1280     for (; edgeIt != edges.end(); edgeIt++) {
1281       SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1282       MapShapeNbElemsItr anIt = aResMap.find(sm);
1283       if (anIt==aResMap.end()) {
1284         return false;
1285       }
1286       std::vector<int> aVec = (*anIt).second;
1287       if (IsQuadratic)
1288         aNbNodes[nbSides] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1289       else
1290         aNbNodes[nbSides] = aVec[SMDSEntity_Node] + 2;
1291       nbSides++;
1292     }
1293   }
1294   else if (nbEdgesInWire.front() > 4) { // more than 4 edges - try to unite some
1295     list< TopoDS_Edge > sideEdges;
1296     while (!edges.empty()) {
1297       sideEdges.clear();
1298       sideEdges.splice(sideEdges.end(), edges, edges.begin()); // edges.front() -> sideEdges.end()
1299       bool sameSide = true;
1300       while (!edges.empty() && sameSide) {
1301         sameSide = SMESH_Algo::IsContinuous(sideEdges.back(), edges.front());
1302         if (sameSide)
1303           sideEdges.splice(sideEdges.end(), edges, edges.begin());
1304       }
1305       if (nbSides == 0) { // go backward from the first edge
1306         sameSide = true;
1307         while (!edges.empty() && sameSide) {
1308           sameSide = SMESH_Algo::IsContinuous(sideEdges.front(), edges.back());
1309           if (sameSide)
1310             sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1311         }
1312       }
1313       list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1314       aNbNodes[nbSides] = 1;
1315       for (; ite!=sideEdges.end(); ite++) {
1316         SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1317         MapShapeNbElemsItr anIt = aResMap.find(sm);
1318         if (anIt==aResMap.end()) {
1319           return false;
1320         }
1321         std::vector<int> aVec = (*anIt).second;
1322         if (IsQuadratic)
1323           aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1324         else
1325           aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1326       }
1327       ++nbSides;
1328     }
1329     // issue 20222. Try to unite only edges shared by two same faces
1330     if (nbSides < 4) {
1331       nbSides = 0;
1332       SMESH_Block::GetOrderedEdges (F, edges, nbEdgesInWire);
1333       while (!edges.empty()) {
1334         sideEdges.clear();
1335         sideEdges.splice(sideEdges.end(), edges, edges.begin());
1336         bool sameSide = true;
1337         while (!edges.empty() && sameSide) {
1338           sameSide =
1339             SMESH_Algo::IsContinuous(sideEdges.back(), edges.front()) &&
1340             twoEdgesMeatAtVertex(sideEdges.back(), edges.front(), aMesh);
1341           if (sameSide)
1342             sideEdges.splice(sideEdges.end(), edges, edges.begin());
1343         }
1344         if (nbSides == 0) { // go backward from the first edge
1345           sameSide = true;
1346           while (!edges.empty() && sameSide) {
1347             sameSide =
1348               SMESH_Algo::IsContinuous(sideEdges.front(), edges.back()) &&
1349               twoEdgesMeatAtVertex(sideEdges.front(), edges.back(), aMesh);
1350             if (sameSide)
1351               sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1352           }
1353         }
1354         list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1355         aNbNodes[nbSides] = 1;
1356         for (; ite!=sideEdges.end(); ite++) {
1357           SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1358           MapShapeNbElemsItr anIt = aResMap.find(sm);
1359           if (anIt==aResMap.end()) {
1360             return false;
1361           }
1362           std::vector<int> aVec = (*anIt).second;
1363           if (IsQuadratic)
1364             aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1365           else
1366             aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1367         }
1368         ++nbSides;
1369       }
1370     }
1371   }
1372   if (nbSides != 4) {
1373     if (!nbSides)
1374       nbSides = nbEdgesInWire.front();
1375     error(COMPERR_BAD_SHAPE, TComm("Face must have 4 sides but not ") << nbSides);
1376     return false;
1377   }
1378
1379   return true;
1380 }
1381
1382
1383 //=============================================================================
1384 /*!
1385  *  CheckAnd2Dcompute
1386  */
1387 //=============================================================================
1388
1389 FaceQuadStruct::Ptr
1390 StdMeshers_Quadrangle_2D::CheckAnd2Dcompute (SMESH_Mesh &         aMesh,
1391                                              const TopoDS_Shape & aShape,
1392                                              const bool           CreateQuadratic)
1393 {
1394   _quadraticMesh = CreateQuadratic;
1395
1396   FaceQuadStruct::Ptr quad = CheckNbEdges(aMesh, aShape);
1397   if ( quad )
1398   {
1399     // set normalized grid on unit square in parametric domain
1400     if ( ! setNormalizedGrid( quad ))
1401       quad.reset();
1402   }
1403   return quad;
1404 }
1405
1406 namespace
1407 {
1408   inline const vector<UVPtStruct>& getUVPtStructIn(FaceQuadStruct::Ptr& quad, int i, int nbSeg)
1409   {
1410     bool   isXConst   = (i == QUAD_BOTTOM_SIDE || i == QUAD_TOP_SIDE);
1411     double constValue = (i == QUAD_BOTTOM_SIDE || i == QUAD_LEFT_SIDE) ? 0 : 1;
1412     return
1413       quad->nbNodeOut(i) ?
1414       quad->side[i].grid->SimulateUVPtStruct(nbSeg,isXConst,constValue) :
1415       quad->side[i].grid->GetUVPtStruct     (isXConst,constValue);
1416   }
1417   inline gp_UV calcUV(double x, double y,
1418                       const gp_UV& a0,const gp_UV& a1,const gp_UV& a2,const gp_UV& a3,
1419                       const gp_UV& p0,const gp_UV& p1,const gp_UV& p2,const gp_UV& p3)
1420   {
1421     return
1422       ((1 - y) * p0 + x * p1 + y * p2 + (1 - x) * p3 ) -
1423       ((1 - x) * (1 - y) * a0 + x * (1 - y) * a1 + x * y * a2 + (1 - x) * y * a3);
1424   }
1425 }
1426
1427 //=============================================================================
1428 /*!
1429  *  
1430  */
1431 //=============================================================================
1432
1433 bool StdMeshers_Quadrangle_2D::setNormalizedGrid (FaceQuadStruct::Ptr quad)
1434 {
1435   if ( !quad->uv_grid.empty() )
1436     return true;
1437
1438   // Algorithme décrit dans "Génération automatique de maillages"
1439   // P.L. GEORGE, MASSON, Â§ 6.4.1 p. 84-85
1440   // traitement dans le domaine paramétrique 2d u,v
1441   // transport - projection sur le carré unité
1442
1443   //      max             min                    0     x1     1
1444   //     |<----north-2-------^                a3 -------------> a2
1445   //     |                   |                   ^1          1^
1446   //    west-3            east-1 =right          |            |
1447   //     |                   |         ==>       |            |
1448   //  y0 |                   | y1                |            |
1449   //     |                   |                   |0          0|
1450   //     v----south-0-------->                a0 -------------> a1
1451   //      min             max                    0     x0     1
1452   //             =down
1453   //
1454   const FaceQuadStruct::Side & bSide = quad->side[0];
1455   const FaceQuadStruct::Side & rSide = quad->side[1];
1456   const FaceQuadStruct::Side & tSide = quad->side[2];
1457   const FaceQuadStruct::Side & lSide = quad->side[3];
1458
1459   int nbhoriz  = Min( bSide.NbPoints(), tSide.NbPoints() );
1460   int nbvertic = Min( rSide.NbPoints(), lSide.NbPoints() );
1461
1462   if ( myQuadList.size() == 1 )
1463   {
1464     // all sub-quads must have NO sides with nbNodeOut > 0
1465     quad->nbNodeOut(0) = Max( 0, bSide.grid->NbPoints() - tSide.grid->NbPoints() );
1466     quad->nbNodeOut(1) = Max( 0, rSide.grid->NbPoints() - lSide.grid->NbPoints() );
1467     quad->nbNodeOut(2) = Max( 0, tSide.grid->NbPoints() - bSide.grid->NbPoints() );
1468     quad->nbNodeOut(3) = Max( 0, lSide.grid->NbPoints() - rSide.grid->NbPoints() );
1469   }
1470   const vector<UVPtStruct>& uv_e0 = bSide.GetUVPtStruct();
1471   const vector<UVPtStruct>& uv_e1 = rSide.GetUVPtStruct();
1472   const vector<UVPtStruct>& uv_e2 = tSide.GetUVPtStruct();
1473   const vector<UVPtStruct>& uv_e3 = lSide.GetUVPtStruct();
1474   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
1475     //return error("Can't find nodes on sides");
1476     return error(COMPERR_BAD_INPUT_MESH);
1477
1478   quad->uv_grid.resize( nbvertic * nbhoriz );
1479   quad->iSize = nbhoriz;
1480   quad->jSize = nbvertic;
1481   UVPtStruct *uv_grid = & quad->uv_grid[0];
1482
1483   quad->uv_box.Clear();
1484
1485   // copy data of face boundary
1486
1487   FaceQuadStruct::SideIterator sideIter;
1488
1489   { // BOTTOM
1490     const int     j = 0;
1491     const double x0 = bSide.First().normParam;
1492     const double dx = bSide.Last().normParam - bSide.First().normParam;
1493     for ( sideIter.Init( bSide ); sideIter.More(); sideIter.Next() ) {
1494       sideIter.UVPt().x = ( sideIter.UVPt().normParam - x0 ) / dx;
1495       sideIter.UVPt().y = 0.;
1496       uv_grid[ j * nbhoriz + sideIter.Count() ] = sideIter.UVPt();
1497       quad->uv_box.Add( sideIter.UVPt().UV() );
1498     }
1499   }
1500   { // RIGHT
1501     const int     i = nbhoriz - 1;
1502     const double y0 = rSide.First().normParam;
1503     const double dy = rSide.Last().normParam - rSide.First().normParam;
1504     sideIter.Init( rSide );
1505     if ( quad->UVPt( i, sideIter.Count() ).node )
1506       sideIter.Next(); // avoid copying from a split emulated side
1507     for ( ; sideIter.More(); sideIter.Next() ) {
1508       sideIter.UVPt().x = 1.;
1509       sideIter.UVPt().y = ( sideIter.UVPt().normParam - y0 ) / dy;
1510       uv_grid[ sideIter.Count() * nbhoriz + i ] = sideIter.UVPt();
1511       quad->uv_box.Add( sideIter.UVPt().UV() );
1512     }
1513   }
1514   { // TOP
1515     const int     j = nbvertic - 1;
1516     const double x0 = tSide.First().normParam;
1517     const double dx = tSide.Last().normParam - tSide.First().normParam;
1518     int i = 0, nb = nbhoriz;
1519     sideIter.Init( tSide );
1520     if ( quad->UVPt( nb-1, j ).node ) --nb; // avoid copying from a split emulated side
1521     for ( ; i < nb; i++, sideIter.Next()) {
1522       sideIter.UVPt().x = ( sideIter.UVPt().normParam - x0 ) / dx;
1523       sideIter.UVPt().y = 1.;
1524       uv_grid[ j * nbhoriz + i ] = sideIter.UVPt();
1525       quad->uv_box.Add( sideIter.UVPt().UV() );
1526     }
1527   }
1528   { // LEFT
1529     const int i = 0;
1530     const double y0 = lSide.First().normParam;
1531     const double dy = lSide.Last().normParam - lSide.First().normParam;
1532     int j = 0, nb = nbvertic;
1533     sideIter.Init( lSide );
1534     if ( quad->UVPt( i, j    ).node )
1535       ++j, sideIter.Next(); // avoid copying from a split emulated side
1536     if ( quad->UVPt( i, nb-1 ).node )
1537       --nb;
1538     for ( ; j < nb; j++, sideIter.Next()) {
1539       sideIter.UVPt().x = 0.;
1540       sideIter.UVPt().y = ( sideIter.UVPt().normParam - y0 ) / dy;
1541       uv_grid[ j * nbhoriz + i ] = sideIter.UVPt();
1542       quad->uv_box.Add( sideIter.UVPt().UV() );
1543     }
1544   }
1545
1546   // normalized 2d parameters on grid
1547
1548   for (int i = 1; i < nbhoriz-1; i++)
1549   {
1550     const double x0 = quad->UVPt( i, 0          ).x;
1551     const double x1 = quad->UVPt( i, nbvertic-1 ).x;
1552     for (int j = 1; j < nbvertic-1; j++)
1553     {
1554       const double y0 = quad->UVPt( 0,         j ).y;
1555       const double y1 = quad->UVPt( nbhoriz-1, j ).y;
1556       // --- intersection : x=x0+(y0+x(y1-y0))(x1-x0)
1557       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1558       double y = y0 + x * (y1 - y0);
1559       int   ij = j * nbhoriz + i;
1560       uv_grid[ij].x = x;
1561       uv_grid[ij].y = y;
1562       uv_grid[ij].node = NULL;
1563     }
1564   }
1565
1566   // projection on 2d domain (u,v)
1567
1568   gp_UV a0 = quad->UVPt( 0,         0          ).UV();
1569   gp_UV a1 = quad->UVPt( nbhoriz-1, 0          ).UV();
1570   gp_UV a2 = quad->UVPt( nbhoriz-1, nbvertic-1 ).UV();
1571   gp_UV a3 = quad->UVPt( 0,         nbvertic-1 ).UV();
1572
1573   for (int i = 1; i < nbhoriz-1; i++)
1574   {
1575     gp_UV p0 = quad->UVPt( i, 0          ).UV();
1576     gp_UV p2 = quad->UVPt( i, nbvertic-1 ).UV();
1577     for (int j = 1; j < nbvertic-1; j++)
1578     {
1579       gp_UV p1 = quad->UVPt( nbhoriz-1, j ).UV();
1580       gp_UV p3 = quad->UVPt( 0,         j ).UV();
1581
1582       int ij = j * nbhoriz + i;
1583       double x = uv_grid[ij].x;
1584       double y = uv_grid[ij].y;
1585
1586       gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1587
1588       uv_grid[ij].u = uv.X();
1589       uv_grid[ij].v = uv.Y();
1590     }
1591   }
1592   return true;
1593 }
1594
1595 //=======================================================================
1596 //function : ShiftQuad
1597 //purpose  : auxilary function for computeQuadPref
1598 //=======================================================================
1599
1600 void StdMeshers_Quadrangle_2D::shiftQuad(FaceQuadStruct::Ptr& quad, const int num )
1601 {
1602   quad->shift( num, /*ori=*/true, /*keepGrid=*/myQuadList.size() > 1 );
1603 }
1604
1605 //================================================================================
1606 /*!
1607  * \brief Rotate sides of a quad by given nb of quartes
1608  *  \param nb  - number of rotation quartes
1609  *  \param ori - to keep orientation of sides as in an unit quad or not
1610  *  \param keepGrid - if \c true Side::grid is not changed, Side::from and Side::to
1611  *         are altered instead
1612  */
1613 //================================================================================
1614
1615 void FaceQuadStruct::shift( size_t nb, bool ori, bool keepGrid )
1616 {
1617   if ( nb == 0 ) return;
1618
1619   vector< Side > newSides( side.size() );
1620   vector< Side* > sidePtrs( side.size() );
1621   for (int i = QUAD_BOTTOM_SIDE; i < NB_QUAD_SIDES; ++i)
1622   {
1623     int id = (i + nb) % NB_QUAD_SIDES;
1624     if ( ori )
1625     {
1626       bool wasForward = (i  < QUAD_TOP_SIDE);
1627       bool newForward = (id < QUAD_TOP_SIDE);
1628       if ( wasForward != newForward )
1629         side[ i ].Reverse( keepGrid );
1630     }
1631     newSides[ id ] = side[ i ];
1632     sidePtrs[ i ] = & side[ i ];
1633   }
1634   // make newSides refer newSides via Side::Contact's
1635   for ( size_t i = 0; i < newSides.size(); ++i )
1636   {
1637     FaceQuadStruct::Side& ns = newSides[ i ];
1638     for ( size_t iC = 0; iC < ns.contacts.size(); ++iC )
1639     {
1640       FaceQuadStruct::Side* oSide = ns.contacts[iC].other_side;
1641       vector< Side* >::iterator sIt = std::find( sidePtrs.begin(), sidePtrs.end(), oSide );
1642       if ( sIt != sidePtrs.end() )
1643         ns.contacts[iC].other_side = & newSides[ *sIt - sidePtrs[0] ];
1644     }
1645   }
1646   newSides.swap( side );
1647
1648   uv_grid.clear();
1649 }
1650
1651 //=======================================================================
1652 //function : calcUV
1653 //purpose  : auxilary function for computeQuadPref
1654 //=======================================================================
1655
1656 static gp_UV calcUV(double x0, double x1, double y0, double y1,
1657                     FaceQuadStruct::Ptr& quad,
1658                     const gp_UV& a0, const gp_UV& a1,
1659                     const gp_UV& a2, const gp_UV& a3)
1660 {
1661   double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1662   double y = y0 + x * (y1 - y0);
1663
1664   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE].grid->Value2d(x).XY();
1665   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ].grid->Value2d(y).XY();
1666   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ].grid->Value2d(x).XY();
1667   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ].grid->Value2d(y).XY();
1668
1669   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1670
1671   return uv;
1672 }
1673
1674 //=======================================================================
1675 //function : calcUV2
1676 //purpose  : auxilary function for computeQuadPref
1677 //=======================================================================
1678
1679 static gp_UV calcUV2(double x, double y,
1680                      FaceQuadStruct::Ptr& quad,
1681                      const gp_UV& a0, const gp_UV& a1,
1682                      const gp_UV& a2, const gp_UV& a3)
1683 {
1684   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE].grid->Value2d(x).XY();
1685   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ].grid->Value2d(y).XY();
1686   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ].grid->Value2d(x).XY();
1687   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ].grid->Value2d(y).XY();
1688
1689   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1690
1691   return uv;
1692 }
1693
1694
1695 //=======================================================================
1696 /*!
1697  * Create only quandrangle faces
1698  */
1699 //=======================================================================
1700
1701 bool StdMeshers_Quadrangle_2D::computeQuadPref (SMESH_Mesh &        aMesh,
1702                                                 const TopoDS_Face&  aFace,
1703                                                 FaceQuadStruct::Ptr quad)
1704 {
1705   const bool OldVersion = (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED);
1706   const bool WisF = true;
1707
1708   SMESHDS_Mesh *  meshDS = aMesh.GetMeshDS();
1709   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
1710   int i,j,    geomFaceID = meshDS->ShapeToIndex(aFace);
1711
1712   int nb = quad->side[0].NbPoints();
1713   int nr = quad->side[1].NbPoints();
1714   int nt = quad->side[2].NbPoints();
1715   int nl = quad->side[3].NbPoints();
1716   int dh = abs(nb-nt);
1717   int dv = abs(nr-nl);
1718
1719   if ( myForcedPnts.empty() )
1720   {
1721     // rotate sides to be as in the picture below and to have
1722     // dh >= dv and nt > nb
1723     if ( dh >= dv )
1724       shiftQuad( quad, ( nt > nb ) ? 0 : 2 );
1725     else
1726       shiftQuad( quad, ( nr > nl ) ? 1 : 3 );
1727   }
1728   else
1729   {
1730     // rotate the quad to have nt > nb [and nr > nl]
1731     if ( nb > nt )
1732       shiftQuad ( quad, nr > nl ? 1 : 2 );
1733     else if ( nr > nl )
1734       shiftQuad( quad, nb == nt ? 1 : 0 );
1735     else if ( nl > nr )
1736       shiftQuad( quad, 3 );
1737   }
1738
1739   nb = quad->side[0].NbPoints();
1740   nr = quad->side[1].NbPoints();
1741   nt = quad->side[2].NbPoints();
1742   nl = quad->side[3].NbPoints();
1743   dh = abs(nb-nt);
1744   dv = abs(nr-nl);
1745   int nbh  = Max(nb,nt);
1746   int nbv  = Max(nr,nl);
1747   int addh = 0;
1748   int addv = 0;
1749
1750   // Orientation of face and 3 main domain for future faces
1751   // ----------- Old version ---------------
1752   //       0   top    1
1753   //      1------------1
1754   //       |   |  |   |
1755   //       |   |C |   |
1756   //       | L |  | R |
1757   //  left |   |__|   | rigth
1758   //       |  /    \  |
1759   //       | /  C   \ |
1760   //       |/        \|
1761   //      0------------0
1762   //       0  bottom  1
1763
1764   // ----------- New version ---------------
1765   //       0   top    1
1766   //      1------------1
1767   //       |   |__|   |
1768   //       |  /    \  |
1769   //       | /  C   \ |
1770   //  left |/________\| rigth
1771   //       |          |
1772   //       |    C     |
1773   //       |          |
1774   //      0------------0
1775   //       0  bottom  1
1776
1777
1778   const int bfrom = quad->side[0].from;
1779   const int rfrom = quad->side[1].from;
1780   const int tfrom = quad->side[2].from;
1781   const int lfrom = quad->side[3].from;
1782   {
1783     const vector<UVPtStruct>& uv_eb_vec = quad->side[0].GetUVPtStruct(true,0);
1784     const vector<UVPtStruct>& uv_er_vec = quad->side[1].GetUVPtStruct(false,1);
1785     const vector<UVPtStruct>& uv_et_vec = quad->side[2].GetUVPtStruct(true,1);
1786     const vector<UVPtStruct>& uv_el_vec = quad->side[3].GetUVPtStruct(false,0);
1787     if (uv_eb_vec.empty() ||
1788         uv_er_vec.empty() ||
1789         uv_et_vec.empty() ||
1790         uv_el_vec.empty())
1791       return error(COMPERR_BAD_INPUT_MESH);
1792   }
1793   FaceQuadStruct::SideIterator uv_eb, uv_er, uv_et, uv_el;
1794   uv_eb.Init( quad->side[0] );
1795   uv_er.Init( quad->side[1] );
1796   uv_et.Init( quad->side[2] );
1797   uv_el.Init( quad->side[3] );
1798
1799   gp_UV a0,a1,a2,a3, p0,p1,p2,p3, uv;
1800   double x,y;
1801
1802   a0 = uv_eb[ 0 ].UV();
1803   a1 = uv_er[ 0 ].UV();
1804   a2 = uv_er[ nr-1 ].UV();
1805   a3 = uv_et[ 0 ].UV();
1806
1807   if ( !myForcedPnts.empty() )
1808   {
1809     if ( dv != 0 && dh != 0 ) // here myQuadList.size() == 1
1810     {
1811       const int dmin = Min( dv, dh );
1812
1813       // Make a side separating domains L and Cb
1814       StdMeshers_FaceSidePtr sideLCb;
1815       UVPtStruct p3dom; // a point where 3 domains meat
1816       {                                                     //   dmin
1817         vector<UVPtStruct> pointsLCb( dmin+1 );             // 1--------1
1818         pointsLCb[0] = uv_eb[0];                            //  |   |  |
1819         for ( int i = 1; i <= dmin; ++i )                   //  |   |Ct|
1820         {                                                   //  | L |  |
1821           x  = uv_et[ i ].normParam;                        //  |   |__|
1822           y  = uv_er[ i ].normParam;                        //  |  /   |
1823           p0 = quad->side[0].grid->Value2d( x ).XY();       //  | / Cb |dmin
1824           p1 = uv_er[ i ].UV();                             //  |/     |
1825           p2 = uv_et[ i ].UV();                             // 0--------0
1826           p3 = quad->side[3].grid->Value2d( y ).XY();
1827           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1828           pointsLCb[ i ].u = uv.X();
1829           pointsLCb[ i ].v = uv.Y();
1830         }
1831         sideLCb = StdMeshers_FaceSide::New( pointsLCb, aFace );
1832         p3dom   = pointsLCb.back();
1833       }
1834       // Make a side separating domains L and Ct
1835       StdMeshers_FaceSidePtr sideLCt;
1836       {
1837         vector<UVPtStruct> pointsLCt( nl );
1838         pointsLCt[0]     = p3dom;
1839         pointsLCt.back() = uv_et[ dmin ];
1840         x  = uv_et[ dmin ].normParam;
1841         p0 = quad->side[0].grid->Value2d( x ).XY();
1842         p2 = uv_et[ dmin ].UV();
1843         double y0 = uv_er[ dmin ].normParam;
1844         for ( int i = 1; i < nl-1; ++i )
1845         {
1846           y  = y0 + i / ( nl-1. ) * ( 1. - y0 );
1847           p1 = quad->side[1].grid->Value2d( y ).XY();
1848           p3 = quad->side[3].grid->Value2d( y ).XY();
1849           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1850           pointsLCt[ i ].u = uv.X();
1851           pointsLCt[ i ].v = uv.Y();
1852         }
1853         sideLCt = StdMeshers_FaceSide::New( pointsLCt, aFace );
1854       }
1855       // Make a side separating domains Cb and Ct
1856       StdMeshers_FaceSidePtr sideCbCt;
1857       {
1858         vector<UVPtStruct> pointsCbCt( nb );
1859         pointsCbCt[0]     = p3dom;
1860         pointsCbCt.back() = uv_er[ dmin ];
1861         y  = uv_er[ dmin ].normParam;
1862         p1 = uv_er[ dmin ].UV();
1863         p3 = quad->side[3].grid->Value2d( y ).XY();
1864         double x0 = uv_et[ dmin ].normParam;
1865         for ( int i = 1; i < nb-1; ++i )
1866         {
1867           x  = x0 + i / ( nb-1. ) * ( 1. - x0 );
1868           p2 = quad->side[2].grid->Value2d( x ).XY();
1869           p0 = quad->side[0].grid->Value2d( x ).XY();
1870           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1871           pointsCbCt[ i ].u = uv.X();
1872           pointsCbCt[ i ].v = uv.Y();
1873         }
1874         sideCbCt = StdMeshers_FaceSide::New( pointsCbCt, aFace );
1875       }
1876       // Make Cb quad
1877       FaceQuadStruct* qCb = new FaceQuadStruct( quad->face, "Cb" );
1878       myQuadList.push_back( FaceQuadStruct::Ptr( qCb ));
1879       qCb->side.resize(4);
1880       qCb->side[0] = quad->side[0];
1881       qCb->side[1] = quad->side[1];
1882       qCb->side[2] = sideCbCt;
1883       qCb->side[3] = sideLCb;
1884       qCb->side[1].to = dmin+1;
1885       // Make L quad
1886       FaceQuadStruct* qL = new FaceQuadStruct( quad->face, "L" );
1887       myQuadList.push_back( FaceQuadStruct::Ptr( qL ));
1888       qL->side.resize(4);
1889       qL->side[0] = sideLCb;
1890       qL->side[1] = sideLCt;
1891       qL->side[2] = quad->side[2];
1892       qL->side[3] = quad->side[3];
1893       qL->side[2].to = dmin+1;
1894       // Make Ct from the main quad
1895       FaceQuadStruct::Ptr qCt = quad;
1896       qCt->side[0] = sideCbCt;
1897       qCt->side[3] = sideLCt;
1898       qCt->side[1].from = dmin;
1899       qCt->side[2].from = dmin;
1900       qCt->uv_grid.clear();
1901       qCt->name = "Ct";
1902
1903       // Connect sides
1904       qCb->side[3].AddContact( dmin, & qCb->side[2], 0 );
1905       qCb->side[3].AddContact( dmin, & qCt->side[3], 0 );
1906       qCt->side[3].AddContact(    0, & qCt->side[0], 0 );
1907       qCt->side[0].AddContact(    0, & qL ->side[0], dmin );
1908       qL ->side[0].AddContact( dmin, & qL ->side[1], 0 );
1909       qL ->side[0].AddContact( dmin, & qCb->side[2], 0 );
1910
1911       if ( dh == dv )
1912         return computeQuadDominant( aMesh, aFace );
1913       else
1914         return computeQuadPref( aMesh, aFace, qCt );
1915
1916     } // if ( dv != 0 && dh != 0 )
1917
1918     const int db = quad->side[0].IsReversed() ? -1 : +1;
1919     const int dr = quad->side[1].IsReversed() ? -1 : +1;
1920     const int dt = quad->side[2].IsReversed() ? -1 : +1;
1921     const int dl = quad->side[3].IsReversed() ? -1 : +1;
1922
1923     // Case dv == 0,  here possibly myQuadList.size() > 1
1924     //
1925     //     lw   nb  lw = dh/2
1926     //    +------------+
1927     //    |   |    |   |
1928     //    |   | Ct |   |
1929     //    | L |    | R |
1930     //    |   |____|   |
1931     //    |  /      \  |
1932     //    | /   Cb   \ |
1933     //    |/          \|
1934     //    +------------+
1935     const int lw = dh/2; // lateral width
1936
1937     double yCbL, yCbR;
1938     {
1939       double   lL = quad->side[3].Length();
1940       double lLwL = quad->side[2].Length( tfrom,
1941                                           tfrom + ( lw ) * dt );
1942       yCbL = lLwL / ( lLwL + lL );
1943
1944       double   lR = quad->side[1].Length();
1945       double lLwR = quad->side[2].Length( tfrom + ( lw + nb-1 ) * dt,
1946                                           tfrom + ( lw + nb-1 + lw ) * dt);
1947       yCbR = lLwR / ( lLwR + lR );
1948     }
1949     // Make sides separating domains Cb and L and R
1950     StdMeshers_FaceSidePtr sideLCb, sideRCb;
1951     UVPtStruct pTBL, pTBR; // points where 3 domains meat
1952     {
1953       vector<UVPtStruct> pointsLCb( lw+1 ), pointsRCb( lw+1 );
1954       pointsLCb[0] = uv_eb[ 0    ];
1955       pointsRCb[0] = uv_eb[ nb-1 ];
1956       for ( int i = 1, i2 = nt-2; i <= lw; ++i, --i2 )
1957       {
1958         x  = quad->side[2].Param( i );
1959         y  = yCbL * i / lw;
1960         p0 = quad->side[0].Value2d( x );
1961         p1 = quad->side[1].Value2d( y );
1962         p2 = uv_et[ i ].UV();
1963         p3 = quad->side[3].Value2d( y );
1964         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1965         pointsLCb[ i ].u = uv.X();
1966         pointsLCb[ i ].v = uv.Y();
1967         pointsLCb[ i ].x = x;
1968
1969         x  = quad->side[2].Param( i2 );
1970         y  = yCbR * i / lw;
1971         p1 = quad->side[1].Value2d( y );
1972         p0 = quad->side[0].Value2d( x );
1973         p2 = uv_et[ i2 ].UV();
1974         p3 = quad->side[3].Value2d( y );
1975         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1976         pointsRCb[ i ].u = uv.X();
1977         pointsRCb[ i ].v = uv.Y();
1978         pointsRCb[ i ].x = x;
1979       }
1980       sideLCb = StdMeshers_FaceSide::New( pointsLCb, aFace );
1981       sideRCb = StdMeshers_FaceSide::New( pointsRCb, aFace );
1982       pTBL    = pointsLCb.back();
1983       pTBR    = pointsRCb.back();
1984     }
1985     // Make sides separating domains Ct and L and R
1986     StdMeshers_FaceSidePtr sideLCt, sideRCt;
1987     {
1988       vector<UVPtStruct> pointsLCt( nl ), pointsRCt( nl );
1989       pointsLCt[0]     = pTBL;
1990       pointsLCt.back() = uv_et[ lw ];
1991       pointsRCt[0]     = pTBR;
1992       pointsRCt.back() = uv_et[ lw + nb - 1 ];
1993       x  = pTBL.x;
1994       p0 = quad->side[0].Value2d( x );
1995       p2 = uv_et[ lw ].UV();
1996       int     iR = lw + nb - 1;
1997       double  xR = pTBR.x;
1998       gp_UV  p0R = quad->side[0].Value2d( xR );
1999       gp_UV  p2R = uv_et[ iR ].UV();
2000       for ( int i = 1; i < nl-1; ++i )
2001       {
2002         y  = yCbL + ( 1. - yCbL ) * i / (nl-1.);
2003         p1 = quad->side[1].Value2d( y );
2004         p3 = quad->side[3].Value2d( y );
2005         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
2006         pointsLCt[ i ].u = uv.X();
2007         pointsLCt[ i ].v = uv.Y();
2008
2009         y  = yCbR + ( 1. - yCbR ) * i / (nl-1.);
2010         p1 = quad->side[1].Value2d( y );
2011         p3 = quad->side[3].Value2d( y );
2012         uv = calcUV( xR,y, a0,a1,a2,a3, p0R,p1,p2R,p3 );
2013         pointsRCt[ i ].u = uv.X();
2014         pointsRCt[ i ].v = uv.Y();
2015       }
2016       sideLCt = StdMeshers_FaceSide::New( pointsLCt, aFace );
2017       sideRCt = StdMeshers_FaceSide::New( pointsRCt, aFace );
2018     }
2019     // Make a side separating domains Cb and Ct
2020     StdMeshers_FaceSidePtr sideCbCt;
2021     {
2022       vector<UVPtStruct> pointsCbCt( nb );
2023       pointsCbCt[0]     = pTBL;
2024       pointsCbCt.back() = pTBR;
2025       p1 = quad->side[1].Value2d( yCbR );
2026       p3 = quad->side[3].Value2d( yCbL );
2027       for ( int i = 1; i < nb-1; ++i )
2028       {
2029         x  = quad->side[2].Param( i + lw );
2030         y  = yCbL + ( yCbR - yCbL ) * i / (nb-1.);
2031         p2 = uv_et[ i + lw ].UV();
2032         p0 = quad->side[0].Value2d( x );
2033         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
2034         pointsCbCt[ i ].u = uv.X();
2035         pointsCbCt[ i ].v = uv.Y();
2036       }
2037       sideCbCt = StdMeshers_FaceSide::New( pointsCbCt, aFace );
2038     }
2039     // Make Cb quad
2040     FaceQuadStruct* qCb = new FaceQuadStruct( quad->face, "Cb" );
2041     myQuadList.push_back( FaceQuadStruct::Ptr( qCb ));
2042     qCb->side.resize(4);
2043     qCb->side[0] = quad->side[0];
2044     qCb->side[1] = sideRCb;
2045     qCb->side[2] = sideCbCt;
2046     qCb->side[3] = sideLCb;
2047     // Make L quad
2048     FaceQuadStruct* qL = new FaceQuadStruct( quad->face, "L" );
2049     myQuadList.push_back( FaceQuadStruct::Ptr( qL ));
2050     qL->side.resize(4);
2051     qL->side[0] = sideLCb;
2052     qL->side[1] = sideLCt;
2053     qL->side[2] = quad->side[2];
2054     qL->side[3] = quad->side[3];
2055     qL->side[2].to = ( lw + 1 ) * dt + tfrom;
2056     // Make R quad
2057     FaceQuadStruct* qR = new FaceQuadStruct( quad->face, "R" );
2058     myQuadList.push_back( FaceQuadStruct::Ptr( qR ));
2059     qR->side.resize(4);
2060     qR->side[0] = sideRCb;
2061     qR->side[0].from = lw;
2062     qR->side[0].to   = -1;
2063     qR->side[0].di   = -1;
2064     qR->side[1] = quad->side[1];
2065     qR->side[2] = quad->side[2];
2066     qR->side[2].from = ( lw + nb-1 ) * dt + tfrom;
2067     qR->side[3] = sideRCt;
2068     // Make Ct from the main quad
2069     FaceQuadStruct::Ptr qCt = quad;
2070     qCt->side[0] = sideCbCt;
2071     qCt->side[1] = sideRCt;
2072     qCt->side[2].from = ( lw ) * dt + tfrom;
2073     qCt->side[2].to   = ( lw + nb ) * dt + tfrom;
2074     qCt->side[3] = sideLCt;
2075     qCt->uv_grid.clear();
2076     qCt->name = "Ct";
2077
2078     // Connect sides
2079     qCb->side[3].AddContact( lw, & qCb->side[2], 0 );
2080     qCb->side[3].AddContact( lw, & qCt->side[3], 0 );
2081     qCt->side[3].AddContact( 0,  & qCt->side[0], 0 );
2082     qCt->side[0].AddContact( 0,  & qL ->side[0], lw );
2083     qL ->side[0].AddContact( lw, & qL ->side[1], 0 );
2084     qL ->side[0].AddContact( lw, & qCb->side[2], 0 );
2085     //
2086     qCb->side[1].AddContact( lw,   & qCb->side[2], nb-1 );
2087     qCb->side[1].AddContact( lw,   & qCt->side[1], 0 );
2088     qCt->side[0].AddContact( nb-1, & qCt->side[1], 0 );
2089     qCt->side[0].AddContact( nb-1, & qR ->side[0], lw );
2090     qR ->side[3].AddContact( 0,    & qR ->side[0], lw );
2091     qR ->side[3].AddContact( 0,    & qCb->side[2], nb-1 );
2092
2093     return computeQuadDominant( aMesh, aFace );
2094
2095   } // if ( !myForcedPnts.empty() )
2096
2097   if ( dh > dv ) {
2098     addv = (dh-dv)/2;
2099     nbv  = nbv + addv;
2100   }
2101   else { // dv >= dh
2102     addh = (dv-dh)/2;
2103     nbh  = nbh + addh;
2104   }
2105
2106   // arrays for normalized params
2107   TColStd_SequenceOfReal npb, npr, npt, npl;
2108   for (i=0; i<nb; i++) {
2109     npb.Append(uv_eb[i].normParam);
2110   }
2111   for (i=0; i<nr; i++) {
2112     npr.Append(uv_er[i].normParam);
2113   }
2114   for (i=0; i<nt; i++) {
2115     npt.Append(uv_et[i].normParam);
2116   }
2117   for (i=0; i<nl; i++) {
2118     npl.Append(uv_el[i].normParam);
2119   }
2120
2121   int dl,dr;
2122   if (OldVersion) {
2123     // add some params to right and left after the first param
2124     // insert to right
2125     dr = nbv - nr;
2126     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
2127     for (i=1; i<=dr; i++) {
2128       npr.InsertAfter(1,npr.Value(2)-dpr);
2129     }
2130     // insert to left
2131     dl = nbv - nl;
2132     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
2133     for (i=1; i<=dl; i++) {
2134       npl.InsertAfter(1,npl.Value(2)-dpr);
2135     }
2136   }
2137
2138   int nnn = Min(nr,nl);
2139   // auxilary sequence of XY for creation nodes
2140   // in the bottom part of central domain
2141   // Length of UVL and UVR must be == nbv-nnn
2142   TColgp_SequenceOfXY UVL, UVR, UVT;
2143
2144   if (OldVersion) {
2145     // step1: create faces for left domain
2146     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
2147     // add left nodes
2148     for (j=1; j<=nl; j++)
2149       NodesL.SetValue(1,j,uv_el[j-1].node);
2150     if (dl>0) {
2151       // add top nodes
2152       for (i=1; i<=dl; i++)
2153         NodesL.SetValue(i+1,nl,uv_et[i].node);
2154       // create and add needed nodes
2155       TColgp_SequenceOfXY UVtmp;
2156       for (i=1; i<=dl; i++) {
2157         double x0 = npt.Value(i+1);
2158         double x1 = x0;
2159         // diagonal node
2160         double y0 = npl.Value(i+1);
2161         double y1 = npr.Value(i+1);
2162         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2163         gp_Pnt P = S->Value(UV.X(),UV.Y());
2164         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2165         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2166         NodesL.SetValue(i+1,1,N);
2167         if (UVL.Length()<nbv-nnn) UVL.Append(UV);
2168         // internal nodes
2169         for (j=2; j<nl; j++) {
2170           double y0 = npl.Value(dl+j);
2171           double y1 = npr.Value(dl+j);
2172           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2173           gp_Pnt P = S->Value(UV.X(),UV.Y());
2174           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2175           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2176           NodesL.SetValue(i+1,j,N);
2177           if (i==dl) UVtmp.Append(UV);
2178         }
2179       }
2180       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn; i++) {
2181         UVL.Append(UVtmp.Value(i));
2182       }
2183       // create faces
2184       for (i=1; i<=dl; i++) {
2185         for (j=1; j<nl; j++) {
2186           if (WisF) {
2187             SMDS_MeshFace* F =
2188               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
2189                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
2190             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2191           }
2192         }
2193       }
2194     }
2195     else {
2196       // fill UVL using c2d
2197       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn; i++) {
2198         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
2199       }
2200     }
2201
2202     // step2: create faces for right domain
2203     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
2204     // add right nodes
2205     for (j=1; j<=nr; j++)
2206       NodesR.SetValue(1,j,uv_er[nr-j].node);
2207     if (dr>0) {
2208       // add top nodes
2209       for (i=1; i<=dr; i++)
2210         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
2211       // create and add needed nodes
2212       TColgp_SequenceOfXY UVtmp;
2213       for (i=1; i<=dr; i++) {
2214         double x0 = npt.Value(nt-i);
2215         double x1 = x0;
2216         // diagonal node
2217         double y0 = npl.Value(i+1);
2218         double y1 = npr.Value(i+1);
2219         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2220         gp_Pnt P = S->Value(UV.X(),UV.Y());
2221         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2222         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2223         NodesR.SetValue(i+1,nr,N);
2224         if (UVR.Length()<nbv-nnn) UVR.Append(UV);
2225         // internal nodes
2226         for (j=2; j<nr; j++) {
2227           double y0 = npl.Value(nbv-j+1);
2228           double y1 = npr.Value(nbv-j+1);
2229           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2230           gp_Pnt P = S->Value(UV.X(),UV.Y());
2231           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2232           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2233           NodesR.SetValue(i+1,j,N);
2234           if (i==dr) UVtmp.Prepend(UV);
2235         }
2236       }
2237       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn; i++) {
2238         UVR.Append(UVtmp.Value(i));
2239       }
2240       // create faces
2241       for (i=1; i<=dr; i++) {
2242         for (j=1; j<nr; j++) {
2243           if (WisF) {
2244             SMDS_MeshFace* F =
2245               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
2246                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
2247             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2248           }
2249         }
2250       }
2251     }
2252     else {
2253       // fill UVR using c2d
2254       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn; i++) {
2255         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
2256       }
2257     }
2258
2259     // step3: create faces for central domain
2260     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
2261     // add first line using NodesL
2262     for (i=1; i<=dl+1; i++)
2263       NodesC.SetValue(1,i,NodesL(i,1));
2264     for (i=2; i<=nl; i++)
2265       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
2266     // add last line using NodesR
2267     for (i=1; i<=dr+1; i++)
2268       NodesC.SetValue(nb,i,NodesR(i,nr));
2269     for (i=1; i<nr; i++)
2270       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
2271     // add top nodes (last columns)
2272     for (i=dl+2; i<nbh-dr; i++)
2273       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
2274     // add bottom nodes (first columns)
2275     for (i=2; i<nb; i++)
2276       NodesC.SetValue(i,1,uv_eb[i-1].node);
2277
2278     // create and add needed nodes
2279     // add linear layers
2280     for (i=2; i<nb; i++) {
2281       double x0 = npt.Value(dl+i);
2282       double x1 = x0;
2283       for (j=1; j<nnn; j++) {
2284         double y0 = npl.Value(nbv-nnn+j);
2285         double y1 = npr.Value(nbv-nnn+j);
2286         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2287         gp_Pnt P = S->Value(UV.X(),UV.Y());
2288         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2289         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2290         NodesC.SetValue(i,nbv-nnn+j,N);
2291         if ( j==1 )
2292           UVT.Append( UV );
2293       }
2294     }
2295     // add diagonal layers
2296     gp_UV A2 = UVR.Value(nbv-nnn);
2297     gp_UV A3 = UVL.Value(nbv-nnn);
2298     for (i=1; i<nbv-nnn; i++) {
2299       gp_UV p1 = UVR.Value(i);
2300       gp_UV p3 = UVL.Value(i);
2301       double y = i / double(nbv-nnn);
2302       for (j=2; j<nb; j++) {
2303         double x = npb.Value(j);
2304         gp_UV p0( uv_eb[j-1].u, uv_eb[j-1].v );
2305         gp_UV p2 = UVT.Value( j-1 );
2306         gp_UV UV = calcUV(x, y, a0, a1, A2, A3, p0,p1,p2,p3 );
2307         gp_Pnt P = S->Value(UV.X(),UV.Y());
2308         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2309         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
2310         NodesC.SetValue(j,i+1,N);
2311       }
2312     }
2313     // create faces
2314     for (i=1; i<nb; i++) {
2315       for (j=1; j<nbv; j++) {
2316         if (WisF) {
2317           SMDS_MeshFace* F =
2318             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2319                               NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2320           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2321         }
2322       }
2323     }
2324   }
2325
2326   else { // New version (!OldVersion)
2327     // step1: create faces for bottom rectangle domain
2328     StdMeshers_Array2OfNode NodesBRD(1,nb,1,nnn-1);
2329     // fill UVL and UVR using c2d
2330     for (j=0; j<nb; j++) {
2331       NodesBRD.SetValue(j+1,1,uv_eb[j].node);
2332     }
2333     for (i=1; i<nnn-1; i++) {
2334       NodesBRD.SetValue(1,i+1,uv_el[i].node);
2335       NodesBRD.SetValue(nb,i+1,uv_er[i].node);
2336       for (j=2; j<nb; j++) {
2337         double x = npb.Value(j);
2338         double y = (1-x) * npl.Value(i+1) + x * npr.Value(i+1);
2339         gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2340         gp_Pnt P = S->Value(UV.X(),UV.Y());
2341         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2342         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
2343         NodesBRD.SetValue(j,i+1,N);
2344       }
2345     }
2346     for (j=1; j<nnn-1; j++) {
2347       for (i=1; i<nb; i++) {
2348         if (WisF) {
2349           SMDS_MeshFace* F =
2350             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i+1,j),
2351                               NodesBRD.Value(i+1,j+1), NodesBRD.Value(i,j+1));
2352           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2353         }
2354       }
2355     }
2356     int drl = abs(nr-nl);
2357     // create faces for region C
2358     StdMeshers_Array2OfNode NodesC(1,nb,1,drl+1+addv);
2359     // add nodes from previous region
2360     for (j=1; j<=nb; j++) {
2361       NodesC.SetValue(j,1,NodesBRD.Value(j,nnn-1));
2362     }
2363     if ((drl+addv) > 0) {
2364       int n1,n2;
2365       if (nr>nl) {
2366         n1 = 1;
2367         n2 = drl + 1;
2368         TColgp_SequenceOfXY UVtmp;
2369         double drparam = npr.Value(nr) - npr.Value(nnn-1);
2370         double dlparam = npl.Value(nnn) - npl.Value(nnn-1);
2371         double y0,y1;
2372         for (i=1; i<=drl; i++) {
2373           // add existed nodes from right edge
2374           NodesC.SetValue(nb,i+1,uv_er[nnn+i-2].node);
2375           //double dtparam = npt.Value(i+1);
2376           y1 = npr.Value(nnn+i-1); // param on right edge
2377           double dpar = (y1 - npr.Value(nnn-1))/drparam;
2378           y0 = npl.Value(nnn-1) + dpar*dlparam; // param on left edge
2379           double dy = y1 - y0;
2380           for (j=1; j<nb; j++) {
2381             double x = npt.Value(i+1) + npb.Value(j)*(1-npt.Value(i+1));
2382             double y = y0 + dy*x;
2383             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2384             gp_Pnt P = S->Value(UV.X(),UV.Y());
2385             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2386             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2387             NodesC.SetValue(j,i+1,N);
2388           }
2389         }
2390         double dy0 = (1-y0)/(addv+1);
2391         double dy1 = (1-y1)/(addv+1);
2392         for (i=1; i<=addv; i++) {
2393           double yy0 = y0 + dy0*i;
2394           double yy1 = y1 + dy1*i;
2395           double dyy = yy1 - yy0;
2396           for (j=1; j<=nb; j++) {
2397             double x = npt.Value(i+1+drl) +
2398               npb.Value(j) * (npt.Value(nt-i) - npt.Value(i+1+drl));
2399             double y = yy0 + dyy*x;
2400             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2401             gp_Pnt P = S->Value(UV.X(),UV.Y());
2402             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2403             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2404             NodesC.SetValue(j,i+drl+1,N);
2405           }
2406         }
2407       }
2408       else { // nr<nl
2409         n2 = 1;
2410         n1 = drl + 1;
2411         TColgp_SequenceOfXY UVtmp;
2412         double dlparam = npl.Value(nl) - npl.Value(nnn-1);
2413         double drparam = npr.Value(nnn) - npr.Value(nnn-1);
2414         double y0 = npl.Value(nnn-1);
2415         double y1 = npr.Value(nnn-1);
2416         for (i=1; i<=drl; i++) {
2417           // add existed nodes from right edge
2418           NodesC.SetValue(1,i+1,uv_el[nnn+i-2].node);
2419           y0 = npl.Value(nnn+i-1); // param on left edge
2420           double dpar = (y0 - npl.Value(nnn-1))/dlparam;
2421           y1 = npr.Value(nnn-1) + dpar*drparam; // param on right edge
2422           double dy = y1 - y0;
2423           for (j=2; j<=nb; j++) {
2424             double x = npb.Value(j)*npt.Value(nt-i);
2425             double y = y0 + dy*x;
2426             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2427             gp_Pnt P = S->Value(UV.X(),UV.Y());
2428             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2429             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2430             NodesC.SetValue(j,i+1,N);
2431           }
2432         }
2433         double dy0 = (1-y0)/(addv+1);
2434         double dy1 = (1-y1)/(addv+1);
2435         for (i=1; i<=addv; i++) {
2436           double yy0 = y0 + dy0*i;
2437           double yy1 = y1 + dy1*i;
2438           double dyy = yy1 - yy0;
2439           for (j=1; j<=nb; j++) {
2440             double x = npt.Value(i+1) +
2441               npb.Value(j) * (npt.Value(nt-i-drl) - npt.Value(i+1));
2442             double y = yy0 + dyy*x;
2443             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2444             gp_Pnt P = S->Value(UV.X(),UV.Y());
2445             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2446             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2447             NodesC.SetValue(j,i+drl+1,N);
2448           }
2449         }
2450       }
2451       // create faces
2452       for (j=1; j<=drl+addv; j++) {
2453         for (i=1; i<nb; i++) {
2454           if (WisF) {
2455             SMDS_MeshFace* F =
2456               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2457                                 NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2458             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2459           }
2460         }
2461       } // end nr<nl
2462
2463       StdMeshers_Array2OfNode NodesLast(1,nt,1,2);
2464       for (i=1; i<=nt; i++) {
2465         NodesLast.SetValue(i,2,uv_et[i-1].node);
2466       }
2467       int nnn=0;
2468       for (i=n1; i<drl+addv+1; i++) {
2469         nnn++;
2470         NodesLast.SetValue(nnn,1,NodesC.Value(1,i));
2471       }
2472       for (i=1; i<=nb; i++) {
2473         nnn++;
2474         NodesLast.SetValue(nnn,1,NodesC.Value(i,drl+addv+1));
2475       }
2476       for (i=drl+addv; i>=n2; i--) {
2477         nnn++;
2478         NodesLast.SetValue(nnn,1,NodesC.Value(nb,i));
2479       }
2480       for (i=1; i<nt; i++) {
2481         if (WisF) {
2482           SMDS_MeshFace* F =
2483             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i+1,1),
2484                               NodesLast.Value(i+1,2), NodesLast.Value(i,2));
2485           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2486         }
2487       }
2488     } // if ((drl+addv) > 0)
2489
2490   } // end new version implementation
2491
2492   bool isOk = true;
2493   return isOk;
2494 }
2495
2496
2497 //=======================================================================
2498 /*!
2499  * Evaluate only quandrangle faces
2500  */
2501 //=======================================================================
2502
2503 bool StdMeshers_Quadrangle_2D::evaluateQuadPref(SMESH_Mesh &        aMesh,
2504                                                 const TopoDS_Shape& aShape,
2505                                                 std::vector<int>&   aNbNodes,
2506                                                 MapShapeNbElems&    aResMap,
2507                                                 bool                IsQuadratic)
2508 {
2509   // Auxilary key in order to keep old variant
2510   // of meshing after implementation new variant
2511   // for bug 0016220 from Mantis.
2512   bool OldVersion = false;
2513   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
2514     OldVersion = true;
2515
2516   const TopoDS_Face& F = TopoDS::Face(aShape);
2517   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
2518
2519   int nb = aNbNodes[0];
2520   int nr = aNbNodes[1];
2521   int nt = aNbNodes[2];
2522   int nl = aNbNodes[3];
2523   int dh = abs(nb-nt);
2524   int dv = abs(nr-nl);
2525
2526   if (dh>=dv) {
2527     if (nt>nb) {
2528       // it is a base case => not shift 
2529     }
2530     else {
2531       // we have to shift on 2
2532       nb = aNbNodes[2];
2533       nr = aNbNodes[3];
2534       nt = aNbNodes[0];
2535       nl = aNbNodes[1];
2536     }
2537   }
2538   else {
2539     if (nr>nl) {
2540       // we have to shift quad on 1
2541       nb = aNbNodes[3];
2542       nr = aNbNodes[0];
2543       nt = aNbNodes[1];
2544       nl = aNbNodes[2];
2545     }
2546     else {
2547       // we have to shift quad on 3
2548       nb = aNbNodes[1];
2549       nr = aNbNodes[2];
2550       nt = aNbNodes[3];
2551       nl = aNbNodes[0];
2552     }
2553   }
2554
2555   dh = abs(nb-nt);
2556   dv = abs(nr-nl);
2557   int nbh  = Max(nb,nt);
2558   int nbv = Max(nr,nl);
2559   int addh = 0;
2560   int addv = 0;
2561
2562   if (dh>dv) {
2563     addv = (dh-dv)/2;
2564     nbv = nbv + addv;
2565   }
2566   else { // dv>=dh
2567     addh = (dv-dh)/2;
2568     nbh = nbh + addh;
2569   }
2570
2571   int dl,dr;
2572   if (OldVersion) {
2573     // add some params to right and left after the first param
2574     // insert to right
2575     dr = nbv - nr;
2576     // insert to left
2577     dl = nbv - nl;
2578   }
2579   
2580   int nnn = Min(nr,nl);
2581
2582   int nbNodes = 0;
2583   int nbFaces = 0;
2584   if (OldVersion) {
2585     // step1: create faces for left domain
2586     if (dl>0) {
2587       nbNodes += dl*(nl-1);
2588       nbFaces += dl*(nl-1);
2589     }
2590     // step2: create faces for right domain
2591     if (dr>0) {
2592       nbNodes += dr*(nr-1);
2593       nbFaces += dr*(nr-1);
2594     }
2595     // step3: create faces for central domain
2596     nbNodes += (nb-2)*(nnn-1) + (nbv-nnn-1)*(nb-2);
2597     nbFaces += (nb-1)*(nbv-1);
2598   }
2599   else { // New version (!OldVersion)
2600     nbNodes += (nnn-2)*(nb-2);
2601     nbFaces += (nnn-2)*(nb-1);
2602     int drl = abs(nr-nl);
2603     nbNodes += drl*(nb-1) + addv*nb;
2604     nbFaces += (drl+addv)*(nb-1) + (nt-1);
2605   } // end new version implementation
2606
2607   std::vector<int> aVec(SMDSEntity_Last);
2608   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
2609   if (IsQuadratic) {
2610     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces;
2611     aVec[SMDSEntity_Node] = nbNodes + nbFaces*4;
2612     if (aNbNodes.size()==5) {
2613       aVec[SMDSEntity_Quad_Triangle] = aNbNodes[3] - 1;
2614       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2615     }
2616   }
2617   else {
2618     aVec[SMDSEntity_Node] = nbNodes;
2619     aVec[SMDSEntity_Quadrangle] = nbFaces;
2620     if (aNbNodes.size()==5) {
2621       aVec[SMDSEntity_Triangle] = aNbNodes[3] - 1;
2622       aVec[SMDSEntity_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2623     }
2624   }
2625   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
2626   aResMap.insert(std::make_pair(sm,aVec));
2627
2628   return true;
2629 }
2630
2631 //=============================================================================
2632 /*! Split quadrangle in to 2 triangles by smallest diagonal
2633  *   
2634  */
2635 //=============================================================================
2636
2637 void StdMeshers_Quadrangle_2D::splitQuadFace(SMESHDS_Mesh *       theMeshDS,
2638                                              int                  theFaceID,
2639                                              const SMDS_MeshNode* theNode1,
2640                                              const SMDS_MeshNode* theNode2,
2641                                              const SMDS_MeshNode* theNode3,
2642                                              const SMDS_MeshNode* theNode4)
2643 {
2644   SMDS_MeshFace* face;
2645   if ( SMESH_TNodeXYZ( theNode1 ).SquareDistance( theNode3 ) >
2646        SMESH_TNodeXYZ( theNode2 ).SquareDistance( theNode4 ) )
2647   {
2648     face = myHelper->AddFace(theNode2, theNode4 , theNode1);
2649     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2650     face = myHelper->AddFace(theNode2, theNode3, theNode4);
2651     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2652   }
2653   else
2654   {
2655     face = myHelper->AddFace(theNode1, theNode2 ,theNode3);
2656     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2657     face = myHelper->AddFace(theNode1, theNode3, theNode4);
2658     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2659   }
2660 }
2661
2662 namespace
2663 {
2664   enum uvPos { UV_A0, UV_A1, UV_A2, UV_A3, UV_B, UV_R, UV_T, UV_L, UV_SIZE };
2665
2666   inline  SMDS_MeshNode* makeNode( UVPtStruct &         uvPt,
2667                                    const double         y,
2668                                    FaceQuadStruct::Ptr& quad,
2669                                    const gp_UV*         UVs,
2670                                    SMESH_MesherHelper*  helper,
2671                                    Handle(Geom_Surface) S)
2672   {
2673     const vector<UVPtStruct>& uv_eb = quad->side[QUAD_BOTTOM_SIDE].GetUVPtStruct();
2674     const vector<UVPtStruct>& uv_et = quad->side[QUAD_TOP_SIDE   ].GetUVPtStruct();
2675     double rBot = ( uv_eb.size() - 1 ) * uvPt.normParam;
2676     double rTop = ( uv_et.size() - 1 ) * uvPt.normParam;
2677     int iBot = int( rBot );
2678     int iTop = int( rTop );
2679     double xBot = uv_eb[ iBot ].normParam + ( rBot - iBot ) * ( uv_eb[ iBot+1 ].normParam - uv_eb[ iBot ].normParam );
2680     double xTop = uv_et[ iTop ].normParam + ( rTop - iTop ) * ( uv_et[ iTop+1 ].normParam - uv_et[ iTop ].normParam );
2681     double x = xBot + y * ( xTop - xBot );
2682     
2683     gp_UV uv = calcUV(/*x,y=*/x, y,
2684                       /*a0,...=*/UVs[UV_A0], UVs[UV_A1], UVs[UV_A2], UVs[UV_A3],
2685                       /*p0=*/quad->side[QUAD_BOTTOM_SIDE].grid->Value2d( x ).XY(),
2686                       /*p1=*/UVs[ UV_R ],
2687                       /*p2=*/quad->side[QUAD_TOP_SIDE   ].grid->Value2d( x ).XY(),
2688                       /*p3=*/UVs[ UV_L ]);
2689     gp_Pnt P = S->Value( uv.X(), uv.Y() );
2690     uvPt.u = uv.X();
2691     uvPt.v = uv.Y();
2692     return helper->AddNode(P.X(), P.Y(), P.Z(), 0, uv.X(), uv.Y() );
2693   }
2694
2695   void reduce42( const vector<UVPtStruct>& curr_base,
2696                  vector<UVPtStruct>&       next_base,
2697                  const int                 j,
2698                  int &                     next_base_len,
2699                  FaceQuadStruct::Ptr&      quad,
2700                  gp_UV*                    UVs,
2701                  const double              y,
2702                  SMESH_MesherHelper*       helper,
2703                  Handle(Geom_Surface)&     S)
2704   {
2705     // add one "HH": nodes a,b,c,d,e and faces 1,2,3,4,5,6
2706     //
2707     //  .-----a-----b i + 1
2708     //  |\ 5  | 6  /|
2709     //  | \   |   / |
2710     //  |  c--d--e  |
2711     //  |1 |2 |3 |4 |
2712     //  |  |  |  |  |
2713     //  .--.--.--.--. i
2714     //
2715     //  j     j+2   j+4
2716
2717     // a (i + 1, j + 2)
2718     const SMDS_MeshNode*& Na = next_base[ ++next_base_len ].node;
2719     if ( !Na )
2720       Na = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2721
2722     // b (i + 1, j + 4)
2723     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2724     if ( !Nb )
2725       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2726
2727     // c
2728     double u = (curr_base[j + 2].u + next_base[next_base_len - 2].u) / 2.0;
2729     double v = (curr_base[j + 2].v + next_base[next_base_len - 2].v) / 2.0;
2730     gp_Pnt P = S->Value(u,v);
2731     SMDS_MeshNode* Nc = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2732
2733     // d
2734     u = (curr_base[j + 2].u + next_base[next_base_len - 1].u) / 2.0;
2735     v = (curr_base[j + 2].v + next_base[next_base_len - 1].v) / 2.0;
2736     P = S->Value(u,v);
2737     SMDS_MeshNode* Nd = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2738
2739     // e
2740     u = (curr_base[j + 2].u + next_base[next_base_len].u) / 2.0;
2741     v = (curr_base[j + 2].v + next_base[next_base_len].v) / 2.0;
2742     P = S->Value(u,v);
2743     SMDS_MeshNode* Ne = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2744
2745     // Faces
2746     helper->AddFace(curr_base[j + 0].node,
2747                     curr_base[j + 1].node, Nc,
2748                     next_base[next_base_len - 2].node);
2749
2750     helper->AddFace(curr_base[j + 1].node,
2751                     curr_base[j + 2].node, Nd, Nc);
2752
2753     helper->AddFace(curr_base[j + 2].node,
2754                     curr_base[j + 3].node, Ne, Nd);
2755
2756     helper->AddFace(curr_base[j + 3].node,
2757                     curr_base[j + 4].node, Nb, Ne);
2758
2759     helper->AddFace(Nc, Nd, Na, next_base[next_base_len - 2].node);
2760
2761     helper->AddFace(Nd, Ne, Nb, Na);
2762   }
2763
2764   void reduce31( const vector<UVPtStruct>& curr_base,
2765                  vector<UVPtStruct>&       next_base,
2766                  const int                 j,
2767                  int &                     next_base_len,
2768                  FaceQuadStruct::Ptr&      quad,
2769                  gp_UV*                    UVs,
2770                  const double              y,
2771                  SMESH_MesherHelper*       helper,
2772                  Handle(Geom_Surface)&     S)
2773   {
2774     // add one "H": nodes b,c,e and faces 1,2,4,5
2775     //
2776     //  .---------b i + 1
2777     //  |\   5   /|
2778     //  | \     / |
2779     //  |  c---e  |
2780     //  |1 |2  |4 |
2781     //  |  |   |  |
2782     //  .--.---.--. i
2783     //
2784     //  j j+1 j+2 j+3
2785
2786     // b (i + 1, j + 3)
2787     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2788     if ( !Nb )
2789       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2790
2791     // c and e
2792     double u1 = (curr_base[ j   ].u + next_base[ next_base_len-1 ].u ) / 2.0;
2793     double u2 = (curr_base[ j+3 ].u + next_base[ next_base_len   ].u ) / 2.0;
2794     double u3 = (u2 - u1) / 3.0;
2795     //
2796     double v1 = (curr_base[ j   ].v + next_base[ next_base_len-1 ].v ) / 2.0;
2797     double v2 = (curr_base[ j+3 ].v + next_base[ next_base_len   ].v ) / 2.0;
2798     double v3 = (v2 - v1) / 3.0;
2799     // c
2800     double u = u1 + u3;
2801     double v = v1 + v3;
2802     gp_Pnt P = S->Value(u,v);
2803     SMDS_MeshNode* Nc = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2804     // e
2805     u = u1 + u3 + u3;
2806     v = v1 + v3 + v3;
2807     P = S->Value(u,v);
2808     SMDS_MeshNode* Ne = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2809
2810     // Faces
2811     // 1
2812     helper->AddFace( curr_base[ j + 0 ].node,
2813                      curr_base[ j + 1 ].node,
2814                      Nc,
2815                      next_base[ next_base_len - 1 ].node);
2816     // 2
2817     helper->AddFace( curr_base[ j + 1 ].node,
2818                      curr_base[ j + 2 ].node, Ne, Nc);
2819     // 4
2820     helper->AddFace( curr_base[ j + 2 ].node,
2821                      curr_base[ j + 3 ].node, Nb, Ne);
2822     // 5
2823     helper->AddFace(Nc, Ne, Nb,
2824                     next_base[ next_base_len - 1 ].node);
2825   }
2826
2827   typedef void (* PReduceFunction) ( const vector<UVPtStruct>& curr_base,
2828                                      vector<UVPtStruct>&       next_base,
2829                                      const int                 j,
2830                                      int &                     next_base_len,
2831                                      FaceQuadStruct::Ptr &     quad,
2832                                      gp_UV*                    UVs,
2833                                      const double              y,
2834                                      SMESH_MesherHelper*       helper,
2835                                      Handle(Geom_Surface)&     S);
2836
2837 } // namespace
2838
2839 //=======================================================================
2840 /*!
2841  *  Implementation of Reduced algorithm (meshing with quadrangles only)
2842  */
2843 //=======================================================================
2844
2845 bool StdMeshers_Quadrangle_2D::computeReduced (SMESH_Mesh &        aMesh,
2846                                                const TopoDS_Face&  aFace,
2847                                                FaceQuadStruct::Ptr quad)
2848 {
2849   SMESHDS_Mesh * meshDS  = aMesh.GetMeshDS();
2850   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
2851   int i,j,geomFaceID     = meshDS->ShapeToIndex(aFace);
2852
2853   int nb = quad->side[0].NbPoints(); // bottom
2854   int nr = quad->side[1].NbPoints(); // right
2855   int nt = quad->side[2].NbPoints(); // top
2856   int nl = quad->side[3].NbPoints(); // left
2857
2858   //  Simple Reduce 10->8->6->4 (3 steps)     Multiple Reduce 10->4 (1 step)
2859   //
2860   //  .-----.-----.-----.-----.               .-----.-----.-----.-----.
2861   //  |    / \    |    / \    |               |    / \    |    / \    |
2862   //  |   /    .--.--.    \   |               |    / \    |    / \    |
2863   //  |   /   /   |   \   \   |               |   /  .----.----.  \   |
2864   //  .---.---.---.---.---.---.               |   / / \   |   / \ \   |
2865   //  |   /  / \  |  / \  \   |               |   / / \   |   / \ \   |
2866   //  |  /  /   .-.-.   \  \  |               |  / /  .---.---.  \ \  |
2867   //  |  /  /  /  |  \  \  \  |               |  / / / \  |  / \ \ \  |
2868   //  .--.--.--.--.--.--.--.--.               |  / / /  \ | /  \ \ \  |
2869   //  |  / /  / \ | / \  \ \  |               | / / /   .-.-.   \ \ \ |
2870   //  | / /  /  .-.-.  \  \ \ |               | / / /  /  |  \  \ \ \ |
2871   //  | / / /  /  |  \  \ \ \ |               | / / /  /  |  \  \ \ \ |
2872   //  .-.-.-.--.--.--.--.-.-.-.               .-.-.-.--.--.--.--.-.-.-.
2873
2874   bool MultipleReduce = false;
2875   {
2876     int nb1 = nb;
2877     int nr1 = nr;
2878     int nt1 = nt;
2879
2880     if (nr == nl) {
2881       if (nb < nt) {
2882         nt1 = nb;
2883         nb1 = nt;
2884       }
2885     }
2886     else if (nb == nt) {
2887       nr1 = nb; // and == nt
2888       if (nl < nr) {
2889         nt1 = nl;
2890         nb1 = nr;
2891       }
2892       else {
2893         nt1 = nr;
2894         nb1 = nl;
2895       }
2896     }
2897     else {
2898       return false;
2899     }
2900
2901     // number of rows and columns
2902     int nrows    = nr1 - 1;
2903     int ncol_top = nt1 - 1;
2904     int ncol_bot = nb1 - 1;
2905     // number of rows needed to reduce ncol_bot to ncol_top using simple 3->1 "tree" (see below)
2906     int nrows_tree31 =
2907       int( ceil( log( double(ncol_bot) / ncol_top) / log( 3.))); // = log x base 3
2908     if ( nrows < nrows_tree31 )
2909     {
2910       MultipleReduce = true;
2911       error( COMPERR_WARNING,
2912              SMESH_Comment("To use 'Reduced' transition, "
2913                            "number of face rows should be at least ")
2914              << nrows_tree31 << ". Actual number of face rows is " << nrows << ". "
2915              "'Quadrangle preference (reversed)' transion has been used.");
2916     }
2917   }
2918
2919   if (MultipleReduce) { // == computeQuadPref QUAD_QUADRANGLE_PREF_REVERSED
2920     //==================================================
2921     int dh = abs(nb-nt);
2922     int dv = abs(nr-nl);
2923
2924     if (dh >= dv) {
2925       if (nt > nb) {
2926         // it is a base case => not shift quad but may be replacement is need
2927         shiftQuad(quad,0);
2928       }
2929       else {
2930         // we have to shift quad on 2
2931         shiftQuad(quad,2);
2932       }
2933     }
2934     else {
2935       if (nr > nl) {
2936         // we have to shift quad on 1
2937         shiftQuad(quad,1);
2938       }
2939       else {
2940         // we have to shift quad on 3
2941         shiftQuad(quad,3);
2942       }
2943     }
2944
2945     nb = quad->side[0].NbPoints();
2946     nr = quad->side[1].NbPoints();
2947     nt = quad->side[2].NbPoints();
2948     nl = quad->side[3].NbPoints();
2949     dh = abs(nb-nt);
2950     dv = abs(nr-nl);
2951     int nbh = Max(nb,nt);
2952     int nbv = Max(nr,nl);
2953     int addh = 0;
2954     int addv = 0;
2955
2956     if (dh>dv) {
2957       addv = (dh-dv)/2;
2958       nbv = nbv + addv;
2959     }
2960     else { // dv>=dh
2961       addh = (dv-dh)/2;
2962       nbh = nbh + addh;
2963     }
2964
2965     const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
2966     const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
2967     const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
2968     const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
2969
2970     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2971       return error(COMPERR_BAD_INPUT_MESH);
2972
2973     // arrays for normalized params
2974     TColStd_SequenceOfReal npb, npr, npt, npl;
2975     for (j = 0; j < nb; j++) {
2976       npb.Append(uv_eb[j].normParam);
2977     }
2978     for (i = 0; i < nr; i++) {
2979       npr.Append(uv_er[i].normParam);
2980     }
2981     for (j = 0; j < nt; j++) {
2982       npt.Append(uv_et[j].normParam);
2983     }
2984     for (i = 0; i < nl; i++) {
2985       npl.Append(uv_el[i].normParam);
2986     }
2987
2988     int dl,dr;
2989     // orientation of face and 3 main domain for future faces
2990     //       0   top    1
2991     //      1------------1
2992     //       |   |  |   |
2993     //       |   |  |   |
2994     //       | L |  | R |
2995     //  left |   |  |   | rigth
2996     //       |  /    \  |
2997     //       | /  C   \ |
2998     //       |/        \|
2999     //      0------------0
3000     //       0  bottom  1
3001
3002     // add some params to right and left after the first param
3003     // insert to right
3004     dr = nbv - nr;
3005     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
3006     for (i=1; i<=dr; i++) {
3007       npr.InsertAfter(1,npr.Value(2)-dpr);
3008     }
3009     // insert to left
3010     dl = nbv - nl;
3011     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
3012     for (i=1; i<=dl; i++) {
3013       npl.InsertAfter(1,npl.Value(2)-dpr);
3014     }
3015   
3016     gp_XY a0 (uv_eb.front().u, uv_eb.front().v);
3017     gp_XY a1 (uv_eb.back().u,  uv_eb.back().v);
3018     gp_XY a2 (uv_et.back().u,  uv_et.back().v);
3019     gp_XY a3 (uv_et.front().u, uv_et.front().v);
3020
3021     int nnn = Min(nr,nl);
3022     // auxilary sequence of XY for creation of nodes
3023     // in the bottom part of central domain
3024     // it's length must be == nbv-nnn-1
3025     TColgp_SequenceOfXY UVL;
3026     TColgp_SequenceOfXY UVR;
3027     //==================================================
3028
3029     // step1: create faces for left domain
3030     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
3031     // add left nodes
3032     for (j=1; j<=nl; j++)
3033       NodesL.SetValue(1,j,uv_el[j-1].node);
3034     if (dl>0) {
3035       // add top nodes
3036       for (i=1; i<=dl; i++) 
3037         NodesL.SetValue(i+1,nl,uv_et[i].node);
3038       // create and add needed nodes
3039       TColgp_SequenceOfXY UVtmp;
3040       for (i=1; i<=dl; i++) {
3041         double x0 = npt.Value(i+1);
3042         double x1 = x0;
3043         // diagonal node
3044         double y0 = npl.Value(i+1);
3045         double y1 = npr.Value(i+1);
3046         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3047         gp_Pnt P = S->Value(UV.X(),UV.Y());
3048         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3049         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3050         NodesL.SetValue(i+1,1,N);
3051         if (UVL.Length()<nbv-nnn-1) UVL.Append(UV);
3052         // internal nodes
3053         for (j=2; j<nl; j++) {
3054           double y0 = npl.Value(dl+j);
3055           double y1 = npr.Value(dl+j);
3056           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3057           gp_Pnt P = S->Value(UV.X(),UV.Y());
3058           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3059           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3060           NodesL.SetValue(i+1,j,N);
3061           if (i==dl) UVtmp.Append(UV);
3062         }
3063       }
3064       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn-1; i++) {
3065         UVL.Append(UVtmp.Value(i));
3066       }
3067       // create faces
3068       for (i=1; i<=dl; i++) {
3069         for (j=1; j<nl; j++) {
3070             SMDS_MeshFace* F =
3071               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
3072                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
3073             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3074         }
3075       }
3076     }
3077     else {
3078       // fill UVL using c2d
3079       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn-1; i++) {
3080         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
3081       }
3082     }
3083     
3084     // step2: create faces for right domain
3085     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
3086     // add right nodes
3087     for (j=1; j<=nr; j++) 
3088       NodesR.SetValue(1,j,uv_er[nr-j].node);
3089     if (dr>0) {
3090       // add top nodes
3091       for (i=1; i<=dr; i++) 
3092         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
3093       // create and add needed nodes
3094       TColgp_SequenceOfXY UVtmp;
3095       for (i=1; i<=dr; i++) {
3096         double x0 = npt.Value(nt-i);
3097         double x1 = x0;
3098         // diagonal node
3099         double y0 = npl.Value(i+1);
3100         double y1 = npr.Value(i+1);
3101         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3102         gp_Pnt P = S->Value(UV.X(),UV.Y());
3103         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3104         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3105         NodesR.SetValue(i+1,nr,N);
3106         if (UVR.Length()<nbv-nnn-1) UVR.Append(UV);
3107         // internal nodes
3108         for (j=2; j<nr; j++) {
3109           double y0 = npl.Value(nbv-j+1);
3110           double y1 = npr.Value(nbv-j+1);
3111           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3112           gp_Pnt P = S->Value(UV.X(),UV.Y());
3113           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3114           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3115           NodesR.SetValue(i+1,j,N);
3116           if (i==dr) UVtmp.Prepend(UV);
3117         }
3118       }
3119       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn-1; i++) {
3120         UVR.Append(UVtmp.Value(i));
3121       }
3122       // create faces
3123       for (i=1; i<=dr; i++) {
3124         for (j=1; j<nr; j++) {
3125             SMDS_MeshFace* F =
3126               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
3127                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
3128             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3129         }
3130       }
3131     }
3132     else {
3133       // fill UVR using c2d
3134       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn-1; i++) {
3135         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
3136       }
3137     }
3138     
3139     // step3: create faces for central domain
3140     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
3141     // add first line using NodesL
3142     for (i=1; i<=dl+1; i++)
3143       NodesC.SetValue(1,i,NodesL(i,1));
3144     for (i=2; i<=nl; i++)
3145       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
3146     // add last line using NodesR
3147     for (i=1; i<=dr+1; i++)
3148       NodesC.SetValue(nb,i,NodesR(i,nr));
3149     for (i=1; i<nr; i++)
3150       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
3151     // add top nodes (last columns)
3152     for (i=dl+2; i<nbh-dr; i++) 
3153       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
3154     // add bottom nodes (first columns)
3155     for (i=2; i<nb; i++)
3156       NodesC.SetValue(i,1,uv_eb[i-1].node);
3157
3158     // create and add needed nodes
3159     // add linear layers
3160     for (i=2; i<nb; i++) {
3161       double x0 = npt.Value(dl+i);
3162       double x1 = x0;
3163       for (j=1; j<nnn; j++) {
3164         double y0 = npl.Value(nbv-nnn+j);
3165         double y1 = npr.Value(nbv-nnn+j);
3166         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3167         gp_Pnt P = S->Value(UV.X(),UV.Y());
3168         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3169         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3170         NodesC.SetValue(i,nbv-nnn+j,N);
3171       }
3172     }
3173     // add diagonal layers
3174     for (i=1; i<nbv-nnn; i++) {
3175       double du = UVR.Value(i).X() - UVL.Value(i).X();
3176       double dv = UVR.Value(i).Y() - UVL.Value(i).Y();
3177       for (j=2; j<nb; j++) {
3178         double u = UVL.Value(i).X() + du*npb.Value(j);
3179         double v = UVL.Value(i).Y() + dv*npb.Value(j);
3180         gp_Pnt P = S->Value(u,v);
3181         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3182         meshDS->SetNodeOnFace(N, geomFaceID, u, v);
3183         NodesC.SetValue(j,i+1,N);
3184       }
3185     }
3186     // create faces
3187     for (i=1; i<nb; i++) {
3188       for (j=1; j<nbv; j++) {
3189         SMDS_MeshFace* F =
3190           myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
3191                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
3192         if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3193       }
3194     }
3195   } // end Multiple Reduce implementation
3196   else { // Simple Reduce (!MultipleReduce)
3197     //=========================================================
3198     if (nr == nl) {
3199       if (nt < nb) {
3200         // it is a base case => not shift quad
3201         //shiftQuad(quad,0,true);
3202       }
3203       else {
3204         // we have to shift quad on 2
3205         shiftQuad(quad,2);
3206       }
3207     }
3208     else {
3209       if (nl > nr) {
3210         // we have to shift quad on 1
3211         shiftQuad(quad,1);
3212       }
3213       else {
3214         // we have to shift quad on 3
3215         shiftQuad(quad,3);
3216       }
3217     }
3218
3219     nb = quad->side[0].NbPoints();
3220     nr = quad->side[1].NbPoints();
3221     nt = quad->side[2].NbPoints();
3222     nl = quad->side[3].NbPoints();
3223
3224     // number of rows and columns
3225     int nrows = nr - 1; // and also == nl - 1
3226     int ncol_top = nt - 1;
3227     int ncol_bot = nb - 1;
3228     int npair_top = ncol_top / 2;
3229     // maximum number of bottom elements for "linear" simple reduce 4->2
3230     int max_lin42 = ncol_top + npair_top * 2 * nrows;
3231     // maximum number of bottom elements for "linear" simple reduce 3->1
3232     int max_lin31 = ncol_top + ncol_top * 2 * nrows;
3233     // maximum number of bottom elements for "tree" simple reduce 4->2
3234     int max_tree42 = 0;
3235     // number of rows needed to reduce ncol_bot to ncol_top using simple 4->2 "tree"
3236     int nrows_tree42 = int( log( (double)(ncol_bot / ncol_top) )/log((double)2)  ); // needed to avoid overflow at pow(2) while computing max_tree42
3237     if (nrows_tree42 < nrows) {
3238       max_tree42 = npair_top * pow(2.0, nrows + 1);
3239       if ( ncol_top > npair_top * 2 ) {
3240         int delta = ncol_bot - max_tree42;
3241         for (int irow = 1; irow < nrows; irow++) {
3242           int nfour = delta / 4;
3243           delta -= nfour * 2;
3244         }
3245         if (delta <= (ncol_top - npair_top * 2))
3246           max_tree42 = ncol_bot;
3247       }
3248     }
3249     // maximum number of bottom elements for "tree" simple reduce 3->1
3250     //int max_tree31 = ncol_top * pow(3.0, nrows);
3251     bool is_lin_31 = false;
3252     bool is_lin_42 = false;
3253     bool is_tree_31 = false;
3254     bool is_tree_42 = false;
3255     int max_lin = max_lin42;
3256     if (ncol_bot > max_lin42) {
3257       if (ncol_bot <= max_lin31) {
3258         is_lin_31 = true;
3259         max_lin = max_lin31;
3260       }
3261     }
3262     else {
3263       // if ncol_bot is a 3*n or not 2*n
3264       if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
3265         is_lin_31 = true;
3266         max_lin = max_lin31;
3267       }
3268       else {
3269         is_lin_42 = true;
3270       }
3271     }
3272     if (ncol_bot > max_lin) { // not "linear"
3273       is_tree_31 = (ncol_bot > max_tree42);
3274       if (ncol_bot <= max_tree42) {
3275         if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
3276           is_tree_31 = true;
3277         }
3278         else {
3279           is_tree_42 = true;
3280         }
3281       }
3282     }
3283
3284     const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
3285     const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
3286     const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
3287     const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
3288
3289     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
3290       return error(COMPERR_BAD_INPUT_MESH);
3291
3292     myHelper->SetElementsOnShape( true );
3293
3294     gp_UV uv[ UV_SIZE ];
3295     uv[ UV_A0 ].SetCoord( uv_eb.front().u, uv_eb.front().v);
3296     uv[ UV_A1 ].SetCoord( uv_eb.back().u,  uv_eb.back().v );
3297     uv[ UV_A2 ].SetCoord( uv_et.back().u,  uv_et.back().v );
3298     uv[ UV_A3 ].SetCoord( uv_et.front().u, uv_et.front().v);
3299
3300     vector<UVPtStruct> curr_base = uv_eb, next_base;
3301
3302     UVPtStruct nullUVPtStruct; nullUVPtStruct.node = 0;
3303
3304     int curr_base_len = nb;
3305     int next_base_len = 0;
3306
3307     if ( true )
3308     { // ------------------------------------------------------------------
3309       // New algorithm implemented by request of IPAL22856
3310       // "2D quadrangle mesher of reduced type works wrong"
3311       // http://bugtracker.opencascade.com/show_bug.cgi?id=22856
3312
3313       // the algorithm is following: all reduces are centred in horizontal
3314       // direction and are distributed among all rows
3315
3316       if (ncol_bot > max_tree42) {
3317         is_lin_31 = true;
3318       }
3319       else {
3320         if ((ncol_top/3)*3 == ncol_top ) {
3321           is_lin_31 = true;
3322         }
3323         else {
3324           is_lin_42 = true;
3325         }
3326       }
3327
3328       const int col_top_size  = is_lin_42 ? 2 : 1;
3329       const int col_base_size = is_lin_42 ? 4 : 3;
3330
3331       // Compute nb of "columns" (like in "linear" simple reducing) in all rows
3332
3333       vector<int> nb_col_by_row;
3334
3335       int delta_all     = nb - nt;
3336       int delta_one_col = nrows * 2;
3337       int nb_col        = delta_all / delta_one_col;
3338       int remainder     = delta_all - nb_col * delta_one_col;
3339       if (remainder > 0) {
3340         nb_col++;
3341       }
3342       if ( nb_col * col_top_size >= nt ) // == "tree" reducing situation
3343       {
3344         // top row is full (all elements reduced), add "columns" one by one
3345         // in rows below until all bottom elements are reduced
3346         nb_col = ( nt - 1 ) / col_top_size;
3347         nb_col_by_row.resize( nrows, nb_col );
3348         int nbrows_not_full = nrows - 1;
3349         int cur_top_size    = nt - 1;
3350         remainder = delta_all - nb_col * delta_one_col;
3351         while ( remainder > 0 )
3352         {
3353           delta_one_col   = nbrows_not_full * 2;
3354           int nb_col_add  = remainder / delta_one_col;
3355           cur_top_size   += 2 * nb_col_by_row[ nbrows_not_full ];
3356           int nb_col_free = cur_top_size / col_top_size - nb_col_by_row[ nbrows_not_full-1 ];
3357           if ( nb_col_add > nb_col_free )
3358             nb_col_add = nb_col_free;
3359           for ( int irow = 0; irow < nbrows_not_full; ++irow )
3360             nb_col_by_row[ irow ] += nb_col_add;
3361           nbrows_not_full --;
3362           remainder -=  nb_col_add * delta_one_col;
3363         }
3364       }
3365       else // == "linear" reducing situation
3366       {
3367         nb_col_by_row.resize( nrows, nb_col );
3368         if (remainder > 0)
3369           for ( int irow = remainder / 2; irow < nrows; ++irow )
3370             nb_col_by_row[ irow ]--;
3371       }
3372
3373       // Make elements
3374
3375       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3376
3377       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3378
3379       for (i = 1; i < nr; i++) // layer by layer
3380       {
3381         nb_col = nb_col_by_row[ i-1 ];
3382         int nb_next = curr_base_len - nb_col * 2;
3383         if (nb_next < nt) nb_next = nt;
3384
3385         const double y = uv_el[ i ].normParam;
3386
3387         if ( i + 1 == nr ) // top
3388         {
3389           next_base = uv_et;
3390         }
3391         else
3392         {
3393           next_base.clear();
3394           next_base.resize( nb_next, nullUVPtStruct );
3395           next_base.front() = uv_el[i];
3396           next_base.back()  = uv_er[i];
3397
3398           // compute normalized param u
3399           double du = 1. / ( nb_next - 1 );
3400           next_base[0].normParam = 0.;
3401           for ( j = 1; j < nb_next; ++j )
3402             next_base[j].normParam = next_base[j-1].normParam + du;
3403         }
3404         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3405         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3406
3407         int free_left = ( curr_base_len - 1 - nb_col * col_base_size ) / 2;
3408         int free_middle = curr_base_len - 1 - nb_col * col_base_size - 2 * free_left;
3409
3410         // not reduced left elements
3411         for (j = 0; j < free_left; j++)
3412         {
3413           // f (i + 1, j + 1)
3414           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3415           if ( !Nf )
3416             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3417
3418           myHelper->AddFace(curr_base[ j ].node,
3419                             curr_base[ j+1 ].node,
3420                             Nf,
3421                             next_base[ next_base_len-1 ].node);
3422         }
3423
3424         for (int icol = 1; icol <= nb_col; icol++)
3425         {
3426           // add "H"
3427           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3428
3429           j += reduce_grp_size;
3430
3431           // elements in the middle of "columns" added for symmetry
3432           if ( free_middle > 0 && ( nb_col % 2 == 0 ) && icol == nb_col / 2 )
3433           {
3434             for (int imiddle = 1; imiddle <= free_middle; imiddle++) {
3435               // f (i + 1, j + imiddle)
3436               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3437               if ( !Nf )
3438                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3439
3440               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3441                                 curr_base[ j  +imiddle ].node,
3442                                 Nf,
3443                                 next_base[ next_base_len-1 ].node);
3444             }
3445             j += free_middle;
3446           }
3447         }
3448
3449         // not reduced right elements
3450         for (; j < curr_base_len-1; j++) {
3451           // f (i + 1, j + 1)
3452           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3453           if ( !Nf )
3454             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3455
3456           myHelper->AddFace(curr_base[ j ].node,
3457                             curr_base[ j+1 ].node,
3458                             Nf,
3459                             next_base[ next_base_len-1 ].node);
3460         }
3461
3462         curr_base_len = next_base_len + 1;
3463         next_base_len = 0;
3464         curr_base.swap( next_base );
3465       }
3466
3467     }
3468     else if ( is_tree_42 || is_tree_31 )
3469     {
3470       // "tree" simple reduce "42": 2->4->8->16->32->...
3471       //
3472       //  .-------------------------------.-------------------------------. nr
3473       //  |    \                          |                          /    |
3474       //  |         \     .---------------.---------------.     /         |
3475       //  |               |               |               |               |
3476       //  .---------------.---------------.---------------.---------------.
3477       //  | \             |             / | \             |             / |
3478       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3479       //  |       |       |       |       |       |       |       |       |
3480       //  .-------.-------.-------.-------.-------.-------.-------.-------. i
3481       //  |\      |      /|\      |      /|\      |      /|\      |      /|
3482       //  |  \.---.---./  |  \.---.---./  |  \.---.---./  |  \.---.---./  |
3483       //  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
3484       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.
3485       //  |\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|
3486       //  | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. |
3487       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
3488       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
3489       //  1                               j                               nb
3490
3491       // "tree" simple reduce "31": 1->3->9->27->...
3492       //
3493       //  .-----------------------------------------------------. nr
3494       //  |        \                                   /        |
3495       //  |                 .-----------------.                 |
3496       //  |                 |                 |                 |
3497       //  .-----------------.-----------------.-----------------.
3498       //  |   \         /   |   \         /   |   \         /   |
3499       //  |     .-----.     |     .-----.     |     .-----.     | i
3500       //  |     |     |     |     |     |     |     |     |     |
3501       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.
3502       //  |\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|
3503       //  | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. |
3504       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | |
3505       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
3506       //  1                          j                          nb
3507
3508       PReduceFunction reduceFunction = & ( is_tree_42 ? reduce42 : reduce31 );
3509
3510       const int reduce_grp_size = is_tree_42 ? 4 : 3;
3511
3512       for (i = 1; i < nr; i++) // layer by layer
3513       {
3514         // to stop reducing, if number of nodes reaches nt
3515         int delta = curr_base_len - nt;
3516
3517         // to calculate normalized parameter, we must know number of points in next layer
3518         int nb_reduce_groups = (curr_base_len - 1) / reduce_grp_size;
3519         int nb_next = nb_reduce_groups * (reduce_grp_size-2) + (curr_base_len - nb_reduce_groups*reduce_grp_size);
3520         if (nb_next < nt) nb_next = nt;
3521
3522         const double y = uv_el[ i ].normParam;
3523
3524         if ( i + 1 == nr ) // top
3525         {
3526           next_base = uv_et;
3527         }
3528         else
3529         {
3530           next_base.clear();
3531           next_base.resize( nb_next, nullUVPtStruct );
3532           next_base.front() = uv_el[i];
3533           next_base.back()  = uv_er[i];
3534
3535           // compute normalized param u
3536           double du = 1. / ( nb_next - 1 );
3537           next_base[0].normParam = 0.;
3538           for ( j = 1; j < nb_next; ++j )
3539             next_base[j].normParam = next_base[j-1].normParam + du;
3540         }
3541         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3542         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3543
3544         for (j = 0; j+reduce_grp_size < curr_base_len && delta > 0; j+=reduce_grp_size, delta-=2)
3545         {
3546           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3547         }
3548
3549         // not reduced side elements (if any)
3550         for (; j < curr_base_len-1; j++)
3551         {
3552           // f (i + 1, j + 1)
3553           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3554           if ( !Nf )
3555             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3556           
3557           myHelper->AddFace(curr_base[ j ].node,
3558                             curr_base[ j+1 ].node,
3559                             Nf,
3560                             next_base[ next_base_len-1 ].node);
3561         }
3562         curr_base_len = next_base_len + 1;
3563         next_base_len = 0;
3564         curr_base.swap( next_base );
3565       }
3566     } // end "tree" simple reduce
3567
3568     else if ( is_lin_42 || is_lin_31 ) {
3569       // "linear" simple reduce "31": 2->6->10->14
3570       //
3571       //  .-----------------------------.-----------------------------. nr
3572       //  |     \                 /     |     \                 /     |
3573       //  |         .---------.         |         .---------.         |
3574       //  |         |         |         |         |         |         |
3575       //  .---------.---------.---------.---------.---------.---------.
3576       //  |        / \       / \        |        / \       / \        |
3577       //  |       /   .-----.   \       |       /   .-----.   \       | i
3578       //  |      /    |     |    \      |      /    |     |    \      |
3579       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.-----.
3580       //  |    /     / \   / \     \    |    /     / \   / \     \    |
3581       //  |   /     /   .-.   \     \   |   /     /   .-.   \     \   |
3582       //  |  /     /   /   \   \     \  |  /     /   /   \   \     \  |
3583       //  .--.----.---.-----.---.-----.-.--.----.---.-----.---.-----.-. 1
3584       //  1                             j                             nb
3585
3586       // "linear" simple reduce "42": 4->8->12->16
3587       //
3588       //  .---------------.---------------.---------------.---------------. nr
3589       //  | \             |             / | \             |             / |
3590       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3591       //  |       |       |       |       |       |       |       |       |
3592       //  .-------.-------.-------.-------.-------.-------.-------.-------.
3593       //  |      / \      |      / \      |      / \      |      / \      |
3594       //  |     /   \.----.----./   \     |     /   \.----.----./   \     | i
3595       //  |     /    |    |    |    \     |     /    |    |    |    \     |
3596       //  .-----.----.----.----.----.-----.-----.----.----.----.----.-----.
3597       //  |     /   / \   |  /  \   \     |     /   / \   |  /  \   \     |
3598       //  |    /   /    .-.-.    \   \    |    /   /    .-.-.    \   \    |
3599       //  |   /   /    /  |  \    \   \   |   /   /    /  |  \    \   \   |
3600       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---. 1
3601       //  1                               j                               nb
3602
3603       // nt = 5, nb = 7, nr = 4
3604       //int delta_all = 2;
3605       //int delta_one_col = 6;
3606       //int nb_col = 0;
3607       //int remainder = 2;
3608       //if (remainder > 0) nb_col++;
3609       //nb_col = 1;
3610       //int free_left = 1;
3611       //free_left += 2;
3612       //int free_middle = 4;
3613
3614       int delta_all = nb - nt;
3615       int delta_one_col = (nr - 1) * 2;
3616       int nb_col = delta_all / delta_one_col;
3617       int remainder = delta_all - nb_col * delta_one_col;
3618       if (remainder > 0) {
3619         nb_col++;
3620       }
3621       const int col_top_size = is_lin_42 ? 2 : 1;
3622       int free_left = ((nt - 1) - nb_col * col_top_size) / 2;
3623       free_left += nr - 2;
3624       int free_middle = (nr - 2) * 2;
3625       if (remainder > 0 && nb_col == 1) {
3626         int nb_rows_short_col = remainder / 2;
3627         int nb_rows_thrown = (nr - 1) - nb_rows_short_col;
3628         free_left -= nb_rows_thrown;
3629       }
3630
3631       // nt = 5, nb = 17, nr = 4
3632       //int delta_all = 12;
3633       //int delta_one_col = 6;
3634       //int nb_col = 2;
3635       //int remainder = 0;
3636       //int free_left = 2;
3637       //int free_middle = 4;
3638
3639       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3640
3641       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3642
3643       for (i = 1; i < nr; i++, free_middle -= 2, free_left -= 1) // layer by layer
3644       {
3645         // to calculate normalized parameter, we must know number of points in next layer
3646         int nb_next = curr_base_len - nb_col * 2;
3647         if (remainder > 0 && i > remainder / 2)
3648           // take into account short "column"
3649           nb_next += 2;
3650         if (nb_next < nt) nb_next = nt;
3651
3652         const double y = uv_el[ i ].normParam;
3653
3654         if ( i + 1 == nr ) // top
3655         {
3656           next_base = uv_et;
3657         }
3658         else
3659         {
3660           next_base.clear();
3661           next_base.resize( nb_next, nullUVPtStruct );
3662           next_base.front() = uv_el[i];
3663           next_base.back()  = uv_er[i];
3664
3665           // compute normalized param u
3666           double du = 1. / ( nb_next - 1 );
3667           next_base[0].normParam = 0.;
3668           for ( j = 1; j < nb_next; ++j )
3669             next_base[j].normParam = next_base[j-1].normParam + du;
3670         }
3671         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3672         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3673
3674         // not reduced left elements
3675         for (j = 0; j < free_left; j++)
3676         {
3677           // f (i + 1, j + 1)
3678           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3679           if ( !Nf )
3680             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3681
3682           myHelper->AddFace(curr_base[ j ].node,
3683                             curr_base[ j+1 ].node,
3684                             Nf,
3685                             next_base[ next_base_len-1 ].node);
3686         }
3687
3688         for (int icol = 1; icol <= nb_col; icol++) {
3689
3690           if (remainder > 0 && icol == nb_col && i > remainder / 2)
3691             // stop short "column"
3692             break;
3693
3694           // add "H"
3695           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3696
3697           j += reduce_grp_size;
3698
3699           // not reduced middle elements
3700           if (icol < nb_col) {
3701             if (remainder > 0 && icol == nb_col - 1 && i > remainder / 2)
3702               // pass middle elements before stopped short "column"
3703               break;
3704
3705             int free_add = free_middle;
3706             if (remainder > 0 && icol == nb_col - 1)
3707               // next "column" is short
3708               free_add -= (nr - 1) - (remainder / 2);
3709
3710             for (int imiddle = 1; imiddle <= free_add; imiddle++) {
3711               // f (i + 1, j + imiddle)
3712               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3713               if ( !Nf )
3714                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3715
3716               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3717                                 curr_base[ j  +imiddle ].node,
3718                                 Nf,
3719                                 next_base[ next_base_len-1 ].node);
3720             }
3721             j += free_add;
3722           }
3723         }
3724
3725         // not reduced right elements
3726         for (; j < curr_base_len-1; j++) {
3727           // f (i + 1, j + 1)
3728           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3729           if ( !Nf )
3730             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3731
3732           myHelper->AddFace(curr_base[ j ].node,
3733                             curr_base[ j+1 ].node,
3734                             Nf,
3735                             next_base[ next_base_len-1 ].node);
3736         }
3737
3738         curr_base_len = next_base_len + 1;
3739         next_base_len = 0;
3740         curr_base.swap( next_base );
3741       }
3742
3743     } // end "linear" simple reduce
3744
3745     else {
3746       return false;
3747     }
3748   } // end Simple Reduce implementation
3749
3750   bool isOk = true;
3751   return isOk;
3752 }
3753
3754 //================================================================================
3755 namespace // data for smoothing
3756 {
3757   struct TSmoothNode;
3758   // --------------------------------------------------------------------------------
3759   /*!
3760    * \brief Structure used to check validity of node position after smoothing.
3761    *        It holds two nodes connected to a smoothed node and belonging to
3762    *        one mesh face
3763    */
3764   struct TTriangle
3765   {
3766     TSmoothNode* _n1;
3767     TSmoothNode* _n2;
3768     TTriangle( TSmoothNode* n1=0, TSmoothNode* n2=0 ): _n1(n1), _n2(n2) {}
3769
3770     inline bool IsForward( gp_UV uv ) const;
3771   };
3772   // --------------------------------------------------------------------------------
3773   /*!
3774    * \brief Data of a smoothed node
3775    */
3776   struct TSmoothNode
3777   {
3778     gp_XY  _uv;
3779     gp_XYZ _xyz;
3780     vector< TTriangle > _triangles; // if empty, then node is not movable
3781   };
3782   // --------------------------------------------------------------------------------
3783   inline bool TTriangle::IsForward( gp_UV uv ) const
3784   {
3785     gp_Vec2d v1( uv, _n1->_uv ), v2( uv, _n2->_uv );
3786     double d = v1 ^ v2;
3787     return d > 1e-100;
3788   }
3789   //================================================================================
3790   /*!
3791    * \brief Returns area of a triangle
3792    */
3793   //================================================================================
3794
3795   double getArea( const gp_UV uv1, const gp_UV uv2, const gp_UV uv3 )
3796   {
3797     gp_XY v1 = uv1 - uv2, v2 = uv3 - uv2;
3798     double a = v2 ^ v1;
3799     return a;
3800   }
3801 }
3802
3803 //================================================================================
3804 /*!
3805  * \brief Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3806  *
3807  * WARNING: this method must be called AFTER retrieving UVPtStruct's from quad
3808  */
3809 //================================================================================
3810
3811 void StdMeshers_Quadrangle_2D::updateDegenUV(FaceQuadStruct::Ptr quad)
3812 {
3813   if ( myNeedSmooth )
3814
3815     // Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3816     // --------------------------------------------------------------------------
3817     for ( unsigned i = 0; i < quad->side.size(); ++i )
3818     {
3819       const vector<UVPtStruct>& uvVec = quad->side[i].GetUVPtStruct();
3820
3821       // find which end of the side is on degenerated shape
3822       int degenInd = -1;
3823       if ( myHelper->IsDegenShape( uvVec[0].node->getshapeId() ))
3824         degenInd = 0;
3825       else if ( myHelper->IsDegenShape( uvVec.back().node->getshapeId() ))
3826         degenInd = uvVec.size() - 1;
3827       else
3828         continue;
3829
3830       // find another side sharing the degenerated shape
3831       bool isPrev = ( degenInd == 0 );
3832       if ( i >= QUAD_TOP_SIDE )
3833         isPrev = !isPrev;
3834       int i2 = ( isPrev ? ( i + 3 ) : ( i + 1 )) % 4;
3835       const vector<UVPtStruct>& uvVec2 = quad->side[ i2 ].GetUVPtStruct();
3836       int degenInd2 = -1;
3837       if (      uvVec[ degenInd ].node == uvVec2.front().node )
3838         degenInd2 = 0;
3839       else if ( uvVec[ degenInd ].node == uvVec2.back().node )
3840         degenInd2 = uvVec2.size() - 1;
3841       else
3842         throw SALOME_Exception( LOCALIZED( "Logical error" ));
3843
3844       // move UV in the middle
3845       uvPtStruct& uv1 = const_cast<uvPtStruct&>( uvVec [ degenInd  ]);
3846       uvPtStruct& uv2 = const_cast<uvPtStruct&>( uvVec2[ degenInd2 ]);
3847       uv1.u = uv2.u = 0.5 * ( uv1.u + uv2.u );
3848       uv1.v = uv2.v = 0.5 * ( uv1.v + uv2.v );
3849     }
3850
3851   else if ( quad->side.size() == 4 /*&& myQuadType == QUAD_STANDARD*/)
3852
3853     // Set number of nodes on a degenerated side to be same as on an opposite side
3854     // ----------------------------------------------------------------------------
3855     for ( unsigned i = 0; i < quad->side.size(); ++i )
3856     {
3857       StdMeshers_FaceSidePtr degSide = quad->side[i];
3858       if ( !myHelper->IsDegenShape( degSide->EdgeID(0) ))
3859         continue;
3860       StdMeshers_FaceSidePtr oppSide = quad->side[( i+2 ) % quad->side.size() ];
3861       if ( degSide->NbSegments() == oppSide->NbSegments() )
3862         continue;
3863
3864       // make new side data
3865       const vector<UVPtStruct>& uvVecDegOld = degSide->GetUVPtStruct();
3866       const SMDS_MeshNode*   n = uvVecDegOld[0].node;
3867       Handle(Geom2d_Curve) c2d = degSide->Curve2d(0);
3868       double f = degSide->FirstU(0), l = degSide->LastU(0);
3869       gp_Pnt2d p1 = uvVecDegOld.front().UV();
3870       gp_Pnt2d p2 = uvVecDegOld.back().UV();
3871
3872       quad->side[i] = StdMeshers_FaceSide::New( oppSide.get(), n, &p1, &p2, c2d, f, l );
3873     }
3874 }
3875
3876 //================================================================================
3877 /*!
3878  * \brief Perform smoothing of 2D elements on a FACE with ignored degenerated EDGE
3879  */
3880 //================================================================================
3881
3882 void StdMeshers_Quadrangle_2D::smooth (FaceQuadStruct::Ptr quad)
3883 {
3884   if ( !myNeedSmooth ) return;
3885
3886   // Get nodes to smooth
3887
3888   // TODO: do not smooth fixed nodes
3889
3890   typedef map< const SMDS_MeshNode*, TSmoothNode, TIDCompare > TNo2SmooNoMap;
3891   TNo2SmooNoMap smooNoMap;
3892
3893   const TopoDS_Face&  geomFace = TopoDS::Face( myHelper->GetSubShape() );
3894   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
3895   double U1, U2, V1, V2;
3896   surface->Bounds(U1, U2, V1, V2);
3897   GeomAPI_ProjectPointOnSurf proj;
3898   proj.Init( surface, U1, U2, V1, V2, BRep_Tool::Tolerance( geomFace ) );
3899
3900   SMESHDS_Mesh*        meshDS = myHelper->GetMeshDS();
3901   SMESHDS_SubMesh*   fSubMesh = meshDS->MeshElements( geomFace );
3902   SMDS_NodeIteratorPtr    nIt = fSubMesh->GetNodes();
3903   while ( nIt->more() ) // loop on nodes bound to a FACE
3904   {
3905     const SMDS_MeshNode* node = nIt->next();
3906     TSmoothNode & sNode = smooNoMap[ node ];
3907     sNode._uv  = myHelper->GetNodeUV( geomFace, node );
3908     sNode._xyz = SMESH_TNodeXYZ( node );
3909
3910     // set sNode._triangles
3911     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator( SMDSAbs_Face );
3912     while ( fIt->more() )
3913     {
3914       const SMDS_MeshElement* face = fIt->next();
3915       const int nbN     = face->NbCornerNodes();
3916       const int nInd    = face->GetNodeIndex( node );
3917       const int prevInd = myHelper->WrapIndex( nInd - 1, nbN );
3918       const int nextInd = myHelper->WrapIndex( nInd + 1, nbN );
3919       const SMDS_MeshNode* prevNode = face->GetNode( prevInd );
3920       const SMDS_MeshNode* nextNode = face->GetNode( nextInd );
3921       sNode._triangles.push_back( TTriangle( & smooNoMap[ prevNode ],
3922                                              & smooNoMap[ nextNode ]));
3923     }
3924   }
3925   // set _uv of smooth nodes on FACE boundary
3926   for ( unsigned i = 0; i < quad->side.size(); ++i )
3927   {
3928     const vector<UVPtStruct>& uvVec = quad->side[i].GetUVPtStruct();
3929     for ( unsigned j = 0; j < uvVec.size(); ++j )
3930     {
3931       TSmoothNode & sNode = smooNoMap[ uvVec[j].node ];
3932       sNode._uv  = uvVec[j].UV();
3933       sNode._xyz = SMESH_TNodeXYZ( uvVec[j].node );
3934     }
3935   }
3936
3937   // define refernce orientation in 2D
3938   TNo2SmooNoMap::iterator n2sn = smooNoMap.begin();
3939   for ( ; n2sn != smooNoMap.end(); ++n2sn )
3940     if ( !n2sn->second._triangles.empty() )
3941       break;
3942   if ( n2sn == smooNoMap.end() ) return;
3943   const TSmoothNode & sampleNode = n2sn->second;
3944   const bool refForward = ( sampleNode._triangles[0].IsForward( sampleNode._uv ));
3945
3946   // Smoothing
3947
3948   for ( int iLoop = 0; iLoop < 5; ++iLoop )
3949   {
3950     for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3951     {
3952       TSmoothNode& sNode = n2sn->second;
3953       if ( sNode._triangles.empty() )
3954         continue; // not movable node
3955
3956       gp_XY newUV;
3957       bool isValid = false;
3958       bool use3D   = ( iLoop > 2 ); // 3 loops in 2D and 2, in 3D
3959
3960       if ( use3D )
3961       {
3962         // compute a new XYZ
3963         gp_XYZ newXYZ (0,0,0);
3964         for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3965           newXYZ += sNode._triangles[i]._n1->_xyz;
3966         newXYZ /= sNode._triangles.size();
3967
3968         // compute a new UV by projection
3969         proj.Perform( newXYZ );
3970         isValid = ( proj.IsDone() && proj.NbPoints() > 0 );
3971         if ( isValid )
3972         {
3973           // check validity of the newUV
3974           Quantity_Parameter u,v;
3975           proj.LowerDistanceParameters( u, v );
3976           newUV.SetCoord( u, v );
3977           for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3978             isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3979         }
3980       }
3981       if ( !isValid )
3982       {
3983         // compute a new UV by averaging
3984         newUV.SetCoord(0.,0.);
3985         for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3986           newUV += sNode._triangles[i]._n1->_uv;
3987         newUV /= sNode._triangles.size();
3988
3989         // check validity of the newUV
3990         isValid = true;
3991         for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3992           isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3993       }
3994       if ( isValid )
3995       {
3996         sNode._uv = newUV;
3997         sNode._xyz = surface->Value( newUV.X(), newUV.Y() ).XYZ();
3998       }
3999     }
4000   }
4001
4002   // Set new XYZ to the smoothed nodes
4003
4004   for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
4005   {
4006     TSmoothNode& sNode = n2sn->second;
4007     if ( sNode._triangles.empty() )
4008       continue; // not movable node
4009
4010     SMDS_MeshNode* node = const_cast< SMDS_MeshNode*>( n2sn->first );
4011     gp_Pnt xyz = surface->Value( sNode._uv.X(), sNode._uv.Y() );
4012     meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
4013
4014     // store the new UV
4015     node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( sNode._uv.X(), sNode._uv.Y() )));
4016   }
4017
4018   // Move medium nodes in quadratic mesh
4019   if ( _quadraticMesh )
4020   {
4021     const TLinkNodeMap& links = myHelper->GetTLinkNodeMap();
4022     TLinkNodeMap::const_iterator linkIt = links.begin();
4023     for ( ; linkIt != links.end(); ++linkIt )
4024     {
4025       const SMESH_TLink& link = linkIt->first;
4026       SMDS_MeshNode*     node = const_cast< SMDS_MeshNode*>( linkIt->second );
4027
4028       if ( node->getshapeId() != myHelper->GetSubShapeID() )
4029         continue; // medium node is on EDGE or VERTEX
4030
4031       gp_XY uv1 = myHelper->GetNodeUV( geomFace, link.node1(), node );
4032       gp_XY uv2 = myHelper->GetNodeUV( geomFace, link.node2(), node );
4033
4034       gp_XY uv  = myHelper->GetMiddleUV( surface, uv1, uv2 );
4035       node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( uv.X(), uv.Y() )));
4036       
4037       gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
4038       meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
4039     }
4040   }
4041 }
4042
4043 //================================================================================
4044 /*!
4045  * \brief Checks validity of generated faces
4046  */
4047 //================================================================================
4048
4049 bool StdMeshers_Quadrangle_2D::check()
4050 {
4051   const bool isOK = true;
4052   if ( !myCheckOri || myQuadList.empty() || !myQuadList.front() || !myHelper )
4053     return isOK;
4054
4055   TopoDS_Face      geomFace = TopoDS::Face( myHelper->GetSubShape() );
4056   SMESHDS_Mesh*    meshDS   = myHelper->GetMeshDS();
4057   SMESHDS_SubMesh* fSubMesh = meshDS->MeshElements( geomFace );
4058   bool toCheckUV;
4059   if ( geomFace.Orientation() >= TopAbs_INTERNAL ) geomFace.Orientation( TopAbs_FORWARD );
4060
4061   // Get a reference orientation sign
4062
4063   double okSign;
4064   {
4065     TError err;
4066     TSideVector wireVec =
4067       StdMeshers_FaceSide::GetFaceWires( geomFace, *myHelper->GetMesh(), true, err );
4068     StdMeshers_FaceSidePtr wire = wireVec[0];
4069
4070     // find a right angle VERTEX
4071     int iVertex;
4072     double maxAngle = -1e100;
4073     for ( int i = 0; i < wire->NbEdges(); ++i )
4074     {
4075       int iPrev = myHelper->WrapIndex( i-1, wire->NbEdges() );
4076       const TopoDS_Edge& e1 = wire->Edge( iPrev );
4077       const TopoDS_Edge& e2 = wire->Edge( i );
4078       double angle = myHelper->GetAngle( e1, e2, geomFace );
4079       if (( maxAngle < angle ) &&
4080           ( 5.* M_PI/180 < angle && angle < 85.* M_PI/180  ))
4081       {
4082         maxAngle = angle;
4083         iVertex = i;
4084       }
4085     }
4086     if ( maxAngle < -2*M_PI ) return isOK;
4087
4088     // get a sign of 2D area of a corner face
4089
4090     int iPrev = myHelper->WrapIndex( iVertex-1, wire->NbEdges() );
4091     const TopoDS_Edge& e1 = wire->Edge( iPrev );
4092     const TopoDS_Edge& e2 = wire->Edge( iVertex );
4093
4094     gp_Vec2d v1, v2; gp_Pnt2d p;
4095     double u[2];
4096     {
4097       bool rev = ( e1.Orientation() == TopAbs_REVERSED );
4098       Handle(Geom2d_Curve) c = BRep_Tool::CurveOnSurface( e1, geomFace, u[0], u[1] );
4099       c->D1( u[ !rev ], p, v1 );
4100       if ( !rev )
4101         v1.Reverse();
4102     }
4103     {
4104       bool rev = ( e2.Orientation() == TopAbs_REVERSED );
4105       Handle(Geom2d_Curve) c = BRep_Tool::CurveOnSurface( e2, geomFace, u[0], u[1] );
4106       c->D1( u[ rev ], p, v2 );
4107       if ( rev )
4108         v2.Reverse();
4109     }
4110
4111     okSign = v2 ^ v1;
4112
4113     if ( maxAngle < 0 )
4114       okSign *= -1;
4115   }
4116
4117   // Look for incorrectly oriented faces
4118
4119   std::list<const SMDS_MeshElement*> badFaces;
4120
4121   const SMDS_MeshNode* nn [ 8 ]; // 8 is just for safety
4122   gp_UV                uv [ 8 ];
4123   SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
4124   while ( fIt->more() ) // loop on faces bound to a FACE
4125   {
4126     const SMDS_MeshElement* f = fIt->next();
4127
4128     const int nbN = f->NbCornerNodes();
4129     for ( int i = 0; i < nbN; ++i )
4130       nn[ i ] = f->GetNode( i );
4131
4132     const SMDS_MeshNode* nInFace = 0;
4133     if ( myHelper->HasSeam() )
4134       for ( int i = 0; i < nbN && !nInFace; ++i )
4135         if ( !myHelper->IsSeamShape( nn[i]->getshapeId() ))
4136           nInFace = nn[i];
4137
4138     for ( int i = 0; i < nbN; ++i )
4139       uv[ i ] = myHelper->GetNodeUV( geomFace, nn[i], nInFace, &toCheckUV );
4140
4141     switch ( nbN ) {
4142     case 4:
4143     {
4144       double sign1 = getArea( uv[0], uv[1], uv[2] );
4145       double sign2 = getArea( uv[0], uv[2], uv[3] );
4146       if ( sign1 * sign2 < 0 )
4147       {
4148         sign2 = getArea( uv[1], uv[2], uv[3] );
4149         sign1 = getArea( uv[1], uv[3], uv[0] );
4150         if ( sign1 * sign2 < 0 )
4151           continue; // this should not happen
4152       }
4153       if ( sign1 * okSign < 0 )
4154         badFaces.push_back ( f );
4155       break;
4156     }
4157     case 3:
4158     {
4159       double sign = getArea( uv[0], uv[1], uv[2] );
4160       if ( sign * okSign < 0 )
4161         badFaces.push_back ( f );
4162       break;
4163     }
4164     default:;
4165     }
4166   }
4167
4168   if ( !badFaces.empty() )
4169   {
4170     SMESH_subMesh* fSM = myHelper->GetMesh()->GetSubMesh( geomFace );
4171     SMESH_ComputeErrorPtr& err = fSM->GetComputeError();
4172     err.reset ( new SMESH_ComputeError( COMPERR_ALGO_FAILED,
4173                                         "Inverted elements generated"));
4174     err->myBadElements.swap( badFaces );
4175
4176     return !isOK;
4177   }
4178
4179   return isOK;
4180 }
4181
4182 /*//================================================================================
4183 /*!
4184  * \brief Finds vertices at the most sharp face corners
4185  *  \param [in] theFace - the FACE
4186  *  \param [in,out] theWire - the ordered edges of the face. It can be modified to
4187  *         have the first VERTEX of the first EDGE in \a vertices
4188  *  \param [out] theVertices - the found corner vertices in the order corresponding to
4189  *         the order of EDGEs in \a theWire
4190  *  \param [out] theNbDegenEdges - nb of degenerated EDGEs in theFace
4191  *  \param [in] theConsiderMesh - if \c true, only meshed VERTEXes are considered
4192  *         as possible corners
4193  *  \return int - number of quad sides found: 0, 3 or 4
4194  */
4195 //================================================================================
4196
4197 int StdMeshers_Quadrangle_2D::getCorners(const TopoDS_Face&          theFace,
4198                                          SMESH_Mesh &                theMesh,
4199                                          std::list<TopoDS_Edge>&     theWire,
4200                                          std::vector<TopoDS_Vertex>& theVertices,
4201                                          int &                       theNbDegenEdges,
4202                                          const bool                  theConsiderMesh)
4203 {
4204   theNbDegenEdges = 0;
4205
4206   SMESH_MesherHelper helper( theMesh );
4207
4208   // sort theVertices by angle
4209   multimap<double, TopoDS_Vertex> vertexByAngle;
4210   TopTools_DataMapOfShapeReal angleByVertex;
4211   TopoDS_Edge prevE = theWire.back();
4212   if ( SMESH_Algo::isDegenerated( prevE ))
4213   {
4214     list<TopoDS_Edge>::reverse_iterator edge = ++theWire.rbegin();
4215     while ( SMESH_Algo::isDegenerated( *edge ))
4216       ++edge;
4217     if ( edge == theWire.rend() )
4218       return false;
4219     prevE = *edge;
4220   }
4221   list<TopoDS_Edge>::iterator edge = theWire.begin();
4222   for ( ; edge != theWire.end(); ++edge )
4223   {
4224     if ( SMESH_Algo::isDegenerated( *edge ))
4225     {
4226       ++theNbDegenEdges;
4227       continue;
4228     }
4229     TopoDS_Vertex v = helper.IthVertex( 0, *edge );
4230     if ( !theConsiderMesh || SMESH_Algo::VertexNode( v, helper.GetMeshDS() ))
4231     {
4232       double angle = SMESH_MesherHelper::GetAngle( prevE, *edge, theFace );
4233       vertexByAngle.insert( make_pair( angle, v ));
4234       angleByVertex.Bind( v, angle );
4235     }
4236     prevE = *edge;
4237   }
4238
4239   // find out required nb of corners (3 or 4)
4240   int nbCorners = 4;
4241   TopoDS_Shape triaVertex = helper.GetMeshDS()->IndexToShape( myTriaVertexID );
4242   if ( !triaVertex.IsNull() &&
4243        triaVertex.ShapeType() == TopAbs_VERTEX &&
4244        helper.IsSubShape( triaVertex, theFace ) &&
4245        ( vertexByAngle.size() != 4 || vertexByAngle.begin()->first < 5 * M_PI/180. ))
4246     nbCorners = 3;
4247   else
4248     triaVertex.Nullify();
4249
4250   // check nb of available corners
4251   if ( nbCorners == 3 )
4252   {
4253     if ( vertexByAngle.size() < 3 )
4254       return error(COMPERR_BAD_SHAPE,
4255                    TComm("Face must have 3 sides but not ") << vertexByAngle.size() );
4256   }
4257   else
4258   {
4259     if ( vertexByAngle.size() == 3 && theNbDegenEdges == 0 )
4260     {
4261       if ( myTriaVertexID < 1 )
4262         return error(COMPERR_BAD_PARMETERS,
4263                      "No Base vertex provided for a trilateral geometrical face");
4264         
4265       TComm comment("Invalid Base vertex: ");
4266       comment << myTriaVertexID << " its ID is not among [ ";
4267       multimap<double, TopoDS_Vertex>::iterator a2v = vertexByAngle.begin();
4268       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << ", "; a2v++;
4269       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << ", "; a2v++;
4270       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << " ]";
4271       return error(COMPERR_BAD_PARMETERS, comment );
4272     }
4273     if ( vertexByAngle.size() + ( theNbDegenEdges > 0 ) < 4 &&
4274          vertexByAngle.size() + theNbDegenEdges != 4 )
4275       return error(COMPERR_BAD_SHAPE,
4276                    TComm("Face must have 4 sides but not ") << vertexByAngle.size() );
4277   }
4278
4279   // put all corner vertices in a map
4280   TopTools_MapOfShape vMap;
4281   if ( nbCorners == 3 )
4282     vMap.Add( triaVertex );
4283   multimap<double, TopoDS_Vertex>::reverse_iterator a2v = vertexByAngle.rbegin();
4284   for ( ; a2v != vertexByAngle.rend() && vMap.Extent() < nbCorners; ++a2v )
4285     vMap.Add( (*a2v).second );
4286
4287   // check if there are possible variations in choosing corners
4288   bool isThereVariants = false;
4289   if ( vertexByAngle.size() > nbCorners )
4290   {
4291     double lostAngle = a2v->first;
4292     double lastAngle = ( --a2v, a2v->first );
4293     isThereVariants  = ( lostAngle * 1.1 >= lastAngle );
4294   }
4295
4296   myCheckOri = ( vertexByAngle.size() > nbCorners ||
4297                  vertexByAngle.begin()->first < 5.* M_PI/180 );
4298
4299   // make theWire begin from a corner vertex or triaVertex
4300   if ( nbCorners == 3 )
4301     while ( !triaVertex.IsSame( ( helper.IthVertex( 0, theWire.front() ))) ||
4302             SMESH_Algo::isDegenerated( theWire.front() ))
4303       theWire.splice( theWire.end(), theWire, theWire.begin() );
4304   else
4305     while ( !vMap.Contains( helper.IthVertex( 0, theWire.front() )) ||
4306             SMESH_Algo::isDegenerated( theWire.front() ))
4307       theWire.splice( theWire.end(), theWire, theWire.begin() );
4308
4309   // fill the result vector and prepare for its refinement
4310   theVertices.clear();
4311   vector< double >      angles;
4312   vector< TopoDS_Edge > edgeVec;
4313   vector< int >         cornerInd, nbSeg;
4314   angles.reserve( vertexByAngle.size() );
4315   edgeVec.reserve( vertexByAngle.size() );
4316   nbSeg.reserve( vertexByAngle.size() );
4317   cornerInd.reserve( nbCorners );
4318   for ( edge = theWire.begin(); edge != theWire.end(); ++edge )
4319   {
4320     if ( SMESH_Algo::isDegenerated( *edge ))
4321       continue;
4322     TopoDS_Vertex v = helper.IthVertex( 0, *edge );
4323     bool   isCorner = vMap.Contains( v );
4324     if ( isCorner )
4325     {
4326       theVertices.push_back( v );
4327       cornerInd.push_back( angles.size() );
4328     }
4329     angles.push_back( angleByVertex.IsBound( v ) ? angleByVertex( v ) : -M_PI );
4330     edgeVec.push_back( *edge );
4331     if ( theConsiderMesh && isThereVariants )
4332     {
4333       if ( SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( *edge ))
4334         nbSeg.push_back( sm->NbNodes() + 1 );
4335       else
4336         nbSeg.push_back( 0 );
4337     }
4338   }
4339
4340   // refine the result vector - make sides elual by length if
4341   // there are several equal angles
4342   if ( isThereVariants )
4343   {
4344     if ( nbCorners == 3 )
4345       angles[0] = 2 * M_PI; // not to move the base triangle VERTEX
4346
4347     set< int > refinedCorners;
4348     for ( size_t iC = 0; iC < cornerInd.size(); ++iC )
4349     {
4350       int iV = cornerInd[iC];
4351       if ( !refinedCorners.insert( iV ).second )
4352         continue;
4353       list< int > equalVertices;
4354       equalVertices.push_back( iV );
4355       int nbC[2] = { 0, 0 };
4356       // find equal angles backward and forward from the iV-th corner vertex
4357       for ( int isFwd = 0; isFwd < 2; ++isFwd )
4358       {
4359         int     dV = isFwd ? +1 : -1;
4360         int iCNext = helper.WrapIndex( iC + dV, cornerInd.size() );
4361         int iVNext = helper.WrapIndex( iV + dV, angles.size() );
4362         while ( iVNext != iV )
4363         {
4364           bool equal = Abs( angles[iV] - angles[iVNext] ) < 0.1 * angles[iV];
4365           if ( equal )
4366             equalVertices.insert( isFwd ? equalVertices.end() : equalVertices.begin(), iVNext );
4367           if ( iVNext == cornerInd[ iCNext ])
4368           {
4369             if ( !equal )
4370               break;
4371             nbC[ isFwd ]++;
4372             refinedCorners.insert( cornerInd[ iCNext ] );
4373             iCNext = helper.WrapIndex( iCNext + dV, cornerInd.size() );
4374           }
4375           iVNext = helper.WrapIndex( iVNext + dV, angles.size() );
4376         }
4377       }
4378       // move corners to make sides equal by length
4379       int nbEqualV  = equalVertices.size();
4380       int nbExcessV = nbEqualV - ( 1 + nbC[0] + nbC[1] );
4381       if ( nbExcessV > 0 )
4382       {
4383         // calculate normalized length of each side enclosed between neighbor equalVertices
4384         vector< double > curLengths;
4385         double totalLen = 0;
4386         vector< int > evVec( equalVertices.begin(), equalVertices.end() );
4387         int   iEV = 0;
4388         int    iE = cornerInd[ helper.WrapIndex( iC - nbC[0] - 1, cornerInd.size() )];
4389         int iEEnd = cornerInd[ helper.WrapIndex( iC + nbC[1] + 1, cornerInd.size() )];
4390         while ( curLengths.size() < nbEqualV + 1 )
4391         {
4392           curLengths.push_back( totalLen );
4393           do {
4394             curLengths.back() += SMESH_Algo::EdgeLength( edgeVec[ iE ]);
4395             iE = helper.WrapIndex( iE + 1, edgeVec.size());
4396             if ( iEV < evVec.size() && iE == evVec[ iEV++ ] )
4397               break;
4398           }
4399           while( iE != iEEnd );
4400           totalLen = curLengths.back();
4401         }
4402         curLengths.resize( equalVertices.size() );
4403         for ( size_t iS = 0; iS < curLengths.size(); ++iS )
4404           curLengths[ iS ] /= totalLen;
4405
4406         // find equalVertices most close to the ideal sub-division of all sides
4407         int iBestEV = 0;
4408         int iCorner = helper.WrapIndex( iC - nbC[0], cornerInd.size() );
4409         int nbSides = 2 + nbC[0] + nbC[1];
4410         for ( int iS = 1; iS < nbSides; ++iS, ++iBestEV )
4411         {
4412           double idealLen = iS / double( nbSides );
4413           double d, bestDist = 1.;
4414           for ( iEV = iBestEV; iEV < curLengths.size(); ++iEV )
4415             if (( d = Abs( idealLen - curLengths[ iEV ])) < bestDist )
4416             {
4417               bestDist = d;
4418               iBestEV  = iEV;
4419             }
4420           if ( iBestEV > iS-1 + nbExcessV )
4421             iBestEV = iS-1 + nbExcessV;
4422           theVertices[ iCorner ] = helper.IthVertex( 0, edgeVec[ evVec[ iBestEV ]]);
4423           iCorner = helper.WrapIndex( iCorner + 1, cornerInd.size() );
4424         }
4425       }
4426     }
4427   }
4428
4429   return nbCorners;
4430 }
4431
4432 //================================================================================
4433 /*!
4434  * \brief Constructor of a side of quad
4435  */
4436 //================================================================================
4437
4438 FaceQuadStruct::Side::Side(StdMeshers_FaceSidePtr theGrid)
4439   : grid(theGrid), nbNodeOut(0), from(0), to(theGrid ? theGrid->NbPoints() : 0 ), di(1)
4440 {
4441 }
4442
4443 //=============================================================================
4444 /*!
4445  * \brief Constructor of a quad
4446  */
4447 //=============================================================================
4448
4449 FaceQuadStruct::FaceQuadStruct(const TopoDS_Face& F, const std::string& theName)
4450   : face( F ), name( theName )
4451 {
4452   side.reserve(4);
4453 }
4454
4455 //================================================================================
4456 /*!
4457  * \brief Fills myForcedPnts
4458  */
4459 //================================================================================
4460
4461 bool StdMeshers_Quadrangle_2D::getEnforcedUV()
4462 {
4463   myForcedPnts.clear();
4464   if ( !myParams ) return true; // missing hypothesis
4465
4466   std::vector< TopoDS_Shape > shapes;
4467   std::vector< gp_Pnt >       points;
4468   myParams->GetEnforcedNodes( shapes, points );
4469
4470   TopTools_IndexedMapOfShape vMap;
4471   for ( size_t i = 0; i < shapes.size(); ++i )
4472     if ( !shapes[i].IsNull() )
4473       TopExp::MapShapes( shapes[i], TopAbs_VERTEX, vMap );
4474
4475   size_t nbPoints = points.size();
4476   for ( int i = 1; i <= vMap.Extent(); ++i )
4477     points.push_back( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))));
4478
4479   // find out if all points must be in the FACE, which is so if
4480   // myParams is a local hypothesis on the FACE being meshed
4481   bool isStrictCheck = false;
4482   {
4483     SMESH_HypoFilter paramFilter( SMESH_HypoFilter::Is( myParams ));
4484     TopoDS_Shape assignedTo;
4485     if ( myHelper->GetMesh()->GetHypothesis( myHelper->GetSubShape(),
4486                                              paramFilter,
4487                                              /*ancestors=*/true,
4488                                              &assignedTo ))
4489       isStrictCheck = ( assignedTo.IsSame( myHelper->GetSubShape() ));
4490   }
4491
4492   multimap< double, ForcedPoint > sortedFP; // sort points by distance from EDGEs
4493
4494   Standard_Real u1,u2,v1,v2;
4495   const TopoDS_Face&   face = TopoDS::Face( myHelper->GetSubShape() );
4496   const double          tol = BRep_Tool::Tolerance( face );
4497   Handle(Geom_Surface) surf = BRep_Tool::Surface( face );
4498   surf->Bounds( u1,u2,v1,v2 );
4499   GeomAPI_ProjectPointOnSurf project;
4500   project.Init(surf, u1,u2, v1,v2, tol );
4501   Bnd_Box bbox;
4502   BRepBndLib::Add( face, bbox );
4503   double farTol = 0.01 * sqrt( bbox.SquareExtent() );
4504
4505   for ( size_t iP = 0; iP < points.size(); ++iP )
4506   {
4507     project.Perform( points[ iP ]);
4508     if ( !project.IsDone() )
4509     {
4510       if ( isStrictCheck && iP < nbPoints )
4511         return error
4512           (TComm("Projection of an enforced point to the face failed - (")
4513            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4514       continue;
4515     }
4516     if ( project.LowerDistance() > farTol )
4517     {
4518       if ( isStrictCheck && iP < nbPoints )
4519         return error
4520           (COMPERR_BAD_PARMETERS, TComm("An enforced point is too far from the face, dist = ")
4521            << project.LowerDistance() << " - ("
4522            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4523       continue;
4524     }
4525     Quantity_Parameter u, v;
4526     project.LowerDistanceParameters(u, v);
4527     gp_Pnt2d uv( u, v );
4528     BRepClass_FaceClassifier clsf ( face, uv, tol );
4529     switch ( clsf.State() ) {
4530     case TopAbs_IN:
4531     {
4532       double edgeDist =  ( Min( Abs( u - u1 ), Abs( u - u2 )) +
4533                            Min( Abs( v - v1 ), Abs( v - v2 )));
4534       ForcedPoint fp;
4535       fp.uv  = uv.XY();
4536       fp.xyz = points[ iP ].XYZ();
4537       if ( iP >= nbPoints )
4538         fp.vertex = TopoDS::Vertex( vMap( iP - nbPoints + 1 ));
4539
4540       sortedFP.insert( make_pair( edgeDist, fp ));
4541       break;
4542     }
4543     case TopAbs_OUT:
4544     {
4545       if ( isStrictCheck && iP < nbPoints )
4546         return error
4547           (COMPERR_BAD_PARMETERS, TComm("An enforced point is out of the face boundary - ")
4548            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4549       break;
4550     }
4551     case TopAbs_ON:
4552     {
4553       if ( isStrictCheck && iP < nbPoints )
4554         return error
4555           (COMPERR_BAD_PARMETERS, TComm("An enforced point is on the face boundary - ")
4556            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4557       break;
4558     }
4559     default:
4560     {
4561       if ( isStrictCheck && iP < nbPoints )
4562         return error
4563           (TComm("Classification of an enforced point ralative to the face boundary failed - ")
4564            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4565     }
4566     }
4567   }
4568
4569   multimap< double, ForcedPoint >::iterator d2uv = sortedFP.begin();
4570   for ( ; d2uv != sortedFP.end(); ++d2uv )
4571     myForcedPnts.push_back( (*d2uv).second );
4572
4573   return true;
4574 }
4575
4576 //================================================================================
4577 /*!
4578  * \brief Splits quads by adding points of enforced nodes and create nodes on
4579  *        the sides shared by quads
4580  */
4581 //================================================================================
4582
4583 bool StdMeshers_Quadrangle_2D::addEnforcedNodes()
4584 {
4585   // if ( myForcedPnts.empty() )
4586   //   return true;
4587
4588   // make a map of quads sharing a side
4589   map< StdMeshers_FaceSidePtr, vector< FaceQuadStruct::Ptr > > quadsBySide;
4590   list< FaceQuadStruct::Ptr >::iterator quadIt = myQuadList.begin();
4591   for ( ; quadIt != myQuadList.end(); ++quadIt )
4592     for ( size_t iSide = 0; iSide < (*quadIt)->side.size(); ++iSide )
4593     {
4594       if ( !setNormalizedGrid( *quadIt ))
4595         return false;
4596       quadsBySide[ (*quadIt)->side[iSide] ].push_back( *quadIt );
4597     }
4598
4599   SMESH_Mesh*          mesh = myHelper->GetMesh();
4600   SMESHDS_Mesh*      meshDS = myHelper->GetMeshDS();
4601   const TopoDS_Face&   face = TopoDS::Face( myHelper->GetSubShape() );
4602   Handle(Geom_Surface) surf = BRep_Tool::Surface( face );
4603
4604   for ( size_t iFP = 0; iFP < myForcedPnts.size(); ++iFP )
4605   {
4606     bool isNodeEnforced = false;
4607
4608     // look for a quad enclosing a enforced point
4609     for ( quadIt = myQuadList.begin(); quadIt != myQuadList.end(); ++quadIt )
4610     {
4611       FaceQuadStruct::Ptr quad = *quadIt;
4612       if ( !setNormalizedGrid( *quadIt ))
4613         return false;
4614       int i,j;
4615       if ( !quad->findCell( myForcedPnts[ iFP ], i, j ))
4616         continue;
4617
4618       // a grid cell is found, select a node of the cell to move
4619       // to the enforced point to and to split the quad at
4620       multimap< double, pair< int, int > > ijByDist;
4621       for ( int di = 0; di < 2; ++di )
4622         for ( int dj = 0; dj < 2; ++dj )
4623         {
4624           double dist2 = ( myForcedPnts[ iFP ].uv - quad->UVPt( i+di,j+dj ).UV() ).SquareModulus();
4625           ijByDist.insert( make_pair( dist2, make_pair( di,dj )));
4626         }
4627       // try all nodes starting from the closest one
4628       set< FaceQuadStruct::Ptr > changedQuads;
4629       multimap< double, pair< int, int > >::iterator d2ij = ijByDist.begin();
4630       for ( ; !isNodeEnforced  &&  d2ij != ijByDist.end(); ++d2ij )
4631       {
4632         int di = d2ij->second.first;
4633         int dj = d2ij->second.second;
4634
4635         // check if a node is at a side
4636         int iSide = -1;
4637         if ( dj== 0 && j == 0 )
4638           iSide = QUAD_BOTTOM_SIDE;
4639         else if ( dj == 1 && j+2 == quad->jSize )
4640           iSide = QUAD_TOP_SIDE;
4641         else if ( di == 0 && i == 0 )
4642           iSide = QUAD_LEFT_SIDE;
4643         else if ( di == 1 && i+2 == quad->iSize )
4644           iSide = QUAD_RIGHT_SIDE;
4645
4646         if ( iSide > -1 ) // ----- node is at a side
4647         {
4648           FaceQuadStruct::Side& side = quad->side[ iSide ];
4649           // check if this node can be moved
4650           if ( quadsBySide[ side ].size() < 2 )
4651             continue; // its a face boundary -> can't move the node
4652
4653           int quadNodeIndex = ( iSide % 2 ) ? j : i;
4654           int sideNodeIndex = side.ToSideIndex( quadNodeIndex );
4655           if ( side.IsForced( sideNodeIndex ))
4656           {
4657             // the node is already moved to another enforced point
4658             isNodeEnforced = quad->isEqual( myForcedPnts[ iFP ], i, j );
4659             continue;
4660           }
4661           // make a node of a side forced
4662           vector<UVPtStruct>& points = (vector<UVPtStruct>&) side.GetUVPtStruct();
4663           points[ sideNodeIndex ].u = myForcedPnts[ iFP ].U();
4664           points[ sideNodeIndex ].v = myForcedPnts[ iFP ].V();
4665
4666           updateSideUV( side, sideNodeIndex, quadsBySide );
4667
4668           // update adjacent sides
4669           set< StdMeshers_FaceSidePtr > updatedSides;
4670           updatedSides.insert( side );
4671           for ( size_t i = 0; i < side.contacts.size(); ++i )
4672             if ( side.contacts[i].point == sideNodeIndex )
4673             {
4674               const vector< FaceQuadStruct::Ptr >& adjQuads =
4675                 quadsBySide[ *side.contacts[i].other_side ];
4676               if ( adjQuads.size() > 1 &&
4677                    updatedSides.insert( * side.contacts[i].other_side ).second )
4678               {
4679                 updateSideUV( *side.contacts[i].other_side,
4680                               side.contacts[i].other_point,
4681                               quadsBySide );
4682               }
4683               changedQuads.insert( adjQuads.begin(), adjQuads.end() );
4684             }
4685           const vector< FaceQuadStruct::Ptr >& adjQuads = quadsBySide[ side ];
4686           changedQuads.insert( adjQuads.begin(), adjQuads.end() );
4687
4688           isNodeEnforced = true;
4689         }
4690         else // ------------------ node is inside the quad
4691         {
4692           i += di;
4693           j += dj;
4694           // make a new side passing through IJ node and split the quad
4695           int indForced, iNewSide;
4696           if ( quad->iSize < quad->jSize ) // split vertically
4697           {
4698             quad->updateUV( myForcedPnts[ iFP ].uv, i, j, /*isVert=*/true );
4699             indForced = j;
4700             iNewSide  = splitQuad( quad, i, 0 );
4701           }
4702           else
4703           {
4704             quad->updateUV( myForcedPnts[ iFP ].uv, i, j, /*isVert=*/false );
4705             indForced = i;
4706             iNewSide  = splitQuad( quad, 0, j );
4707           }
4708           FaceQuadStruct::Ptr   newQuad = myQuadList.back();
4709           FaceQuadStruct::Side& newSide = newQuad->side[ iNewSide ];
4710
4711           newSide.forced_nodes.insert( indForced );
4712           quad->side[( iNewSide+2 ) % 4 ].forced_nodes.insert( indForced );
4713
4714           quadsBySide[ newSide ].push_back( quad );
4715           quadsBySide[ newQuad->side[0] ].push_back( newQuad );
4716           quadsBySide[ newQuad->side[1] ].push_back( newQuad );
4717           quadsBySide[ newQuad->side[2] ].push_back( newQuad );
4718           quadsBySide[ newQuad->side[3] ].push_back( newQuad );
4719
4720           isNodeEnforced = true;
4721
4722         } // end of "node is inside the quad"
4723
4724       } // loop on nodes of the cell
4725
4726       // remove out-of-date uv grid of changedQuads
4727       set< FaceQuadStruct::Ptr >::iterator qIt = changedQuads.begin();
4728       for ( ; qIt != changedQuads.end(); ++qIt )
4729         (*qIt)->uv_grid.clear();
4730
4731       if ( isNodeEnforced )
4732         break;
4733
4734     } // loop on quads
4735
4736     if ( !isNodeEnforced )
4737     {
4738       if ( !myForcedPnts[ iFP ].vertex.IsNull() )
4739         return error(TComm("Unable to move any node to vertex #")
4740                      <<myHelper->GetMeshDS()->ShapeToIndex( myForcedPnts[ iFP ].vertex ));
4741       else
4742         return error(TComm("Unable to move any node to point ( ")
4743                      << myForcedPnts[iFP].xyz.X() << ", "
4744                      << myForcedPnts[iFP].xyz.Y() << ", "
4745                      << myForcedPnts[iFP].xyz.Z() << " )");
4746     }
4747
4748   } // loop on enforced points
4749
4750   // Compute nodes on all sides, where not yet present
4751
4752   for ( quadIt = myQuadList.begin(); quadIt != myQuadList.end(); ++quadIt )
4753   {
4754     FaceQuadStruct::Ptr quad = *quadIt;
4755     for ( int iSide = 0; iSide < 4; ++iSide )
4756     {
4757       FaceQuadStruct::Side & side = quad->side[ iSide ];
4758       if ( side.nbNodeOut > 0 )
4759         continue; // emulated side
4760       vector< FaceQuadStruct::Ptr >& quadVec = quadsBySide[ side ];
4761       if ( quadVec.size() <= 1 )
4762         continue; // outer side
4763
4764       bool missedNodesOnSide = false;
4765       const vector<UVPtStruct>& points = side.grid->GetUVPtStruct();
4766       for ( size_t iC = 0; iC < side.contacts.size(); ++iC )
4767       {
4768         const vector<UVPtStruct>& oGrid = side.contacts[iC].other_side->grid->GetUVPtStruct();
4769         const UVPtStruct&         uvPt  = points[ side.contacts[iC].point ];
4770         if ( side.contacts[iC].other_point >= oGrid.size()      ||
4771              side.contacts[iC].point       >= points.size() )
4772           throw SALOME_Exception( "StdMeshers_Quadrangle_2D::addEnforcedNodes(): wrong contact" );
4773         if ( oGrid[ side.contacts[iC].other_point ].node )
4774           (( UVPtStruct& ) uvPt).node = oGrid[ side.contacts[iC].other_point ].node;
4775       }
4776       for ( size_t iP = 0; iP < points.size(); ++iP )
4777         if ( !points[ iP ].node )
4778         {
4779           UVPtStruct& uvPnt = ( UVPtStruct& ) points[ iP ];
4780           gp_Pnt P = surf->Value( uvPnt.u, uvPnt.v );
4781           uvPnt.node = meshDS->AddNode(P.X(), P.Y(), P.Z());
4782           meshDS->SetNodeOnFace( uvPnt.node, myHelper->GetSubShapeID(), uvPnt.u, uvPnt.v );
4783           missedNodesOnSide = true;
4784         }
4785       if ( missedNodesOnSide )
4786       {
4787         // clear uv_grid where nodes are missing
4788         for ( size_t iQ = 0; iQ < quadVec.size(); ++iQ )
4789           quadVec[ iQ ]->uv_grid.clear();
4790       }
4791     }
4792   }
4793
4794   return true;
4795 }
4796
4797 //================================================================================
4798 /*!
4799  * \brief Splits a quad at I or J. Returns an index of a new side in the new quad
4800  */
4801 //================================================================================
4802
4803 int StdMeshers_Quadrangle_2D::splitQuad(FaceQuadStruct::Ptr quad, int I, int J)
4804 {
4805   FaceQuadStruct* newQuad = new FaceQuadStruct( quad->face );
4806   myQuadList.push_back( FaceQuadStruct::Ptr( newQuad ));
4807
4808   vector<UVPtStruct> points;
4809   if ( I > 0 && I <= quad->iSize-2 )
4810   {
4811     points.reserve( quad->jSize );
4812     for ( int jP = 0; jP < quad->jSize; ++jP )
4813       points.push_back( quad->UVPt( I, jP ));
4814
4815     newQuad->side.resize( 4 );
4816     newQuad->side[ QUAD_BOTTOM_SIDE ] = quad->side[ QUAD_BOTTOM_SIDE ];
4817     newQuad->side[ QUAD_RIGHT_SIDE  ] = quad->side[ QUAD_RIGHT_SIDE  ];
4818     newQuad->side[ QUAD_TOP_SIDE    ] = quad->side[ QUAD_TOP_SIDE    ];
4819     newQuad->side[ QUAD_LEFT_SIDE   ] = StdMeshers_FaceSide::New( points, quad->face );
4820
4821     FaceQuadStruct::Side& newSide  = newQuad->side[ QUAD_LEFT_SIDE ];
4822     FaceQuadStruct::Side& newSide2 = quad->side   [ QUAD_RIGHT_SIDE ];
4823
4824     quad->side[ QUAD_RIGHT_SIDE  ] = newSide;
4825
4826     int iBot = quad->side[ QUAD_BOTTOM_SIDE ].ToSideIndex( I );
4827     int iTop = quad->side[ QUAD_TOP_SIDE    ].ToSideIndex( I );
4828
4829     newSide.AddContact ( 0,               & quad->side[ QUAD_BOTTOM_SIDE ], iBot );
4830     newSide2.AddContact( 0,               & quad->side[ QUAD_BOTTOM_SIDE ], iBot );
4831     newSide.AddContact ( quad->jSize - 1, & quad->side[ QUAD_TOP_SIDE    ], iTop );
4832     newSide2.AddContact( quad->jSize - 1, & quad->side[ QUAD_TOP_SIDE    ], iTop );
4833     // cout << "Contact: L " << &newSide << " "<< newSide.NbPoints()
4834     //      << " R " << &newSide2 << " "<< newSide2.NbPoints()
4835     //      << " B " << &quad->side[ QUAD_BOTTOM_SIDE ] << " "<< quad->side[ QUAD_BOTTOM_SIDE].NbPoints()
4836     //      << " T " << &quad->side[ QUAD_TOP_SIDE ]  << " "<< quad->side[ QUAD_TOP_SIDE].NbPoints()<< endl;
4837
4838     newQuad->side[ QUAD_BOTTOM_SIDE ].from = iBot;
4839     newQuad->side[ QUAD_TOP_SIDE    ].from = iTop;
4840     newQuad->name = ( TComm("Right of I=") << I );
4841
4842     quad->side[ QUAD_BOTTOM_SIDE ].to = iBot + 1;
4843     quad->side[ QUAD_TOP_SIDE    ].to = iTop + 1;
4844     quad->uv_grid.clear();
4845
4846     return QUAD_LEFT_SIDE;
4847   }
4848   else if ( J > 0  && J <= quad->jSize-2 ) //// split horizontally, a new quad is below an old one
4849   {
4850     points.reserve( quad->iSize );
4851     for ( int iP = 0; iP < quad->iSize; ++iP )
4852       points.push_back( quad->UVPt( iP, J ));
4853
4854     newQuad->side.resize( 4 );
4855     newQuad->side[ QUAD_BOTTOM_SIDE ] = quad->side[ QUAD_BOTTOM_SIDE ];
4856     newQuad->side[ QUAD_RIGHT_SIDE  ] = quad->side[ QUAD_RIGHT_SIDE  ];
4857     newQuad->side[ QUAD_TOP_SIDE    ] = StdMeshers_FaceSide::New( points, quad->face );
4858     newQuad->side[ QUAD_LEFT_SIDE   ] = quad->side[ QUAD_LEFT_SIDE   ];
4859
4860     FaceQuadStruct::Side& newSide  = newQuad->side[ QUAD_TOP_SIDE    ];
4861     FaceQuadStruct::Side& newSide2 = quad->side   [ QUAD_BOTTOM_SIDE ];
4862
4863     quad->side[ QUAD_BOTTOM_SIDE ] = newSide;
4864
4865     int iLft = quad->side[ QUAD_LEFT_SIDE  ].ToSideIndex( J );
4866     int iRgt = quad->side[ QUAD_RIGHT_SIDE ].ToSideIndex( J );
4867
4868     newSide.AddContact ( 0,               & quad->side[ QUAD_LEFT_SIDE  ], iLft );
4869     newSide2.AddContact( 0,               & quad->side[ QUAD_LEFT_SIDE  ], iLft );
4870     newSide.AddContact ( quad->iSize - 1, & quad->side[ QUAD_RIGHT_SIDE ], iRgt );
4871     newSide2.AddContact( quad->iSize - 1, & quad->side[ QUAD_RIGHT_SIDE ], iRgt );
4872     // cout << "Contact: T " << &newSide << " "<< newSide.NbPoints()
4873     //      << " B " << &newSide2 << " "<< newSide2.NbPoints()
4874     //      << " L " << &quad->side[ QUAD_LEFT_SIDE ] << " "<< quad->side[ QUAD_LEFT_SIDE].NbPoints()
4875     //      << " R " << &quad->side[ QUAD_RIGHT_SIDE ]  << " "<< quad->side[ QUAD_RIGHT_SIDE].NbPoints()<< endl;
4876
4877     newQuad->side[ QUAD_RIGHT_SIDE ].to = iRgt+1;
4878     newQuad->side[ QUAD_LEFT_SIDE  ].to = iLft+1;
4879     newQuad->name = ( TComm("Below J=") << J );
4880
4881     quad->side[ QUAD_RIGHT_SIDE ].from = iRgt;
4882     quad->side[ QUAD_LEFT_SIDE  ].from = iLft;
4883     quad->uv_grid.clear();
4884
4885     return QUAD_TOP_SIDE;
4886   }
4887
4888   myQuadList.pop_back();
4889   return -1;
4890 }
4891
4892 //================================================================================
4893 /*!
4894  * \brief Updates UV of a side after moving its node
4895  */
4896 //================================================================================
4897
4898 void StdMeshers_Quadrangle_2D::updateSideUV( FaceQuadStruct::Side&  side,
4899                                              int                    iForced,
4900                                              const TQuadsBySide&    quadsBySide,
4901                                              int *                  iNext)
4902 {
4903   if ( !iNext )
4904   {
4905     side.forced_nodes.insert( iForced );
4906
4907     // update parts of the side before and after iForced
4908
4909     set<int>::iterator iIt = side.forced_nodes.upper_bound( iForced );
4910     int iEnd = Min( side.NbPoints()-1, ( iIt == side.forced_nodes.end() ) ? int(1e7) : *iIt );
4911     if ( iForced + 1 < iEnd )
4912       updateSideUV( side, iForced, quadsBySide, &iEnd );
4913
4914     iIt = side.forced_nodes.lower_bound( iForced );
4915     int iBeg = Max( 0, ( iIt == side.forced_nodes.begin() ) ? 0 : *--iIt );
4916     if ( iForced - 1 > iBeg )
4917       updateSideUV( side, iForced, quadsBySide, &iBeg );
4918
4919     return;
4920   }
4921
4922   const int iFrom    = Min ( iForced, *iNext );
4923   const int iTo      = Max ( iForced, *iNext ) + 1;
4924   const int sideSize = iTo - iFrom;
4925
4926   vector<UVPtStruct> points[4]; // side points of a temporary quad
4927
4928   // from the quads get grid points adjacent to the side
4929   // to make two sides of a temporary quad
4930   vector< FaceQuadStruct::Ptr > quads = quadsBySide.find( side )->second; // copy!
4931   for ( int is2nd = 0; is2nd < 2; ++is2nd )
4932   {
4933     points[ is2nd ].reserve( sideSize );
4934     int nbLoops = 0;
4935     while ( points[is2nd].size() < sideSize )
4936     {
4937       int iCur = iFrom + points[is2nd].size() - int( !points[is2nd].empty() );
4938
4939       // look for a quad adjacent to iCur-th point of the side
4940       for ( size_t iQ = 0; iQ < quads.size(); ++iQ )
4941       {
4942         FaceQuadStruct::Ptr q = quads[ iQ ];
4943         if ( !q )
4944           continue;
4945         size_t iS;
4946         for ( iS = 0; iS < q->side.size(); ++iS )
4947           if ( side.grid == q->side[ iS ].grid )
4948             break;
4949         bool isOut;
4950         if ( !q->side[ iS ].IsReversed() )
4951           isOut = ( q->side[ iS ].from > iCur || q->side[ iS ].to-1 <= iCur );
4952         else
4953           isOut = ( q->side[ iS ].to  >= iCur || q->side[ iS ].from <= iCur );
4954         if ( isOut )
4955           continue;
4956         if ( !setNormalizedGrid( q ))
4957           continue;
4958
4959         // found - copy points
4960         int i,j,di,dj,nb;
4961         if ( iS % 2 ) // right or left
4962         {
4963           i  = ( iS == QUAD_LEFT_SIDE ) ? 1 : q->iSize-2;
4964           j  = q->side[ iS ].ToQuadIndex( iCur );
4965           di = 0;
4966           dj = ( q->side[ iS ].IsReversed() ) ? -1  : +1;
4967           nb = ( q->side[ iS ].IsReversed() ) ? j+1 : q->jSize-j;
4968         }
4969         else // bottom or top
4970         {
4971           i  = q->side[ iS ].ToQuadIndex( iCur );
4972           j  = ( iS == QUAD_BOTTOM_SIDE )  ?  1 : q->jSize-2;
4973           di = ( q->side[ iS ].IsReversed() ) ? -1  : +1;
4974           dj = 0;
4975           nb = ( q->side[ iS ].IsReversed() ) ? i+1 : q->iSize-i;
4976         }
4977         if ( !points[is2nd].empty() )
4978         {
4979           gp_UV lastUV = points[is2nd].back().UV();
4980           gp_UV quadUV = q->UVPt( i, j ).UV();
4981           if ( ( lastUV - quadUV ).SquareModulus() > 1e-10 )
4982             continue; // quad is on the other side of the side
4983           i += di; j += dj; --nb;
4984         }
4985         for ( ; nb > 0 ; --nb )
4986         {
4987           points[ is2nd ].push_back( q->UVPt( i, j ));
4988           if ( points[is2nd].size() >= sideSize )
4989             break;
4990           i += di; j += dj;
4991         }
4992         quads[ iQ ].reset(); // not to use this quad anymore
4993
4994         if ( points[is2nd].size() >= sideSize )
4995           break;
4996       } // loop on quads
4997
4998       if ( nbLoops++ > quads.size() )
4999         throw SALOME_Exception( "StdMeshers_Quadrangle_2D::updateSideUV() bug: infinite loop" );
5000
5001     } // while ( points[is2nd].size() < sideSize )
5002   } // two loops to fill points[0] and points[1]
5003
5004   // points for other pair of opposite sides of the temporary quad
5005
5006   enum { L,R,B,T }; // side index of points[]
5007
5008   points[B].push_back( points[L].front() );
5009   points[B].push_back( side.GetUVPtStruct()[ iFrom ]);
5010   points[B].push_back( points[R].front() );
5011
5012   points[T].push_back( points[L].back() );
5013   points[T].push_back( side.GetUVPtStruct()[ iTo-1 ]);
5014   points[T].push_back( points[R].back() );
5015
5016   // make the temporary quad
5017   FaceQuadStruct::Ptr tmpQuad
5018     ( new FaceQuadStruct( TopoDS::Face( myHelper->GetSubShape() ), "tmpQuad"));
5019   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[B] )); // bottom
5020   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[R] )); // right
5021   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[T] ));
5022   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[L] ));
5023
5024   // compute new UV of the side
5025   setNormalizedGrid( tmpQuad );
5026   gp_UV uv = tmpQuad->UVPt(1,0).UV();
5027   tmpQuad->updateUV( uv, 1,0, /*isVertical=*/true );
5028
5029   // update UV of the side
5030   vector<UVPtStruct>& sidePoints = (vector<UVPtStruct>&) side.GetUVPtStruct();
5031   for ( int i = iFrom; i < iTo; ++i )
5032   {
5033     const uvPtStruct& uvPt = tmpQuad->UVPt( 1, i-iFrom );
5034     sidePoints[ i ].u = uvPt.u;
5035     sidePoints[ i ].v = uvPt.v;
5036   }
5037 }
5038
5039 //================================================================================
5040 /*!
5041  * \brief Finds indices of a grid quad enclosing the given enforced UV
5042  */
5043 //================================================================================
5044
5045 bool FaceQuadStruct::findCell( const gp_XY& UV, int & I, int & J )
5046 {
5047   // setNormalizedGrid() must be called before!
5048   if ( uv_box.IsOut( UV ))
5049     return false;
5050
5051   // find an approximate position
5052   double x = 0.5, y = 0.5;
5053   gp_XY t0 = UVPt( iSize - 1, 0 ).UV();
5054   gp_XY t1 = UVPt( 0, jSize - 1 ).UV();
5055   gp_XY t2 = UVPt( 0, 0         ).UV();
5056   SMESH_MeshAlgos::GetBarycentricCoords( UV, t0, t1, t2, x, y );
5057   x = Min( 1., Max( 0., x ));
5058   y = Min( 1., Max( 0., y ));
5059
5060   // precise the position
5061   normPa2IJ( x,y, I,J );
5062   if ( !isNear( UV, I,J ))
5063   {
5064     // look for the most close IJ by traversing uv_grid in the middle
5065     double dist2, minDist2 = ( UV - UVPt( I,J ).UV() ).SquareModulus();
5066     for ( int isU = 0; isU < 2; ++isU )
5067     {
5068       int ind1 = isU ? 0 : iSize / 2;
5069       int ind2 = isU ? jSize / 2 : 0;
5070       int di1  = isU ? Max( 2, iSize / 20 ) : 0;
5071       int di2  = isU ? 0 : Max( 2, jSize / 20 );
5072       int i,nb = isU ? iSize / di1 : jSize / di2;
5073       for ( i = 0; i < nb; ++i, ind1 += di1, ind2 += di2 )
5074         if (( dist2 = ( UV - UVPt( ind1,ind2 ).UV() ).SquareModulus() ) < minDist2 )
5075         {
5076           I = ind1;
5077           J = ind2;
5078           if ( isNear( UV, I,J ))
5079             return true;
5080           minDist2 = ( UV - UVPt( I,J ).UV() ).SquareModulus();
5081         }
5082     }
5083     if ( !isNear( UV, I,J, Max( iSize, jSize ) /2 ))
5084       return false;
5085   }
5086   return true;
5087 }
5088
5089 //================================================================================
5090 /*!
5091  * \brief Find indices (i,j) of a point in uv_grid by normalized parameters (x,y)
5092  */
5093 //================================================================================
5094
5095 void FaceQuadStruct::normPa2IJ(double X, double Y, int & I, int & J )
5096 {
5097
5098   I = Min( int ( iSize * X ), iSize - 2 );
5099   J = Min( int ( jSize * Y ), jSize - 2 );
5100
5101   int oldI, oldJ;
5102   do
5103   {
5104     oldI = I, oldJ = J;
5105     while ( X <= UVPt( I,J ).x   && I != 0 )
5106       --I;
5107     while ( X >  UVPt( I+1,J ).x && I+2 < iSize )
5108       ++I;
5109     while ( Y <= UVPt( I,J ).y   && J != 0 )
5110       --J;
5111     while ( Y >  UVPt( I,J+1 ).y && J+2 < jSize )
5112       ++J;
5113   } while ( oldI != I || oldJ != J );
5114 }
5115
5116 //================================================================================
5117 /*!
5118  * \brief Looks for UV in quads around a given (I,J) and precise (I,J)
5119  */
5120 //================================================================================
5121
5122 bool FaceQuadStruct::isNear( const gp_XY& UV, int & I, int & J, int nbLoops )
5123 {
5124   if ( I+1 >= iSize ) I = iSize - 2;
5125   if ( J+1 >= jSize ) J = jSize - 2;
5126
5127   double bcI, bcJ;
5128   gp_XY uvI, uvJ, uv0, uv1;
5129   for ( int iLoop = 0; iLoop < nbLoops; ++iLoop )
5130   {
5131     int oldI = I, oldJ = J;
5132
5133     uvI = UVPt( I+1, J ).UV();
5134     uvJ = UVPt( I, J+1 ).UV();
5135     uv0 = UVPt( I, J   ).UV();
5136     SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv0, bcI, bcJ );
5137     if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5138       return true;
5139
5140     if ( I > 0       && bcI < 0. ) --I;
5141     if ( I+2 < iSize && bcI > 1. ) ++I;
5142     if ( J > 0       && bcJ < 0. ) --J;
5143     if ( J+2 < jSize && bcJ > 1. ) ++J;
5144
5145     uv1 = UVPt( I+1,J+1).UV();
5146     if ( I != oldI || J != oldJ )
5147     {
5148       uvI = UVPt( I+1, J ).UV();
5149       uvJ = UVPt( I, J+1 ).UV();
5150     }
5151     SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv1, bcI, bcJ );
5152     if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5153       return true;
5154
5155     if ( I > 0       && bcI > 1. ) --I;
5156     if ( I+2 < iSize && bcI < 0. ) ++I;
5157     if ( J > 0       && bcJ > 1. ) --J;
5158     if ( J+2 < jSize && bcJ < 0. ) ++J;
5159
5160     if ( I == oldI && J == oldJ )
5161       return false;
5162
5163     if ( iLoop+1 == nbLoops )
5164     {
5165       uvI = UVPt( I+1, J ).UV();
5166       uvJ = UVPt( I, J+1 ).UV();
5167       uv0 = UVPt( I, J   ).UV();
5168       SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv0, bcI, bcJ );
5169       if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5170         return true;
5171
5172       uv1 = UVPt( I+1,J+1).UV();
5173       SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv1, bcI, bcJ );
5174       if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
5175         return true;
5176     }
5177   }
5178   return false;
5179 }
5180
5181 //================================================================================
5182 /*!
5183  * \brief Checks if a given UV is equal to a given grid point
5184  */
5185 //================================================================================
5186
5187 bool FaceQuadStruct::isEqual( const gp_XY& UV, int I, int J )
5188 {
5189   TopLoc_Location loc;
5190   Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
5191   gp_Pnt p1 = surf->Value( UV.X(), UV.Y() );
5192   gp_Pnt p2 = surf->Value( UVPt( I,J ).u, UVPt( I,J ).v );
5193
5194   double dist2 = 1e100;
5195   for ( int di = -1; di < 2; di += 2 )
5196   {
5197     int i = I + di;
5198     if ( i < 0 || i+1 >= iSize ) continue;
5199     for ( int dj = -1; dj < 2; dj += 2 )
5200     {
5201       int j = J + dj;
5202       if ( j < 0 || j+1 >= jSize ) continue;
5203
5204       dist2 = Min( dist2,
5205                    p2.SquareDistance( surf->Value( UVPt( i,j ).u, UVPt( i,j ).v )));
5206     }
5207   }
5208   double tol2 = dist2 / 1000.;
5209   return p1.SquareDistance( p2 ) < tol2;
5210 }
5211
5212 //================================================================================
5213 /*!
5214  * \brief Recompute UV of grid points around a moved point in one direction
5215  */
5216 //================================================================================
5217
5218 void FaceQuadStruct::updateUV( const gp_XY& UV, int I, int J, bool isVertical )
5219 {
5220   UVPt( I, J ).u = UV.X();
5221   UVPt( I, J ).v = UV.Y();
5222
5223   if ( isVertical )
5224   {
5225     // above J
5226     if ( J+1 < jSize-1 )
5227     {
5228       gp_UV a0 = UVPt( 0,       J       ).UV();
5229       gp_UV a1 = UVPt( iSize-1, J       ).UV();
5230       gp_UV a2 = UVPt( iSize-1, jSize-1 ).UV();
5231       gp_UV a3 = UVPt( 0,       jSize-1 ).UV();
5232
5233       gp_UV p0 = UVPt( I, J       ).UV();
5234       gp_UV p2 = UVPt( I, jSize-1 ).UV();
5235       const double y0 = UVPt( I, J ).y, dy = 1. - y0;
5236       for (int j = J+1; j < jSize-1; j++)
5237       {
5238         gp_UV p1 = UVPt( iSize-1, j ).UV();
5239         gp_UV p3 = UVPt( 0,       j ).UV();
5240
5241         UVPtStruct& uvPt = UVPt( I, j );
5242         gp_UV uv = calcUV( uvPt.x, ( uvPt.y - y0 ) / dy, a0,a1,a2,a3, p0,p1,p2,p3);
5243         uvPt.u = uv.X();
5244         uvPt.v = uv.Y();
5245       }
5246     }
5247     // under J
5248     if ( J-1 > 0 )
5249     {
5250       gp_UV a0 = UVPt( 0,       0 ).UV();
5251       gp_UV a1 = UVPt( iSize-1, 0 ).UV();
5252       gp_UV a2 = UVPt( iSize-1, J ).UV();
5253       gp_UV a3 = UVPt( 0,       J ).UV();
5254
5255       gp_UV p0 = UVPt( I, 0 ).UV();
5256       gp_UV p2 = UVPt( I, J ).UV();
5257       const double y0 = 0., dy = UVPt( I, J ).y - y0;
5258       for (int j = 1; j < J; j++)
5259       {
5260         gp_UV p1 = UVPt( iSize-1, j ).UV();
5261         gp_UV p3 = UVPt( 0,       j ).UV();
5262
5263         UVPtStruct& uvPt = UVPt( I, j );
5264         gp_UV uv = calcUV( uvPt.x, ( uvPt.y - y0 ) / dy, a0,a1,a2,a3, p0,p1,p2,p3);
5265         uvPt.u = uv.X();
5266         uvPt.v = uv.Y();
5267       }
5268     }
5269   }
5270   else  // horizontally
5271   {
5272     // before I
5273     if ( I-1 > 0 )
5274     {
5275       gp_UV a0 = UVPt( 0, 0 ).UV();
5276       gp_UV a1 = UVPt( I, 0 ).UV();
5277       gp_UV a2 = UVPt( I, jSize-1 ).UV();
5278       gp_UV a3 = UVPt( 0, jSize-1 ).UV();
5279
5280       gp_UV p1 = UVPt( I, J ).UV();
5281       gp_UV p3 = UVPt( 0, J ).UV();
5282       const double x0 = 0., dx = UVPt( I, J ).x - x0;
5283       for (int i = 1; i < I; i++)
5284       {
5285         gp_UV p0 = UVPt( i, 0       ).UV();
5286         gp_UV p2 = UVPt( i, jSize-1 ).UV();
5287
5288         UVPtStruct& uvPt = UVPt( i, J );
5289         gp_UV uv = calcUV(( uvPt.x - x0 ) / dx , uvPt.y, a0,a1,a2,a3, p0,p1,p2,p3);
5290         uvPt.u = uv.X();
5291         uvPt.v = uv.Y();
5292       }
5293     }
5294     // after I
5295     if ( I+1 < iSize-1 )
5296     {
5297       gp_UV a0 = UVPt( I,       0 ).UV();
5298       gp_UV a1 = UVPt( iSize-1, 0 ).UV();
5299       gp_UV a2 = UVPt( iSize-1, jSize-1 ).UV();
5300       gp_UV a3 = UVPt( I,       jSize-1 ).UV();
5301
5302       gp_UV p1 = UVPt( iSize-1, J ).UV();
5303       gp_UV p3 = UVPt( I,       J ).UV();
5304       const double x0 = UVPt( I, J ).x, dx = 1. - x0;
5305       for (int i = I+1; i < iSize-1; i++)
5306       {
5307         gp_UV p0 = UVPt( i, 0       ).UV();
5308         gp_UV p2 = UVPt( i, jSize-1 ).UV();
5309
5310         UVPtStruct& uvPt = UVPt( i, J );
5311         gp_UV uv = calcUV(( uvPt.x - x0 ) / dx , uvPt.y, a0,a1,a2,a3, p0,p1,p2,p3);
5312         uvPt.u = uv.X();
5313         uvPt.v = uv.Y();
5314       }
5315     }
5316   }
5317 }
5318
5319 //================================================================================
5320 /*!
5321  * \brief Side copying
5322  */
5323 //================================================================================
5324
5325 FaceQuadStruct::Side& FaceQuadStruct::Side::operator=(const Side& otherSide)
5326 {
5327   grid = otherSide.grid;
5328   from = otherSide.from;
5329   to   = otherSide.to;
5330   di   = otherSide.di;
5331   forced_nodes = otherSide.forced_nodes;
5332   contacts     = otherSide.contacts;
5333   nbNodeOut    = otherSide.nbNodeOut;
5334
5335   for ( size_t iC = 0; iC < contacts.size(); ++iC )
5336   {
5337     FaceQuadStruct::Side* oSide = contacts[iC].other_side;
5338     for ( size_t iOC = 0; iOC < oSide->contacts.size(); ++iOC )
5339       if ( oSide->contacts[iOC].other_side == & otherSide )
5340       {
5341         // cout << "SHIFT old " << &otherSide << " " << otherSide.NbPoints()
5342         //      << " -> new " << this << " " << this->NbPoints() << endl;
5343         oSide->contacts[iOC].other_side = this;
5344       }
5345   }
5346   return *this;
5347 }
5348
5349 //================================================================================
5350 /*!
5351  * \brief Converts node index of a quad to node index of this side
5352  */
5353 //================================================================================
5354
5355 int FaceQuadStruct::Side::ToSideIndex( int quadNodeIndex ) const
5356 {
5357   return from + di * quadNodeIndex;
5358 }
5359
5360 //================================================================================
5361 /*!
5362  * \brief Converts node index of this side to node index of a quad
5363  */
5364 //================================================================================
5365
5366 int FaceQuadStruct::Side::ToQuadIndex( int sideNodeIndex ) const
5367 {
5368   return ( sideNodeIndex - from ) * di;
5369 }
5370
5371 //================================================================================
5372 /*!
5373  * \brief Reverse the side
5374  */
5375 //================================================================================
5376
5377 bool FaceQuadStruct::Side::Reverse(bool keepGrid)
5378 {
5379   if ( grid )
5380   {
5381     if ( keepGrid )
5382     {
5383       from -= di;
5384       to   -= di;
5385       std::swap( from, to );
5386       di   *= -1;
5387     }
5388     else
5389     {
5390       grid->Reverse();
5391     }
5392   }
5393   return (bool)grid;
5394 }
5395
5396 //================================================================================
5397 /*!
5398  * \brief Checks if a node is enforced
5399  *  \param [in] nodeIndex - an index of a node in a size
5400  *  \return bool - \c true if the node is forced
5401  */
5402 //================================================================================
5403
5404 bool FaceQuadStruct::Side::IsForced( int nodeIndex ) const
5405 {
5406   if ( nodeIndex < 0 || nodeIndex >= grid->NbPoints() )
5407     throw SALOME_Exception( " FaceQuadStruct::Side::IsForced(): wrong index" );
5408
5409   if ( forced_nodes.count( nodeIndex ) )
5410     return true;
5411
5412   for ( size_t i = 0; i < this->contacts.size(); ++i )
5413     if ( contacts[ i ].point == nodeIndex &&
5414          contacts[ i ].other_side->forced_nodes.count( contacts[ i ].other_point ))
5415       return true;
5416
5417   return false;
5418 }
5419
5420 //================================================================================
5421 /*!
5422  * \brief Sets up a contact between this and another side
5423  */
5424 //================================================================================
5425
5426 void FaceQuadStruct::Side::AddContact( int ip, Side* side, int iop )
5427 {
5428   if ( ip  >= GetUVPtStruct().size()      ||
5429        iop >= side->GetUVPtStruct().size() )
5430     throw SALOME_Exception( "FaceQuadStruct::Side::AddContact(): wrong point" );
5431   {
5432     contacts.resize( contacts.size() + 1 );
5433     Contact&    c = contacts.back();
5434     c.point       = ip;
5435     c.other_side  = side;
5436     c.other_point = iop;
5437   }
5438   {
5439     side->contacts.resize( side->contacts.size() + 1 );
5440     Contact&    c = side->contacts.back();
5441     c.point       = iop;
5442     c.other_side  = this;
5443     c.other_point = ip;
5444   }
5445 }
5446
5447 //================================================================================
5448 /*!
5449  * \brief Returns a normalized parameter of a point indexed within a quadrangle
5450  */
5451 //================================================================================
5452
5453 double FaceQuadStruct::Side::Param( int i ) const
5454 {
5455   const vector<UVPtStruct>& points = GetUVPtStruct();
5456   return (( points[ from + i * di ].normParam - points[ from ].normParam ) /
5457           ( points[ to   - 1 * di ].normParam - points[ from ].normParam ));
5458 }
5459
5460 //================================================================================
5461 /*!
5462  * \brief Returns UV by a parameter normalized within a quadrangle
5463  */
5464 //================================================================================
5465
5466 gp_XY FaceQuadStruct::Side::Value2d( double x ) const
5467 {
5468   const vector<UVPtStruct>& points = GetUVPtStruct();
5469   double u = ( points[ from ].normParam +
5470                x * ( points[ to-di ].normParam - points[ from ].normParam ));
5471   return grid->Value2d( u ).XY();
5472 }
5473
5474 //================================================================================
5475 /*!
5476  * \brief Returns side length
5477  */
5478 //================================================================================
5479
5480 double FaceQuadStruct::Side::Length(int theFrom, int theTo) const
5481 {
5482   if ( IsReversed() != ( theTo < theFrom ))
5483     std::swap( theTo, theFrom );
5484
5485   const vector<UVPtStruct>& points = GetUVPtStruct();
5486   double r;
5487   if ( theFrom == theTo && theTo == -1 )
5488     r = Abs( First().normParam -
5489              Last ().normParam );
5490   else if ( IsReversed() )
5491     r = Abs( points[ Max( to,   theTo+1 ) ].normParam -
5492              points[ Min( from, theFrom ) ].normParam );
5493   else
5494     r = Abs( points[ Min( to,   theTo-1 ) ].normParam -
5495              points[ Max( from, theFrom ) ].normParam );
5496   return r * grid->Length();
5497 }