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