Salome HOME
Merge from BR_imps_2013 14/01/2014
[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
1308   int nbhoriz  = Min(quad->side[0].NbPoints(), quad->side[2].NbPoints());
1309   int nbvertic = Min(quad->side[1].NbPoints(), quad->side[3].NbPoints());
1310
1311   if ( myQuadList.size() == 1 )
1312   {
1313     // all sub-quads must have NO sides with nbNodeOut > 0
1314     quad->nbNodeOut(0) = Max( 0, quad->side[0].grid->NbPoints() - quad->side[2].grid->NbPoints());
1315     quad->nbNodeOut(1) = Max( 0, quad->side[1].grid->NbPoints() - quad->side[3].grid->NbPoints());
1316     quad->nbNodeOut(2) = Max( 0, quad->side[2].grid->NbPoints() - quad->side[0].grid->NbPoints());
1317     quad->nbNodeOut(3) = Max( 0, quad->side[3].grid->NbPoints() - quad->side[1].grid->NbPoints());
1318   }
1319   int from[4] = {
1320     quad->side[0].from,
1321     quad->side[1].from,
1322     quad->side[2].from,
1323     quad->side[3].from
1324   };
1325   const vector<UVPtStruct>& uv_e0_vec = quad->side[ 0 ].GetUVPtStruct();
1326   const vector<UVPtStruct>& uv_e1_vec = quad->side[ 1 ].GetUVPtStruct();
1327   const vector<UVPtStruct>& uv_e2_vec = quad->side[ 2 ].GetUVPtStruct();
1328   const vector<UVPtStruct>& uv_e3_vec = quad->side[ 3 ].GetUVPtStruct();
1329
1330   if (uv_e0_vec.empty() || uv_e1_vec.empty() || uv_e2_vec.empty() || uv_e3_vec.empty())
1331     //return error("Can't find nodes on sides");
1332     return error(COMPERR_BAD_INPUT_MESH);
1333
1334   UVPtStruct* uv_e0 = (UVPtStruct*) & uv_e0_vec[0] + from[0];
1335   UVPtStruct* uv_e1 = (UVPtStruct*) & uv_e1_vec[0] + from[1];
1336   UVPtStruct* uv_e2 = (UVPtStruct*) & uv_e2_vec[0] + from[2];
1337   UVPtStruct* uv_e3 = (UVPtStruct*) & uv_e3_vec[0] + from[3];
1338
1339   quad->uv_grid.resize( nbvertic * nbhoriz );
1340   quad->iSize = nbhoriz;
1341   quad->jSize = nbvertic;
1342   UVPtStruct *uv_grid = & quad->uv_grid[0];
1343
1344   quad->uv_box.Clear();
1345
1346   // copy data of face boundary
1347
1348   { // BOTTOM
1349     const int j = 0;
1350     const double x0 = uv_e0[ 0 ].normParam;
1351     const double dx = uv_e0[ nbhoriz-1 ].normParam - uv_e0[ 0 ].normParam;
1352     for (int i = 0; i < nbhoriz; i++) {      // down
1353       uv_e0[i].x = ( uv_e0[i].normParam - x0 ) / dx;
1354       uv_e0[i].y = 0.;
1355       uv_grid[ j * nbhoriz + i ] = uv_e0[i];
1356       quad->uv_box.Add( uv_e0[i].UV() );
1357     }
1358   }
1359   { // RIGHT
1360     const int i = nbhoriz - 1;
1361     const double y0 = uv_e1[ 0 ].normParam;
1362     const double dy = uv_e1[ nbvertic-1 ].normParam - uv_e1[ 0 ].normParam;
1363     int j = 0, nb = nbvertic;
1364     if ( quad->UVPt( i, j ).node ) ++j; // avoid copying from a split emulated side
1365     for ( ; j < nb; j++) {      // right
1366       uv_e1[j].x = 1.;
1367       uv_e1[j].y = ( uv_e1[j].normParam - y0 ) / dy;
1368       uv_grid[ j * nbhoriz + i ] = uv_e1[j];
1369       quad->uv_box.Add( uv_e1[j].UV() );
1370     }
1371   }
1372   { // TOP
1373     const int j = nbvertic - 1;
1374     const double x0 = uv_e2[ 0 ].normParam;
1375     const double dx = uv_e2[ nbhoriz-1 ].normParam - uv_e2[ 0 ].normParam;
1376     int i = 0, nb = nbhoriz;
1377     if ( quad->UVPt( nb-1, j ).node ) --nb; // avoid copying from a split emulated side
1378     for (; i < nb; i++) {      // up
1379       uv_e2[i].x = ( uv_e2[i].normParam - x0 ) / dx;
1380       uv_e2[i].y = 1.;
1381       uv_grid[ j * nbhoriz + i ] = uv_e2[i];
1382       quad->uv_box.Add( uv_e2[i].UV() );
1383     }
1384   }
1385   { // LEFT
1386     const int i = 0;
1387     const double y0 = uv_e3[ 0 ].normParam;
1388     const double dy = uv_e3[ nbvertic-1 ].normParam - uv_e3[ 0 ].normParam;
1389     int j = 0, nb = nbvertic;
1390     if ( quad->UVPt( i, j    ).node ) ++j; // avoid copying from a split emulated side
1391     if ( quad->UVPt( i, nb-1 ).node ) --nb;
1392     for ( ; j < nb; j++) {     // left
1393       uv_e3[j].x = 0.;
1394       uv_e3[j].y = ( uv_e3[j].normParam - y0 ) / dy;
1395       uv_grid[ j * nbhoriz + i ] = uv_e3[j];
1396       quad->uv_box.Add( uv_e3[j].UV() );
1397     }
1398   }
1399
1400   // normalized 2d parameters on grid
1401
1402   for (int i = 1; i < nbhoriz-1; i++)
1403   {
1404     const double x0 = uv_e0[i].x;
1405     const double x1 = uv_e2[i].x;
1406     for (int j = 1; j < nbvertic-1; j++)
1407     {
1408       const double y0 = uv_e3[j].y;
1409       const double y1 = uv_e1[j].y;
1410       // --- intersection : x=x0+(y0+x(y1-y0))(x1-x0)
1411       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1412       double y = y0 + x * (y1 - y0);
1413       int   ij = j * nbhoriz + i;
1414       uv_grid[ij].x = x;
1415       uv_grid[ij].y = y;
1416       uv_grid[ij].node = NULL;
1417     }
1418   }
1419
1420   // projection on 2d domain (u,v)
1421
1422   gp_UV a0 = uv_e0[0        ].UV();
1423   gp_UV a1 = uv_e0[nbhoriz-1].UV();
1424   gp_UV a2 = uv_e2[nbhoriz-1].UV();
1425   gp_UV a3 = uv_e2[0        ].UV();
1426
1427   for (int i = 1; i < nbhoriz-1; i++)
1428   {
1429     gp_UV p0 = uv_e0[i].UV();
1430     gp_UV p2 = uv_e2[i].UV();
1431     for (int j = 1; j < nbvertic-1; j++)
1432     {
1433       gp_UV p1 = uv_e1[j].UV();
1434       gp_UV p3 = uv_e3[j].UV();
1435
1436       int ij = j * nbhoriz + i;
1437       double x = uv_grid[ij].x;
1438       double y = uv_grid[ij].y;
1439
1440       gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1441
1442       uv_grid[ij].u = uv.X();
1443       uv_grid[ij].v = uv.Y();
1444     }
1445   }
1446   return true;
1447 }
1448
1449 //=======================================================================
1450 //function : ShiftQuad
1451 //purpose  : auxilary function for computeQuadPref
1452 //=======================================================================
1453
1454 static void shiftQuad(FaceQuadStruct::Ptr& quad, const int num)
1455 {
1456   quad->shift( num, /*ori=*/true );
1457 }
1458
1459 //================================================================================
1460 /*!
1461  * \brief Rotate sides of a quad by nb
1462  *  \param nb  - number of rotation quartes
1463  *  \param ori - to keep orientation of sides as in an unit quad or not
1464  */
1465 //================================================================================
1466
1467 void FaceQuadStruct::shift( size_t nb, bool ori )
1468 {
1469   if ( nb == 0 ) return;
1470   StdMeshers_FaceSidePtr sideArr[4] = { side[0], side[1], side[2], side[3] };
1471   for (int i = QUAD_BOTTOM_SIDE; i < NB_QUAD_SIDES; ++i) {
1472     int id = (i + nb) % NB_QUAD_SIDES;
1473     bool wasForward = (i  < QUAD_TOP_SIDE);
1474     bool newForward = (id < QUAD_TOP_SIDE);
1475     if (ori && wasForward != newForward)
1476       sideArr[ i ]->Reverse();
1477     side[ id ] = sideArr[ i ];
1478   }
1479 }
1480
1481 //=======================================================================
1482 //function : calcUV
1483 //purpose  : auxilary function for computeQuadPref
1484 //=======================================================================
1485
1486 static gp_UV calcUV(double x0, double x1, double y0, double y1,
1487                     FaceQuadStruct::Ptr& quad,
1488                     const gp_UV& a0, const gp_UV& a1,
1489                     const gp_UV& a2, const gp_UV& a3)
1490 {
1491   double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1492   double y = y0 + x * (y1 - y0);
1493
1494   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE].grid->Value2d(x).XY();
1495   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ].grid->Value2d(y).XY();
1496   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ].grid->Value2d(x).XY();
1497   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ].grid->Value2d(y).XY();
1498
1499   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1500
1501   return uv;
1502 }
1503
1504 //=======================================================================
1505 //function : calcUV2
1506 //purpose  : auxilary function for computeQuadPref
1507 //=======================================================================
1508
1509 static gp_UV calcUV2(double x, double y,
1510                      FaceQuadStruct::Ptr& quad,
1511                      const gp_UV& a0, const gp_UV& a1,
1512                      const gp_UV& a2, const gp_UV& a3)
1513 {
1514   gp_UV p0 = quad->side[QUAD_BOTTOM_SIDE].grid->Value2d(x).XY();
1515   gp_UV p1 = quad->side[QUAD_RIGHT_SIDE ].grid->Value2d(y).XY();
1516   gp_UV p2 = quad->side[QUAD_TOP_SIDE   ].grid->Value2d(x).XY();
1517   gp_UV p3 = quad->side[QUAD_LEFT_SIDE  ].grid->Value2d(y).XY();
1518
1519   gp_UV uv = calcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1520
1521   return uv;
1522 }
1523
1524
1525 //=======================================================================
1526 /*!
1527  * Create only quandrangle faces
1528  */
1529 //=======================================================================
1530
1531 bool StdMeshers_Quadrangle_2D::computeQuadPref (SMESH_Mesh &        aMesh,
1532                                                 const TopoDS_Face&  aFace,
1533                                                 FaceQuadStruct::Ptr quad)
1534 {
1535   // Auxilary key in order to keep old variant
1536   // of meshing after implementation new variant
1537   // for bug 0016220 from Mantis.
1538   bool OldVersion = (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED);
1539
1540   SMESHDS_Mesh *  meshDS = aMesh.GetMeshDS();
1541   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
1542   bool WisF = true;
1543   int i,j,geomFaceID = meshDS->ShapeToIndex(aFace);
1544
1545   int nb = quad->side[0].grid->NbPoints();
1546   int nr = quad->side[1].grid->NbPoints();
1547   int nt = quad->side[2].grid->NbPoints();
1548   int nl = quad->side[3].grid->NbPoints();
1549   int dh = abs(nb-nt);
1550   int dv = abs(nr-nl);
1551
1552   if ( myForcedPnts.empty() )
1553   {
1554     // rotate sides to be as in the picture below and to have
1555     // dh >= dv and nt > nb
1556     if ( dh >= dv )
1557       shiftQuad( quad, ( nt > nb ) ? 0 : 2 );
1558     else
1559       shiftQuad( quad, ( nr > nl ) ? 1 : 3 );
1560   }
1561   else
1562   {
1563     // rotate the quad to have nt > nb [and nr > nl]
1564     if ( nb > nt )
1565       quad->shift( nr > nl ? 1 : 2, true );
1566     else if ( nr > nl )
1567       quad->shift( nb == nt ? 1 : 0, true );
1568     else if ( nl > nr )
1569       quad->shift( 3, true );
1570   }
1571
1572   nb = quad->side[0].grid->NbPoints();
1573   nr = quad->side[1].grid->NbPoints();
1574   nt = quad->side[2].grid->NbPoints();
1575   nl = quad->side[3].grid->NbPoints();
1576   dh = abs(nb-nt);
1577   dv = abs(nr-nl);
1578   int nbh  = Max(nb,nt);
1579   int nbv  = Max(nr,nl);
1580   int addh = 0;
1581   int addv = 0;
1582
1583   // Orientation of face and 3 main domain for future faces
1584   // ----------- Old version ---------------
1585   //       0   top    1
1586   //      1------------1
1587   //       |   |  |   |
1588   //       |   |C |   |
1589   //       | L |  | R |
1590   //  left |   |__|   | rigth
1591   //       |  /    \  |
1592   //       | /  C   \ |
1593   //       |/        \|
1594   //      0------------0
1595   //       0  bottom  1
1596
1597   // ----------- New version ---------------
1598   //       0   top    1
1599   //      1------------1
1600   //       |   |__|   |
1601   //       |  /    \  |
1602   //       | /  C   \ |
1603   //  left |/________\| rigth
1604   //       |          |
1605   //       |    C     |
1606   //       |          |
1607   //      0------------0
1608   //       0  bottom  1
1609
1610   const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
1611   const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
1612   const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
1613   const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
1614
1615   if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
1616     return error(COMPERR_BAD_INPUT_MESH);
1617
1618   gp_UV a0,a1,a2,a3, p0,p1,p2,p3, uv;
1619   double x,y;
1620
1621   a0 = uv_eb[ 0 ].UV();
1622   a1 = uv_er[ 0 ].UV();
1623   a2 = uv_er[ nr-1 ].UV();
1624   a3 = uv_et[ 0 ].UV();
1625
1626   if ( !myForcedPnts.empty() )
1627   {
1628     if ( dv != 0 && dh != 0 )
1629     {
1630       const int dmin = Min( dv, dh );
1631
1632       // Make a side separating domains L and Cb
1633       StdMeshers_FaceSidePtr sideLCb;
1634       UVPtStruct p3dom; // a point where 3 domains meat
1635       {                                                     //   dmin
1636         vector<UVPtStruct> pointsLCb( dmin+1 );             // 1--------1
1637         pointsLCb[0] = uv_eb[0];                            //  |   |  |
1638         for ( int i = 1; i <= dmin; ++i )                   //  |   |Ct|
1639         {                                                   //  | L |  |
1640           x  = uv_et[ i ].normParam;                        //  |   |__|
1641           y  = uv_er[ i ].normParam;                        //  |  /   |
1642           p0 = quad->side[0].grid->Value2d( x ).XY();       //  | / Cb |dmin
1643           p1 = uv_er[ i ].UV();                             //  |/     |
1644           p2 = uv_et[ i ].UV();                             // 0--------0
1645           p3 = quad->side[3].grid->Value2d( y ).XY();
1646           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1647           pointsLCb[ i ].u = uv.X();
1648           pointsLCb[ i ].v = uv.Y();
1649         }
1650         sideLCb = StdMeshers_FaceSide::New( pointsLCb, aFace );
1651         p3dom   = pointsLCb.back();
1652       }
1653       // Make a side separating domains L and Ct
1654       StdMeshers_FaceSidePtr sideLCt;
1655       {
1656         vector<UVPtStruct> pointsLCt( nl );
1657         pointsLCt[0]     = p3dom;
1658         pointsLCt.back() = uv_et[ dmin ];
1659         x  = uv_et[ dmin ].normParam;
1660         p0 = quad->side[0].grid->Value2d( x ).XY();
1661         p2 = uv_et[ dmin ].UV();
1662         for ( int i = 1; i < nl; ++i )
1663         {
1664           y  = uv_er[ i + dmin ].normParam;
1665           p1 = uv_er[ i + dmin ].UV();
1666           p3 = quad->side[3].grid->Value2d( y ).XY();
1667           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1668           pointsLCt[ i ].u = uv.X();
1669           pointsLCt[ i ].v = uv.Y();
1670         }
1671         sideLCt = StdMeshers_FaceSide::New( pointsLCt, aFace );
1672       }
1673       // Make a side separating domains Cb and Ct
1674       StdMeshers_FaceSidePtr sideCbCt;
1675       {
1676         vector<UVPtStruct> pointsCbCt( nb );
1677         pointsCbCt[0]     = p3dom;
1678         pointsCbCt.back() = uv_er[ dmin ];
1679         y  = uv_er[ dmin ].normParam;
1680         p1 = uv_er[ dmin ].UV();
1681         p3 = quad->side[3].grid->Value2d( y ).XY();
1682         for ( int i = 1; i < nb-1; ++i )
1683         {
1684           x  = uv_et[ i + dmin ].normParam;
1685           p2 = uv_et[ i + dmin ].UV();
1686           p0 = quad->side[0].grid->Value2d( x ).XY();
1687           uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1688           pointsCbCt[ i ].u = uv.X();
1689           pointsCbCt[ i ].v = uv.Y();
1690         }
1691         sideCbCt = StdMeshers_FaceSide::New( pointsCbCt, aFace );
1692       }
1693       // Make Cb quad
1694       FaceQuadStruct* qCb = new FaceQuadStruct( quad->face );
1695       myQuadList.push_back( FaceQuadStruct::Ptr( qCb ));
1696       qCb->side.resize(4);
1697       qCb->side[0] = quad->side[0];
1698       qCb->side[1] = quad->side[1];
1699       qCb->side[2] = sideCbCt;
1700       qCb->side[3] = sideLCb;
1701       qCb->side[1].to = dmin+1;
1702       // Make L quad
1703       FaceQuadStruct* qL = new FaceQuadStruct( quad->face );
1704       myQuadList.push_back( FaceQuadStruct::Ptr( qL ));
1705       qL->side.resize(4);
1706       qL->side[0] = sideLCb;
1707       qL->side[1] = sideLCt;
1708       qL->side[2] = quad->side[2];
1709       qL->side[3] = quad->side[3];
1710       qL->side[2].to = dmin+1;
1711       // Make Ct from the main quad
1712       FaceQuadStruct::Ptr qCt = quad;
1713       qCt->side[0] = sideCbCt;
1714       qCt->side[3] = sideLCt;
1715       qCt->side[1].from = dmin;
1716       qCt->side[2].from = dmin;
1717       qCt->uv_grid.clear();
1718
1719       // Connect sides
1720       qCb->side[3].AddContact( dmin, & qCb->side[2], 0 );
1721       qCb->side[3].AddContact( dmin, & qCt->side[3], 0 );
1722       qCt->side[3].AddContact(    0, & qCt->side[0], 0 );
1723       qCt->side[0].AddContact(    0, & qL ->side[0], dmin );
1724       qL ->side[0].AddContact( dmin, & qL ->side[1], 0 );
1725       qL ->side[0].AddContact( dmin, & qCb->side[2], 0 );
1726
1727       if ( dh == dv )
1728         return computeQuadDominant( aMesh, aFace );
1729       else
1730         return computeQuadPref( aMesh, aFace, qCt );
1731
1732     } // if ( dv != 0 && dh != 0 )
1733
1734     // Case dv == 0
1735     //
1736     //     lw   nb  lw = dh/2
1737     //    +------------+
1738     //    |   |    |   |
1739     //    |   | Ct |   |
1740     //    | L |    | R |
1741     //    |   |____|   |
1742     //    |  /      \  |
1743     //    | /   Cb   \ |
1744     //    |/          \|
1745     //    +------------+
1746     const int lw = dh/2; // lateral width
1747     const int bfrom = quad->side[0].from;
1748     const int rfrom = quad->side[1].from;
1749     const int tfrom = quad->side[2].from;
1750     const int lfrom = quad->side[3].from;
1751
1752     const double   lL = quad->side[3].Length();
1753     const double lLwL = quad->side[2].Length( tfrom, tfrom + lw + 1 );
1754     const double yCbL = lLwL / ( lLwL + lL );
1755
1756     const double   lR = quad->side[1].Length();
1757     const double lLwR = quad->side[2].Length( nt - lw - 1, nt );
1758     const double yCbR = lLwR / ( lLwR + lR );
1759
1760     // Make sides separating domains Cb and L and R
1761     StdMeshers_FaceSidePtr sideLCb, sideRCb;
1762     UVPtStruct pTBL, pTBR; // points where 3 domains meat
1763     {
1764       vector<UVPtStruct> pointsLCb( lw+1 ), pointsRCb( lw+1 );
1765       pointsLCb[0] = uv_eb[ 0  + bfrom ];
1766       pointsRCb[0] = uv_eb[ nb + bfrom ];
1767       for ( int i = 1, i2 = nt-2; i <= lw; ++i, --i2 )
1768       {
1769         x  = quad->side[2].Param( i );
1770         y  = yCbL * i / lw;
1771         p0 = quad->side[0].Value2d( x );
1772         p1 = quad->side[1].Value2d( y );
1773         p2 = uv_et[ i + tfrom ].UV();
1774         p3 = quad->side[3].Value2d( y );
1775         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1776         pointsLCb[ i ].u = uv.X();
1777         pointsLCb[ i ].v = uv.Y();
1778         pointsLCb[ i ].x = x;
1779
1780         x  = quad->side[2].Param( i2 );
1781         y  = yCbR * i / lw;
1782         p0 = quad->side[0].Value2d( x );
1783         p2 = uv_et[ i2 + tfrom ].UV();
1784         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1785         pointsRCb[ i ].u = uv.X();
1786         pointsRCb[ i ].v = uv.Y();
1787         pointsRCb[ i ].x = x;
1788       }
1789       sideLCb = StdMeshers_FaceSide::New( pointsLCb, aFace );
1790       sideRCb = StdMeshers_FaceSide::New( pointsRCb, aFace );
1791       pTBL    = pointsLCb.back();
1792       pTBR    = pointsRCb.back();
1793     }
1794     // Make sides separating domains Ct and L and R
1795     StdMeshers_FaceSidePtr sideLCt, sideRCt;
1796     {
1797       vector<UVPtStruct> pointsLCt( nl ), pointsRCt( nl );
1798       pointsLCt[0]     = pTBL;
1799       pointsLCt.back() = uv_et[ lw + tfrom ];
1800       pointsRCt[0]     = pTBR;
1801       pointsRCt.back() = uv_et[ lw + nb - 1 + tfrom ];
1802       x  = pTBL.x;
1803       p0 = quad->side[0].Value2d( x );
1804       p2 = uv_et[ lw + tfrom ].UV();
1805       int     iR = lw + nb - 1;
1806       double  xR = pTBR.x;
1807       gp_UV  p0R = quad->side[0].Value2d( xR );
1808       gp_UV  p2R = uv_et[ iR + tfrom ].UV();
1809       for ( int i = 1; i < nl; ++i )
1810       {
1811         y  = yCbL + ( 1. - yCbL ) * i / nl;
1812         p1 = quad->side[1].Value2d( y );
1813         p3 = quad->side[3].Value2d( y );
1814         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1815         pointsLCt[ i ].u = uv.X();
1816         pointsLCt[ i ].v = uv.Y();
1817
1818         y  = yCbR + ( 1. - yCbR ) * i / nl;
1819         p1 = quad->side[1].Value2d( y );
1820         p3 = quad->side[3].Value2d( y );
1821         uv = calcUV( xR,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1822         pointsRCt[ i ].u = uv.X();
1823         pointsRCt[ i ].v = uv.Y();
1824       }
1825       sideLCt = StdMeshers_FaceSide::New( pointsLCt, aFace );
1826       sideRCt = StdMeshers_FaceSide::New( pointsRCt, aFace );
1827     }
1828     // Make a side separating domains Cb and Ct
1829     StdMeshers_FaceSidePtr sideCbCt;
1830     {
1831       vector<UVPtStruct> pointsCbCt( nb );
1832       pointsCbCt[0]     = pTBL;
1833       pointsCbCt.back() = pTBR;
1834       p1 = quad->side[1].Value2d( yCbR );
1835       p3 = quad->side[3].Value2d( yCbL );
1836       for ( int i = 1; i < nb-1; ++i )
1837       {
1838         x  = quad->side[2].Param( i + lw );
1839         y  = yCbL + ( yCbR - yCbL ) * i / nb;
1840         p2 = uv_et[ i + lw + tfrom ].UV();
1841         p0 = quad->side[0].Value2d( x );
1842         uv = calcUV( x,y, a0,a1,a2,a3, p0,p1,p2,p3 );
1843         pointsCbCt[ i ].u = uv.X();
1844         pointsCbCt[ i ].v = uv.Y();
1845       }
1846       sideCbCt = StdMeshers_FaceSide::New( pointsCbCt, aFace );
1847     }
1848     // Make Cb quad
1849     FaceQuadStruct* qCb = new FaceQuadStruct( quad->face );
1850     myQuadList.push_back( FaceQuadStruct::Ptr( qCb ));
1851     qCb->side.resize(4);
1852     qCb->side[0] = quad->side[0];
1853     qCb->side[1] = sideRCb;
1854     qCb->side[2] = sideCbCt;
1855     qCb->side[3] = sideLCb;
1856     // Make L quad
1857     FaceQuadStruct* qL = new FaceQuadStruct( quad->face );
1858     myQuadList.push_back( FaceQuadStruct::Ptr( qL ));
1859     qL->side.resize(4);
1860     qL->side[0] = sideLCb;
1861     qL->side[1] = sideLCt;
1862     qL->side[2] = quad->side[2];
1863     qL->side[3] = quad->side[3];
1864     qL->side[2].to = lw+1;
1865     // Make R quad
1866     FaceQuadStruct* qR = new FaceQuadStruct( quad->face );
1867     myQuadList.push_back( FaceQuadStruct::Ptr( qR ));
1868     qR->side.resize(4);
1869     qR->side[0] = sideRCb;
1870     qR->side[0].from = lw;
1871     qR->side[0].to   = -1;
1872     qR->side[1] = quad->side[1];
1873     qR->side[2] = quad->side[2];
1874     qR->side[2].from = nb + lw + tfrom;
1875     qR->side[3] = sideRCt;
1876     // Make Ct from the main quad
1877     FaceQuadStruct::Ptr qCt = quad;
1878     qCt->side[0] = sideCbCt;
1879     qCt->side[1] = sideRCt;
1880     qCt->side[2].from = lw + tfrom;
1881     qCt->side[2].to   = nt - lw + tfrom;
1882     qCt->side[3] = sideLCt;
1883     qCt->uv_grid.clear();
1884
1885     // Connect sides
1886     qCb->side[3].AddContact( lw, & qCb->side[2], 0 );
1887     qCb->side[3].AddContact( lw, & qCt->side[3], 0 );
1888     qCt->side[3].AddContact(  0, & qCt->side[0], 0 );
1889     qCt->side[0].AddContact(  0, & qL ->side[0], lw );
1890     qL ->side[0].AddContact( lw, & qL ->side[1], 0 );
1891     qL ->side[0].AddContact( lw, & qCb->side[2], 0 );
1892     //
1893     qCb->side[1].AddContact( lw, & qCb->side[2], lw );
1894     qCb->side[1].AddContact( lw, & qCt->side[1], 0 );
1895     qCt->side[0].AddContact( lw, & qCt->side[1], 0 );
1896     qCt->side[0].AddContact( lw, & qR ->side[0], lw );
1897     qR ->side[3].AddContact( lw, & qR ->side[0], lw );
1898     qR ->side[3].AddContact( lw, & qCb->side[2], lw );
1899
1900     if ( dh == dv )
1901       return computeQuadDominant( aMesh, aFace );
1902
1903
1904   }
1905
1906   if ( dh > dv ) {
1907     addv = (dh-dv)/2;
1908     nbv  = nbv + addv;
1909   }
1910   else { // dv >= dh
1911     addh = (dv-dh)/2;
1912     nbh  = nbh + addh;
1913   }
1914
1915   // arrays for normalized params
1916   TColStd_SequenceOfReal npb, npr, npt, npl;
1917   for (i=0; i<nb; i++) {
1918     npb.Append(uv_eb[i].normParam);
1919   }
1920   for (i=0; i<nr; i++) {
1921     npr.Append(uv_er[i].normParam);
1922   }
1923   for (i=0; i<nt; i++) {
1924     npt.Append(uv_et[i].normParam);
1925   }
1926   for (i=0; i<nl; i++) {
1927     npl.Append(uv_el[i].normParam);
1928   }
1929
1930   int dl,dr;
1931   if (OldVersion) {
1932     // add some params to right and left after the first param
1933     // insert to right
1934     dr = nbv - nr;
1935     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
1936     for (i=1; i<=dr; i++) {
1937       npr.InsertAfter(1,npr.Value(2)-dpr);
1938     }
1939     // insert to left
1940     dl = nbv - nl;
1941     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
1942     for (i=1; i<=dl; i++) {
1943       npl.InsertAfter(1,npl.Value(2)-dpr);
1944     }
1945   }
1946
1947   int nnn = Min(nr,nl);
1948   // auxilary sequence of XY for creation nodes
1949   // in the bottom part of central domain
1950   // Length of UVL and UVR must be == nbv-nnn
1951   TColgp_SequenceOfXY UVL, UVR, UVT;
1952
1953   if (OldVersion) {
1954     // step1: create faces for left domain
1955     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
1956     // add left nodes
1957     for (j=1; j<=nl; j++)
1958       NodesL.SetValue(1,j,uv_el[j-1].node);
1959     if (dl>0) {
1960       // add top nodes
1961       for (i=1; i<=dl; i++)
1962         NodesL.SetValue(i+1,nl,uv_et[i].node);
1963       // create and add needed nodes
1964       TColgp_SequenceOfXY UVtmp;
1965       for (i=1; i<=dl; i++) {
1966         double x0 = npt.Value(i+1);
1967         double x1 = x0;
1968         // diagonal node
1969         double y0 = npl.Value(i+1);
1970         double y1 = npr.Value(i+1);
1971         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1972         gp_Pnt P = S->Value(UV.X(),UV.Y());
1973         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1974         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1975         NodesL.SetValue(i+1,1,N);
1976         if (UVL.Length()<nbv-nnn) UVL.Append(UV);
1977         // internal nodes
1978         for (j=2; j<nl; j++) {
1979           double y0 = npl.Value(dl+j);
1980           double y1 = npr.Value(dl+j);
1981           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1982           gp_Pnt P = S->Value(UV.X(),UV.Y());
1983           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1984           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1985           NodesL.SetValue(i+1,j,N);
1986           if (i==dl) UVtmp.Append(UV);
1987         }
1988       }
1989       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn; i++) {
1990         UVL.Append(UVtmp.Value(i));
1991       }
1992       // create faces
1993       for (i=1; i<=dl; i++) {
1994         for (j=1; j<nl; j++) {
1995           if (WisF) {
1996             SMDS_MeshFace* F =
1997               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
1998                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
1999             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2000           }
2001           else {
2002             SMDS_MeshFace* F =
2003               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i,j+1),
2004                                 NodesL.Value(i+1,j+1), NodesL.Value(i+1,j));
2005             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2006           }
2007         }
2008       }
2009     }
2010     else {
2011       // fill UVL using c2d
2012       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn; i++) {
2013         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
2014       }
2015     }
2016
2017     // step2: create faces for right domain
2018     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
2019     // add right nodes
2020     for (j=1; j<=nr; j++)
2021       NodesR.SetValue(1,j,uv_er[nr-j].node);
2022     if (dr>0) {
2023       // add top nodes
2024       for (i=1; i<=dr; i++)
2025         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
2026       // create and add needed nodes
2027       TColgp_SequenceOfXY UVtmp;
2028       for (i=1; i<=dr; i++) {
2029         double x0 = npt.Value(nt-i);
2030         double x1 = x0;
2031         // diagonal node
2032         double y0 = npl.Value(i+1);
2033         double y1 = npr.Value(i+1);
2034         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2035         gp_Pnt P = S->Value(UV.X(),UV.Y());
2036         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2037         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2038         NodesR.SetValue(i+1,nr,N);
2039         if (UVR.Length()<nbv-nnn) UVR.Append(UV);
2040         // internal nodes
2041         for (j=2; j<nr; j++) {
2042           double y0 = npl.Value(nbv-j+1);
2043           double y1 = npr.Value(nbv-j+1);
2044           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2045           gp_Pnt P = S->Value(UV.X(),UV.Y());
2046           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2047           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2048           NodesR.SetValue(i+1,j,N);
2049           if (i==dr) UVtmp.Prepend(UV);
2050         }
2051       }
2052       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn; i++) {
2053         UVR.Append(UVtmp.Value(i));
2054       }
2055       // create faces
2056       for (i=1; i<=dr; i++) {
2057         for (j=1; j<nr; j++) {
2058           if (WisF) {
2059             SMDS_MeshFace* F =
2060               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
2061                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
2062             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2063           }
2064           else {
2065             SMDS_MeshFace* F =
2066               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i,j+1),
2067                                 NodesR.Value(i+1,j+1), NodesR.Value(i+1,j));
2068             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2069           }
2070         }
2071       }
2072     }
2073     else {
2074       // fill UVR using c2d
2075       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn; i++) {
2076         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
2077       }
2078     }
2079
2080     // step3: create faces for central domain
2081     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
2082     // add first line using NodesL
2083     for (i=1; i<=dl+1; i++)
2084       NodesC.SetValue(1,i,NodesL(i,1));
2085     for (i=2; i<=nl; i++)
2086       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
2087     // add last line using NodesR
2088     for (i=1; i<=dr+1; i++)
2089       NodesC.SetValue(nb,i,NodesR(i,nr));
2090     for (i=1; i<nr; i++)
2091       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
2092     // add top nodes (last columns)
2093     for (i=dl+2; i<nbh-dr; i++)
2094       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
2095     // add bottom nodes (first columns)
2096     for (i=2; i<nb; i++)
2097       NodesC.SetValue(i,1,uv_eb[i-1].node);
2098
2099     // create and add needed nodes
2100     // add linear layers
2101     for (i=2; i<nb; i++) {
2102       double x0 = npt.Value(dl+i);
2103       double x1 = x0;
2104       for (j=1; j<nnn; j++) {
2105         double y0 = npl.Value(nbv-nnn+j);
2106         double y1 = npr.Value(nbv-nnn+j);
2107         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2108         gp_Pnt P = S->Value(UV.X(),UV.Y());
2109         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2110         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2111         NodesC.SetValue(i,nbv-nnn+j,N);
2112         if ( j==1 )
2113           UVT.Append( UV );
2114       }
2115     }
2116     // add diagonal layers
2117     gp_UV A2 = UVR.Value(nbv-nnn);
2118     gp_UV A3 = UVL.Value(nbv-nnn);
2119     for (i=1; i<nbv-nnn; i++) {
2120       gp_UV p1 = UVR.Value(i);
2121       gp_UV p3 = UVL.Value(i);
2122       double y = i / double(nbv-nnn);
2123       for (j=2; j<nb; j++) {
2124         double x = npb.Value(j);
2125         gp_UV p0( uv_eb[j-1].u, uv_eb[j-1].v );
2126         gp_UV p2 = UVT.Value( j-1 );
2127         gp_UV UV = calcUV(x, y, a0, a1, A2, A3, p0,p1,p2,p3 );
2128         gp_Pnt P = S->Value(UV.X(),UV.Y());
2129         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2130         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
2131         NodesC.SetValue(j,i+1,N);
2132       }
2133     }
2134     // create faces
2135     for (i=1; i<nb; i++) {
2136       for (j=1; j<nbv; j++) {
2137         if (WisF) {
2138           SMDS_MeshFace* F =
2139             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2140                               NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2141           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2142         }
2143         else {
2144           SMDS_MeshFace* F =
2145             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i,j+1),
2146                               NodesC.Value(i+1,j+1), NodesC.Value(i+1,j));
2147           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2148         }
2149       }
2150     }
2151   }
2152
2153   else { // New version (!OldVersion)
2154     // step1: create faces for bottom rectangle domain
2155     StdMeshers_Array2OfNode NodesBRD(1,nb,1,nnn-1);
2156     // fill UVL and UVR using c2d
2157     for (j=0; j<nb; j++) {
2158       NodesBRD.SetValue(j+1,1,uv_eb[j].node);
2159     }
2160     for (i=1; i<nnn-1; i++) {
2161       NodesBRD.SetValue(1,i+1,uv_el[i].node);
2162       NodesBRD.SetValue(nb,i+1,uv_er[i].node);
2163       for (j=2; j<nb; j++) {
2164         double x = npb.Value(j);
2165         double y = (1-x) * npl.Value(i+1) + x * npr.Value(i+1);
2166         gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2167         gp_Pnt P = S->Value(UV.X(),UV.Y());
2168         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2169         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
2170         NodesBRD.SetValue(j,i+1,N);
2171       }
2172     }
2173     for (j=1; j<nnn-1; j++) {
2174       for (i=1; i<nb; i++) {
2175         if (WisF) {
2176           SMDS_MeshFace* F =
2177             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i+1,j),
2178                               NodesBRD.Value(i+1,j+1), NodesBRD.Value(i,j+1));
2179           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2180         }
2181         else {
2182           SMDS_MeshFace* F =
2183             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i,j+1),
2184                               NodesBRD.Value(i+1,j+1), NodesBRD.Value(i+1,j));
2185           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2186         }
2187       }
2188     }
2189     int drl = abs(nr-nl);
2190     // create faces for region C
2191     StdMeshers_Array2OfNode NodesC(1,nb,1,drl+1+addv);
2192     // add nodes from previous region
2193     for (j=1; j<=nb; j++) {
2194       NodesC.SetValue(j,1,NodesBRD.Value(j,nnn-1));
2195     }
2196     if ((drl+addv) > 0) {
2197       int n1,n2;
2198       if (nr>nl) {
2199         n1 = 1;
2200         n2 = drl + 1;
2201         TColgp_SequenceOfXY UVtmp;
2202         double drparam = npr.Value(nr) - npr.Value(nnn-1);
2203         double dlparam = npl.Value(nnn) - npl.Value(nnn-1);
2204         double y0,y1;
2205         for (i=1; i<=drl; i++) {
2206           // add existed nodes from right edge
2207           NodesC.SetValue(nb,i+1,uv_er[nnn+i-2].node);
2208           //double dtparam = npt.Value(i+1);
2209           y1 = npr.Value(nnn+i-1); // param on right edge
2210           double dpar = (y1 - npr.Value(nnn-1))/drparam;
2211           y0 = npl.Value(nnn-1) + dpar*dlparam; // param on left edge
2212           double dy = y1 - y0;
2213           for (j=1; j<nb; j++) {
2214             double x = npt.Value(i+1) + npb.Value(j)*(1-npt.Value(i+1));
2215             double y = y0 + dy*x;
2216             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2217             gp_Pnt P = S->Value(UV.X(),UV.Y());
2218             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2219             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2220             NodesC.SetValue(j,i+1,N);
2221           }
2222         }
2223         double dy0 = (1-y0)/(addv+1);
2224         double dy1 = (1-y1)/(addv+1);
2225         for (i=1; i<=addv; i++) {
2226           double yy0 = y0 + dy0*i;
2227           double yy1 = y1 + dy1*i;
2228           double dyy = yy1 - yy0;
2229           for (j=1; j<=nb; j++) {
2230             double x = npt.Value(i+1+drl) +
2231               npb.Value(j) * (npt.Value(nt-i) - npt.Value(i+1+drl));
2232             double y = yy0 + dyy*x;
2233             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2234             gp_Pnt P = S->Value(UV.X(),UV.Y());
2235             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2236             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2237             NodesC.SetValue(j,i+drl+1,N);
2238           }
2239         }
2240       }
2241       else { // nr<nl
2242         n2 = 1;
2243         n1 = drl + 1;
2244         TColgp_SequenceOfXY UVtmp;
2245         double dlparam = npl.Value(nl) - npl.Value(nnn-1);
2246         double drparam = npr.Value(nnn) - npr.Value(nnn-1);
2247         double y0 = npl.Value(nnn-1);
2248         double y1 = npr.Value(nnn-1);
2249         for (i=1; i<=drl; i++) {
2250           // add existed nodes from right edge
2251           NodesC.SetValue(1,i+1,uv_el[nnn+i-2].node);
2252           y0 = npl.Value(nnn+i-1); // param on left edge
2253           double dpar = (y0 - npl.Value(nnn-1))/dlparam;
2254           y1 = npr.Value(nnn-1) + dpar*drparam; // param on right edge
2255           double dy = y1 - y0;
2256           for (j=2; j<=nb; j++) {
2257             double x = npb.Value(j)*npt.Value(nt-i);
2258             double y = y0 + dy*x;
2259             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2260             gp_Pnt P = S->Value(UV.X(),UV.Y());
2261             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2262             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2263             NodesC.SetValue(j,i+1,N);
2264           }
2265         }
2266         double dy0 = (1-y0)/(addv+1);
2267         double dy1 = (1-y1)/(addv+1);
2268         for (i=1; i<=addv; i++) {
2269           double yy0 = y0 + dy0*i;
2270           double yy1 = y1 + dy1*i;
2271           double dyy = yy1 - yy0;
2272           for (j=1; j<=nb; j++) {
2273             double x = npt.Value(i+1) +
2274               npb.Value(j) * (npt.Value(nt-i-drl) - npt.Value(i+1));
2275             double y = yy0 + dyy*x;
2276             gp_UV UV = calcUV2(x, y, quad, a0, a1, a2, a3);
2277             gp_Pnt P = S->Value(UV.X(),UV.Y());
2278             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2279             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2280             NodesC.SetValue(j,i+drl+1,N);
2281           }
2282         }
2283       }
2284       // create faces
2285       for (j=1; j<=drl+addv; j++) {
2286         for (i=1; i<nb; i++) {
2287           if (WisF) {
2288             SMDS_MeshFace* F =
2289               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2290                                 NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2291             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2292           }
2293           else {
2294             SMDS_MeshFace* F =
2295               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i,j+1),
2296                                 NodesC.Value(i+1,j+1), NodesC.Value(i+1,j));
2297             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2298           }
2299         }
2300       } // end nr<nl
2301
2302       StdMeshers_Array2OfNode NodesLast(1,nt,1,2);
2303       for (i=1; i<=nt; i++) {
2304         NodesLast.SetValue(i,2,uv_et[i-1].node);
2305       }
2306       int nnn=0;
2307       for (i=n1; i<drl+addv+1; i++) {
2308         nnn++;
2309         NodesLast.SetValue(nnn,1,NodesC.Value(1,i));
2310       }
2311       for (i=1; i<=nb; i++) {
2312         nnn++;
2313         NodesLast.SetValue(nnn,1,NodesC.Value(i,drl+addv+1));
2314       }
2315       for (i=drl+addv; i>=n2; i--) {
2316         nnn++;
2317         NodesLast.SetValue(nnn,1,NodesC.Value(nb,i));
2318       }
2319       for (i=1; i<nt; i++) {
2320         if (WisF) {
2321           SMDS_MeshFace* F =
2322             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i+1,1),
2323                               NodesLast.Value(i+1,2), NodesLast.Value(i,2));
2324           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2325         }
2326         else {
2327           SMDS_MeshFace* F =
2328             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i,2),
2329                               NodesLast.Value(i+1,2), NodesLast.Value(i+1,2));
2330           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2331         }
2332       }
2333     } // if ((drl+addv) > 0)
2334
2335   } // end new version implementation
2336
2337   bool isOk = true;
2338   return isOk;
2339 }
2340
2341
2342 //=======================================================================
2343 /*!
2344  * Evaluate only quandrangle faces
2345  */
2346 //=======================================================================
2347
2348 bool StdMeshers_Quadrangle_2D::evaluateQuadPref(SMESH_Mesh &        aMesh,
2349                                                 const TopoDS_Shape& aShape,
2350                                                 std::vector<int>&   aNbNodes,
2351                                                 MapShapeNbElems&    aResMap,
2352                                                 bool                IsQuadratic)
2353 {
2354   // Auxilary key in order to keep old variant
2355   // of meshing after implementation new variant
2356   // for bug 0016220 from Mantis.
2357   bool OldVersion = false;
2358   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
2359     OldVersion = true;
2360
2361   const TopoDS_Face& F = TopoDS::Face(aShape);
2362   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
2363
2364   int nb = aNbNodes[0];
2365   int nr = aNbNodes[1];
2366   int nt = aNbNodes[2];
2367   int nl = aNbNodes[3];
2368   int dh = abs(nb-nt);
2369   int dv = abs(nr-nl);
2370
2371   if (dh>=dv) {
2372     if (nt>nb) {
2373       // it is a base case => not shift 
2374     }
2375     else {
2376       // we have to shift on 2
2377       nb = aNbNodes[2];
2378       nr = aNbNodes[3];
2379       nt = aNbNodes[0];
2380       nl = aNbNodes[1];
2381     }
2382   }
2383   else {
2384     if (nr>nl) {
2385       // we have to shift quad on 1
2386       nb = aNbNodes[3];
2387       nr = aNbNodes[0];
2388       nt = aNbNodes[1];
2389       nl = aNbNodes[2];
2390     }
2391     else {
2392       // we have to shift quad on 3
2393       nb = aNbNodes[1];
2394       nr = aNbNodes[2];
2395       nt = aNbNodes[3];
2396       nl = aNbNodes[0];
2397     }
2398   }
2399
2400   dh = abs(nb-nt);
2401   dv = abs(nr-nl);
2402   int nbh  = Max(nb,nt);
2403   int nbv = Max(nr,nl);
2404   int addh = 0;
2405   int addv = 0;
2406
2407   if (dh>dv) {
2408     addv = (dh-dv)/2;
2409     nbv = nbv + addv;
2410   }
2411   else { // dv>=dh
2412     addh = (dv-dh)/2;
2413     nbh = nbh + addh;
2414   }
2415
2416   int dl,dr;
2417   if (OldVersion) {
2418     // add some params to right and left after the first param
2419     // insert to right
2420     dr = nbv - nr;
2421     // insert to left
2422     dl = nbv - nl;
2423   }
2424   
2425   int nnn = Min(nr,nl);
2426
2427   int nbNodes = 0;
2428   int nbFaces = 0;
2429   if (OldVersion) {
2430     // step1: create faces for left domain
2431     if (dl>0) {
2432       nbNodes += dl*(nl-1);
2433       nbFaces += dl*(nl-1);
2434     }
2435     // step2: create faces for right domain
2436     if (dr>0) {
2437       nbNodes += dr*(nr-1);
2438       nbFaces += dr*(nr-1);
2439     }
2440     // step3: create faces for central domain
2441     nbNodes += (nb-2)*(nnn-1) + (nbv-nnn-1)*(nb-2);
2442     nbFaces += (nb-1)*(nbv-1);
2443   }
2444   else { // New version (!OldVersion)
2445     nbNodes += (nnn-2)*(nb-2);
2446     nbFaces += (nnn-2)*(nb-1);
2447     int drl = abs(nr-nl);
2448     nbNodes += drl*(nb-1) + addv*nb;
2449     nbFaces += (drl+addv)*(nb-1) + (nt-1);
2450   } // end new version implementation
2451
2452   std::vector<int> aVec(SMDSEntity_Last);
2453   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
2454   if (IsQuadratic) {
2455     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces;
2456     aVec[SMDSEntity_Node] = nbNodes + nbFaces*4;
2457     if (aNbNodes.size()==5) {
2458       aVec[SMDSEntity_Quad_Triangle] = aNbNodes[3] - 1;
2459       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2460     }
2461   }
2462   else {
2463     aVec[SMDSEntity_Node] = nbNodes;
2464     aVec[SMDSEntity_Quadrangle] = nbFaces;
2465     if (aNbNodes.size()==5) {
2466       aVec[SMDSEntity_Triangle] = aNbNodes[3] - 1;
2467       aVec[SMDSEntity_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2468     }
2469   }
2470   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
2471   aResMap.insert(std::make_pair(sm,aVec));
2472
2473   return true;
2474 }
2475
2476 //=============================================================================
2477 /*! Split quadrangle in to 2 triangles by smallest diagonal
2478  *   
2479  */
2480 //=============================================================================
2481
2482 void StdMeshers_Quadrangle_2D::splitQuadFace(SMESHDS_Mesh *       theMeshDS,
2483                                              int                  theFaceID,
2484                                              const SMDS_MeshNode* theNode1,
2485                                              const SMDS_MeshNode* theNode2,
2486                                              const SMDS_MeshNode* theNode3,
2487                                              const SMDS_MeshNode* theNode4)
2488 {
2489   SMDS_MeshFace* face;
2490   if ( SMESH_TNodeXYZ( theNode1 ).SquareDistance( theNode3 ) >
2491        SMESH_TNodeXYZ( theNode2 ).SquareDistance( theNode4 ) )
2492   {
2493     face = myHelper->AddFace(theNode2, theNode4 , theNode1);
2494     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2495     face = myHelper->AddFace(theNode2, theNode3, theNode4);
2496     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2497   }
2498   else
2499   {
2500     face = myHelper->AddFace(theNode1, theNode2 ,theNode3);
2501     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2502     face = myHelper->AddFace(theNode1, theNode3, theNode4);
2503     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2504   }
2505 }
2506
2507 namespace
2508 {
2509   enum uvPos { UV_A0, UV_A1, UV_A2, UV_A3, UV_B, UV_R, UV_T, UV_L, UV_SIZE };
2510
2511   inline  SMDS_MeshNode* makeNode( UVPtStruct &         uvPt,
2512                                    const double         y,
2513                                    FaceQuadStruct::Ptr& quad,
2514                                    const gp_UV*         UVs,
2515                                    SMESH_MesherHelper*  helper,
2516                                    Handle(Geom_Surface) S)
2517   {
2518     const vector<UVPtStruct>& uv_eb = quad->side[QUAD_BOTTOM_SIDE].GetUVPtStruct();
2519     const vector<UVPtStruct>& uv_et = quad->side[QUAD_TOP_SIDE   ].GetUVPtStruct();
2520     double rBot = ( uv_eb.size() - 1 ) * uvPt.normParam;
2521     double rTop = ( uv_et.size() - 1 ) * uvPt.normParam;
2522     int iBot = int( rBot );
2523     int iTop = int( rTop );
2524     double xBot = uv_eb[ iBot ].normParam + ( rBot - iBot ) * ( uv_eb[ iBot+1 ].normParam - uv_eb[ iBot ].normParam );
2525     double xTop = uv_et[ iTop ].normParam + ( rTop - iTop ) * ( uv_et[ iTop+1 ].normParam - uv_et[ iTop ].normParam );
2526     double x = xBot + y * ( xTop - xBot );
2527     
2528     gp_UV uv = calcUV(/*x,y=*/x, y,
2529                       /*a0,...=*/UVs[UV_A0], UVs[UV_A1], UVs[UV_A2], UVs[UV_A3],
2530                       /*p0=*/quad->side[QUAD_BOTTOM_SIDE].grid->Value2d( x ).XY(),
2531                       /*p1=*/UVs[ UV_R ],
2532                       /*p2=*/quad->side[QUAD_TOP_SIDE   ].grid->Value2d( x ).XY(),
2533                       /*p3=*/UVs[ UV_L ]);
2534     gp_Pnt P = S->Value( uv.X(), uv.Y() );
2535     uvPt.u = uv.X();
2536     uvPt.v = uv.Y();
2537     return helper->AddNode(P.X(), P.Y(), P.Z(), 0, uv.X(), uv.Y() );
2538   }
2539
2540   void reduce42( const vector<UVPtStruct>& curr_base,
2541                  vector<UVPtStruct>&       next_base,
2542                  const int                 j,
2543                  int &                     next_base_len,
2544                  FaceQuadStruct::Ptr&      quad,
2545                  gp_UV*                    UVs,
2546                  const double              y,
2547                  SMESH_MesherHelper*       helper,
2548                  Handle(Geom_Surface)&     S)
2549   {
2550     // add one "HH": nodes a,b,c,d,e and faces 1,2,3,4,5,6
2551     //
2552     //  .-----a-----b i + 1
2553     //  |\ 5  | 6  /|
2554     //  | \   |   / |
2555     //  |  c--d--e  |
2556     //  |1 |2 |3 |4 |
2557     //  |  |  |  |  |
2558     //  .--.--.--.--. i
2559     //
2560     //  j     j+2   j+4
2561
2562     // a (i + 1, j + 2)
2563     const SMDS_MeshNode*& Na = next_base[ ++next_base_len ].node;
2564     if ( !Na )
2565       Na = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2566
2567     // b (i + 1, j + 4)
2568     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2569     if ( !Nb )
2570       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2571
2572     // c
2573     double u = (curr_base[j + 2].u + next_base[next_base_len - 2].u) / 2.0;
2574     double v = (curr_base[j + 2].v + next_base[next_base_len - 2].v) / 2.0;
2575     gp_Pnt P = S->Value(u,v);
2576     SMDS_MeshNode* Nc = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2577
2578     // d
2579     u = (curr_base[j + 2].u + next_base[next_base_len - 1].u) / 2.0;
2580     v = (curr_base[j + 2].v + next_base[next_base_len - 1].v) / 2.0;
2581     P = S->Value(u,v);
2582     SMDS_MeshNode* Nd = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2583
2584     // e
2585     u = (curr_base[j + 2].u + next_base[next_base_len].u) / 2.0;
2586     v = (curr_base[j + 2].v + next_base[next_base_len].v) / 2.0;
2587     P = S->Value(u,v);
2588     SMDS_MeshNode* Ne = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2589
2590     // Faces
2591     helper->AddFace(curr_base[j + 0].node,
2592                     curr_base[j + 1].node, Nc,
2593                     next_base[next_base_len - 2].node);
2594
2595     helper->AddFace(curr_base[j + 1].node,
2596                     curr_base[j + 2].node, Nd, Nc);
2597
2598     helper->AddFace(curr_base[j + 2].node,
2599                     curr_base[j + 3].node, Ne, Nd);
2600
2601     helper->AddFace(curr_base[j + 3].node,
2602                     curr_base[j + 4].node, Nb, Ne);
2603
2604     helper->AddFace(Nc, Nd, Na, next_base[next_base_len - 2].node);
2605
2606     helper->AddFace(Nd, Ne, Nb, Na);
2607   }
2608
2609   void reduce31( const vector<UVPtStruct>& curr_base,
2610                  vector<UVPtStruct>&       next_base,
2611                  const int                 j,
2612                  int &                     next_base_len,
2613                  FaceQuadStruct::Ptr&      quad,
2614                  gp_UV*                    UVs,
2615                  const double              y,
2616                  SMESH_MesherHelper*       helper,
2617                  Handle(Geom_Surface)&     S)
2618   {
2619     // add one "H": nodes b,c,e and faces 1,2,4,5
2620     //
2621     //  .---------b i + 1
2622     //  |\   5   /|
2623     //  | \     / |
2624     //  |  c---e  |
2625     //  |1 |2  |4 |
2626     //  |  |   |  |
2627     //  .--.---.--. i
2628     //
2629     //  j j+1 j+2 j+3
2630
2631     // b (i + 1, j + 3)
2632     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2633     if ( !Nb )
2634       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2635
2636     // c and e
2637     double u1 = (curr_base[ j   ].u + next_base[ next_base_len-1 ].u ) / 2.0;
2638     double u2 = (curr_base[ j+3 ].u + next_base[ next_base_len   ].u ) / 2.0;
2639     double u3 = (u2 - u1) / 3.0;
2640     //
2641     double v1 = (curr_base[ j   ].v + next_base[ next_base_len-1 ].v ) / 2.0;
2642     double v2 = (curr_base[ j+3 ].v + next_base[ next_base_len   ].v ) / 2.0;
2643     double v3 = (v2 - v1) / 3.0;
2644     // c
2645     double u = u1 + u3;
2646     double v = v1 + v3;
2647     gp_Pnt P = S->Value(u,v);
2648     SMDS_MeshNode* Nc = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2649     // e
2650     u = u1 + u3 + u3;
2651     v = v1 + v3 + v3;
2652     P = S->Value(u,v);
2653     SMDS_MeshNode* Ne = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2654
2655     // Faces
2656     // 1
2657     helper->AddFace( curr_base[ j + 0 ].node,
2658                      curr_base[ j + 1 ].node,
2659                      Nc,
2660                      next_base[ next_base_len - 1 ].node);
2661     // 2
2662     helper->AddFace( curr_base[ j + 1 ].node,
2663                      curr_base[ j + 2 ].node, Ne, Nc);
2664     // 4
2665     helper->AddFace( curr_base[ j + 2 ].node,
2666                      curr_base[ j + 3 ].node, Nb, Ne);
2667     // 5
2668     helper->AddFace(Nc, Ne, Nb,
2669                     next_base[ next_base_len - 1 ].node);
2670   }
2671
2672   typedef void (* PReduceFunction) ( const vector<UVPtStruct>& curr_base,
2673                                      vector<UVPtStruct>&       next_base,
2674                                      const int                 j,
2675                                      int &                     next_base_len,
2676                                      FaceQuadStruct::Ptr &     quad,
2677                                      gp_UV*                    UVs,
2678                                      const double              y,
2679                                      SMESH_MesherHelper*       helper,
2680                                      Handle(Geom_Surface)&     S);
2681
2682 } // namespace
2683
2684 //=======================================================================
2685 /*!
2686  *  Implementation of Reduced algorithm (meshing with quadrangles only)
2687  */
2688 //=======================================================================
2689
2690 bool StdMeshers_Quadrangle_2D::computeReduced (SMESH_Mesh &        aMesh,
2691                                                const TopoDS_Face&  aFace,
2692                                                FaceQuadStruct::Ptr quad)
2693 {
2694   SMESHDS_Mesh * meshDS  = aMesh.GetMeshDS();
2695   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace);
2696   int i,j,geomFaceID     = meshDS->ShapeToIndex(aFace);
2697
2698   int nb = quad->side[0].grid->NbPoints(); // bottom
2699   int nr = quad->side[1].grid->NbPoints(); // right
2700   int nt = quad->side[2].grid->NbPoints(); // top
2701   int nl = quad->side[3].grid->NbPoints(); // left
2702
2703   //  Simple Reduce 10->8->6->4 (3 steps)     Multiple Reduce 10->4 (1 step)
2704   //
2705   //  .-----.-----.-----.-----.               .-----.-----.-----.-----.
2706   //  |    / \    |    / \    |               |    / \    |    / \    |
2707   //  |   /    .--.--.    \   |               |    / \    |    / \    |
2708   //  |   /   /   |   \   \   |               |   /  .----.----.  \   |
2709   //  .---.---.---.---.---.---.               |   / / \   |   / \ \   |
2710   //  |   /  / \  |  / \  \   |               |   / / \   |   / \ \   |
2711   //  |  /  /   .-.-.   \  \  |               |  / /  .---.---.  \ \  |
2712   //  |  /  /  /  |  \  \  \  |               |  / / / \  |  / \ \ \  |
2713   //  .--.--.--.--.--.--.--.--.               |  / / /  \ | /  \ \ \  |
2714   //  |  / /  / \ | / \  \ \  |               | / / /   .-.-.   \ \ \ |
2715   //  | / /  /  .-.-.  \  \ \ |               | / / /  /  |  \  \ \ \ |
2716   //  | / / /  /  |  \  \ \ \ |               | / / /  /  |  \  \ \ \ |
2717   //  .-.-.-.--.--.--.--.-.-.-.               .-.-.-.--.--.--.--.-.-.-.
2718
2719   bool MultipleReduce = false;
2720   {
2721     int nb1 = nb;
2722     int nr1 = nr;
2723     int nt1 = nt;
2724
2725     if (nr == nl) {
2726       if (nb < nt) {
2727         nt1 = nb;
2728         nb1 = nt;
2729       }
2730     }
2731     else if (nb == nt) {
2732       nr1 = nb; // and == nt
2733       if (nl < nr) {
2734         nt1 = nl;
2735         nb1 = nr;
2736       }
2737       else {
2738         nt1 = nr;
2739         nb1 = nl;
2740       }
2741     }
2742     else {
2743       return false;
2744     }
2745
2746     // number of rows and columns
2747     int nrows    = nr1 - 1;
2748     int ncol_top = nt1 - 1;
2749     int ncol_bot = nb1 - 1;
2750     // number of rows needed to reduce ncol_bot to ncol_top using simple 3->1 "tree" (see below)
2751     int nrows_tree31 =
2752       int( ceil( log( double(ncol_bot) / ncol_top) / log( 3.))); // = log x base 3
2753     if ( nrows < nrows_tree31 )
2754     {
2755       MultipleReduce = true;
2756       error( COMPERR_WARNING,
2757              SMESH_Comment("To use 'Reduced' transition, "
2758                            "number of face rows should be at least ")
2759              << nrows_tree31 << ". Actual number of face rows is " << nrows << ". "
2760              "'Quadrangle preference (reversed)' transion has been used.");
2761     }
2762   }
2763
2764   if (MultipleReduce) { // == computeQuadPref QUAD_QUADRANGLE_PREF_REVERSED
2765     //==================================================
2766     int dh = abs(nb-nt);
2767     int dv = abs(nr-nl);
2768
2769     if (dh >= dv) {
2770       if (nt > nb) {
2771         // it is a base case => not shift quad but may be replacement is need
2772         shiftQuad(quad,0);
2773       }
2774       else {
2775         // we have to shift quad on 2
2776         shiftQuad(quad,2);
2777       }
2778     }
2779     else {
2780       if (nr > nl) {
2781         // we have to shift quad on 1
2782         shiftQuad(quad,1);
2783       }
2784       else {
2785         // we have to shift quad on 3
2786         shiftQuad(quad,3);
2787       }
2788     }
2789
2790     nb = quad->side[0].grid->NbPoints();
2791     nr = quad->side[1].grid->NbPoints();
2792     nt = quad->side[2].grid->NbPoints();
2793     nl = quad->side[3].grid->NbPoints();
2794     dh = abs(nb-nt);
2795     dv = abs(nr-nl);
2796     int nbh = Max(nb,nt);
2797     int nbv = Max(nr,nl);
2798     int addh = 0;
2799     int addv = 0;
2800
2801     if (dh>dv) {
2802       addv = (dh-dv)/2;
2803       nbv = nbv + addv;
2804     }
2805     else { // dv>=dh
2806       addh = (dv-dh)/2;
2807       nbh = nbh + addh;
2808     }
2809
2810     const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
2811     const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
2812     const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
2813     const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
2814
2815     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2816       return error(COMPERR_BAD_INPUT_MESH);
2817
2818     // arrays for normalized params
2819     TColStd_SequenceOfReal npb, npr, npt, npl;
2820     for (j = 0; j < nb; j++) {
2821       npb.Append(uv_eb[j].normParam);
2822     }
2823     for (i = 0; i < nr; i++) {
2824       npr.Append(uv_er[i].normParam);
2825     }
2826     for (j = 0; j < nt; j++) {
2827       npt.Append(uv_et[j].normParam);
2828     }
2829     for (i = 0; i < nl; i++) {
2830       npl.Append(uv_el[i].normParam);
2831     }
2832
2833     int dl,dr;
2834     // orientation of face and 3 main domain for future faces
2835     //       0   top    1
2836     //      1------------1
2837     //       |   |  |   |
2838     //       |   |  |   |
2839     //       | L |  | R |
2840     //  left |   |  |   | rigth
2841     //       |  /    \  |
2842     //       | /  C   \ |
2843     //       |/        \|
2844     //      0------------0
2845     //       0  bottom  1
2846
2847     // add some params to right and left after the first param
2848     // insert to right
2849     dr = nbv - nr;
2850     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
2851     for (i=1; i<=dr; i++) {
2852       npr.InsertAfter(1,npr.Value(2)-dpr);
2853     }
2854     // insert to left
2855     dl = nbv - nl;
2856     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
2857     for (i=1; i<=dl; i++) {
2858       npl.InsertAfter(1,npl.Value(2)-dpr);
2859     }
2860   
2861     gp_XY a0 (uv_eb.front().u, uv_eb.front().v);
2862     gp_XY a1 (uv_eb.back().u,  uv_eb.back().v);
2863     gp_XY a2 (uv_et.back().u,  uv_et.back().v);
2864     gp_XY a3 (uv_et.front().u, uv_et.front().v);
2865
2866     int nnn = Min(nr,nl);
2867     // auxilary sequence of XY for creation of nodes
2868     // in the bottom part of central domain
2869     // it's length must be == nbv-nnn-1
2870     TColgp_SequenceOfXY UVL;
2871     TColgp_SequenceOfXY UVR;
2872     //==================================================
2873
2874     // step1: create faces for left domain
2875     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
2876     // add left nodes
2877     for (j=1; j<=nl; j++)
2878       NodesL.SetValue(1,j,uv_el[j-1].node);
2879     if (dl>0) {
2880       // add top nodes
2881       for (i=1; i<=dl; i++) 
2882         NodesL.SetValue(i+1,nl,uv_et[i].node);
2883       // create and add needed nodes
2884       TColgp_SequenceOfXY UVtmp;
2885       for (i=1; i<=dl; i++) {
2886         double x0 = npt.Value(i+1);
2887         double x1 = x0;
2888         // diagonal node
2889         double y0 = npl.Value(i+1);
2890         double y1 = npr.Value(i+1);
2891         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2892         gp_Pnt P = S->Value(UV.X(),UV.Y());
2893         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2894         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2895         NodesL.SetValue(i+1,1,N);
2896         if (UVL.Length()<nbv-nnn-1) UVL.Append(UV);
2897         // internal nodes
2898         for (j=2; j<nl; j++) {
2899           double y0 = npl.Value(dl+j);
2900           double y1 = npr.Value(dl+j);
2901           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2902           gp_Pnt P = S->Value(UV.X(),UV.Y());
2903           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2904           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2905           NodesL.SetValue(i+1,j,N);
2906           if (i==dl) UVtmp.Append(UV);
2907         }
2908       }
2909       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn-1; i++) {
2910         UVL.Append(UVtmp.Value(i));
2911       }
2912       // create faces
2913       for (i=1; i<=dl; i++) {
2914         for (j=1; j<nl; j++) {
2915             SMDS_MeshFace* F =
2916               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
2917                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
2918             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2919         }
2920       }
2921     }
2922     else {
2923       // fill UVL using c2d
2924       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn-1; i++) {
2925         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
2926       }
2927     }
2928     
2929     // step2: create faces for right domain
2930     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
2931     // add right nodes
2932     for (j=1; j<=nr; j++) 
2933       NodesR.SetValue(1,j,uv_er[nr-j].node);
2934     if (dr>0) {
2935       // add top nodes
2936       for (i=1; i<=dr; i++) 
2937         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
2938       // create and add needed nodes
2939       TColgp_SequenceOfXY UVtmp;
2940       for (i=1; i<=dr; i++) {
2941         double x0 = npt.Value(nt-i);
2942         double x1 = x0;
2943         // diagonal node
2944         double y0 = npl.Value(i+1);
2945         double y1 = npr.Value(i+1);
2946         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2947         gp_Pnt P = S->Value(UV.X(),UV.Y());
2948         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2949         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2950         NodesR.SetValue(i+1,nr,N);
2951         if (UVR.Length()<nbv-nnn-1) UVR.Append(UV);
2952         // internal nodes
2953         for (j=2; j<nr; j++) {
2954           double y0 = npl.Value(nbv-j+1);
2955           double y1 = npr.Value(nbv-j+1);
2956           gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2957           gp_Pnt P = S->Value(UV.X(),UV.Y());
2958           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2959           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2960           NodesR.SetValue(i+1,j,N);
2961           if (i==dr) UVtmp.Prepend(UV);
2962         }
2963       }
2964       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn-1; i++) {
2965         UVR.Append(UVtmp.Value(i));
2966       }
2967       // create faces
2968       for (i=1; i<=dr; i++) {
2969         for (j=1; j<nr; j++) {
2970             SMDS_MeshFace* F =
2971               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
2972                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
2973             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2974         }
2975       }
2976     }
2977     else {
2978       // fill UVR using c2d
2979       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn-1; i++) {
2980         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
2981       }
2982     }
2983     
2984     // step3: create faces for central domain
2985     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
2986     // add first line using NodesL
2987     for (i=1; i<=dl+1; i++)
2988       NodesC.SetValue(1,i,NodesL(i,1));
2989     for (i=2; i<=nl; i++)
2990       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
2991     // add last line using NodesR
2992     for (i=1; i<=dr+1; i++)
2993       NodesC.SetValue(nb,i,NodesR(i,nr));
2994     for (i=1; i<nr; i++)
2995       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
2996     // add top nodes (last columns)
2997     for (i=dl+2; i<nbh-dr; i++) 
2998       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
2999     // add bottom nodes (first columns)
3000     for (i=2; i<nb; i++)
3001       NodesC.SetValue(i,1,uv_eb[i-1].node);
3002
3003     // create and add needed nodes
3004     // add linear layers
3005     for (i=2; i<nb; i++) {
3006       double x0 = npt.Value(dl+i);
3007       double x1 = x0;
3008       for (j=1; j<nnn; j++) {
3009         double y0 = npl.Value(nbv-nnn+j);
3010         double y1 = npr.Value(nbv-nnn+j);
3011         gp_UV UV = calcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
3012         gp_Pnt P = S->Value(UV.X(),UV.Y());
3013         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3014         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
3015         NodesC.SetValue(i,nbv-nnn+j,N);
3016       }
3017     }
3018     // add diagonal layers
3019     for (i=1; i<nbv-nnn; i++) {
3020       double du = UVR.Value(i).X() - UVL.Value(i).X();
3021       double dv = UVR.Value(i).Y() - UVL.Value(i).Y();
3022       for (j=2; j<nb; j++) {
3023         double u = UVL.Value(i).X() + du*npb.Value(j);
3024         double v = UVL.Value(i).Y() + dv*npb.Value(j);
3025         gp_Pnt P = S->Value(u,v);
3026         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
3027         meshDS->SetNodeOnFace(N, geomFaceID, u, v);
3028         NodesC.SetValue(j,i+1,N);
3029       }
3030     }
3031     // create faces
3032     for (i=1; i<nb; i++) {
3033       for (j=1; j<nbv; j++) {
3034         SMDS_MeshFace* F =
3035           myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
3036                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
3037         if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
3038       }
3039     }
3040   } // end Multiple Reduce implementation
3041   else { // Simple Reduce (!MultipleReduce)
3042     //=========================================================
3043     if (nr == nl) {
3044       if (nt < nb) {
3045         // it is a base case => not shift quad
3046         //shiftQuad(quad,0,true);
3047       }
3048       else {
3049         // we have to shift quad on 2
3050         shiftQuad(quad,2);
3051       }
3052     }
3053     else {
3054       if (nl > nr) {
3055         // we have to shift quad on 1
3056         shiftQuad(quad,1);
3057       }
3058       else {
3059         // we have to shift quad on 3
3060         shiftQuad(quad,3);
3061       }
3062     }
3063
3064     nb = quad->side[0].grid->NbPoints();
3065     nr = quad->side[1].grid->NbPoints();
3066     nt = quad->side[2].grid->NbPoints();
3067     nl = quad->side[3].grid->NbPoints();
3068
3069     // number of rows and columns
3070     int nrows = nr - 1; // and also == nl - 1
3071     int ncol_top = nt - 1;
3072     int ncol_bot = nb - 1;
3073     int npair_top = ncol_top / 2;
3074     // maximum number of bottom elements for "linear" simple reduce 4->2
3075     int max_lin42 = ncol_top + npair_top * 2 * nrows;
3076     // maximum number of bottom elements for "linear" simple reduce 3->1
3077     int max_lin31 = ncol_top + ncol_top * 2 * nrows;
3078     // maximum number of bottom elements for "tree" simple reduce 4->2
3079     int max_tree42 = 0;
3080     // number of rows needed to reduce ncol_bot to ncol_top using simple 4->2 "tree"
3081     int nrows_tree42 = int( log( (double)(ncol_bot / ncol_top) )/log((double)2)  ); // needed to avoid overflow at pow(2) while computing max_tree42
3082     if (nrows_tree42 < nrows) {
3083       max_tree42 = npair_top * pow(2.0, nrows + 1);
3084       if ( ncol_top > npair_top * 2 ) {
3085         int delta = ncol_bot - max_tree42;
3086         for (int irow = 1; irow < nrows; irow++) {
3087           int nfour = delta / 4;
3088           delta -= nfour * 2;
3089         }
3090         if (delta <= (ncol_top - npair_top * 2))
3091           max_tree42 = ncol_bot;
3092       }
3093     }
3094     // maximum number of bottom elements for "tree" simple reduce 3->1
3095     //int max_tree31 = ncol_top * pow(3.0, nrows);
3096     bool is_lin_31 = false;
3097     bool is_lin_42 = false;
3098     bool is_tree_31 = false;
3099     bool is_tree_42 = false;
3100     int max_lin = max_lin42;
3101     if (ncol_bot > max_lin42) {
3102       if (ncol_bot <= max_lin31) {
3103         is_lin_31 = true;
3104         max_lin = max_lin31;
3105       }
3106     }
3107     else {
3108       // if ncol_bot is a 3*n or not 2*n
3109       if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
3110         is_lin_31 = true;
3111         max_lin = max_lin31;
3112       }
3113       else {
3114         is_lin_42 = true;
3115       }
3116     }
3117     if (ncol_bot > max_lin) { // not "linear"
3118       is_tree_31 = (ncol_bot > max_tree42);
3119       if (ncol_bot <= max_tree42) {
3120         if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
3121           is_tree_31 = true;
3122         }
3123         else {
3124           is_tree_42 = true;
3125         }
3126       }
3127     }
3128
3129     const vector<UVPtStruct>& uv_eb = quad->side[0].GetUVPtStruct(true,0);
3130     const vector<UVPtStruct>& uv_er = quad->side[1].GetUVPtStruct(false,1);
3131     const vector<UVPtStruct>& uv_et = quad->side[2].GetUVPtStruct(true,1);
3132     const vector<UVPtStruct>& uv_el = quad->side[3].GetUVPtStruct(false,0);
3133
3134     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
3135       return error(COMPERR_BAD_INPUT_MESH);
3136
3137     myHelper->SetElementsOnShape( true );
3138
3139     gp_UV uv[ UV_SIZE ];
3140     uv[ UV_A0 ].SetCoord( uv_eb.front().u, uv_eb.front().v);
3141     uv[ UV_A1 ].SetCoord( uv_eb.back().u,  uv_eb.back().v );
3142     uv[ UV_A2 ].SetCoord( uv_et.back().u,  uv_et.back().v );
3143     uv[ UV_A3 ].SetCoord( uv_et.front().u, uv_et.front().v);
3144
3145     vector<UVPtStruct> curr_base = uv_eb, next_base;
3146
3147     UVPtStruct nullUVPtStruct; nullUVPtStruct.node = 0;
3148
3149     int curr_base_len = nb;
3150     int next_base_len = 0;
3151
3152     if ( true )
3153     { // ------------------------------------------------------------------
3154       // New algorithm implemented by request of IPAL22856
3155       // "2D quadrangle mesher of reduced type works wrong"
3156       // http://bugtracker.opencascade.com/show_bug.cgi?id=22856
3157
3158       // the algorithm is following: all reduces are centred in horizontal
3159       // direction and are distributed among all rows
3160
3161       if (ncol_bot > max_tree42) {
3162         is_lin_31 = true;
3163       }
3164       else {
3165         if ((ncol_top/3)*3 == ncol_top ) {
3166           is_lin_31 = true;
3167         }
3168         else {
3169           is_lin_42 = true;
3170         }
3171       }
3172
3173       const int col_top_size  = is_lin_42 ? 2 : 1;
3174       const int col_base_size = is_lin_42 ? 4 : 3;
3175
3176       // Compute nb of "columns" (like in "linear" simple reducing) in all rows
3177
3178       vector<int> nb_col_by_row;
3179
3180       int delta_all     = nb - nt;
3181       int delta_one_col = nrows * 2;
3182       int nb_col        = delta_all / delta_one_col;
3183       int remainder     = delta_all - nb_col * delta_one_col;
3184       if (remainder > 0) {
3185         nb_col++;
3186       }
3187       if ( nb_col * col_top_size >= nt ) // == "tree" reducing situation
3188       {
3189         // top row is full (all elements reduced), add "columns" one by one
3190         // in rows below until all bottom elements are reduced
3191         nb_col = ( nt - 1 ) / col_top_size;
3192         nb_col_by_row.resize( nrows, nb_col );
3193         int nbrows_not_full = nrows - 1;
3194         int cur_top_size    = nt - 1;
3195         remainder = delta_all - nb_col * delta_one_col;
3196         while ( remainder > 0 )
3197         {
3198           delta_one_col   = nbrows_not_full * 2;
3199           int nb_col_add  = remainder / delta_one_col;
3200           cur_top_size   += 2 * nb_col_by_row[ nbrows_not_full ];
3201           int nb_col_free = cur_top_size / col_top_size - nb_col_by_row[ nbrows_not_full-1 ];
3202           if ( nb_col_add > nb_col_free )
3203             nb_col_add = nb_col_free;
3204           for ( int irow = 0; irow < nbrows_not_full; ++irow )
3205             nb_col_by_row[ irow ] += nb_col_add;
3206           nbrows_not_full --;
3207           remainder -=  nb_col_add * delta_one_col;
3208         }
3209       }
3210       else // == "linear" reducing situation
3211       {
3212         nb_col_by_row.resize( nrows, nb_col );
3213         if (remainder > 0)
3214           for ( int irow = remainder / 2; irow < nrows; ++irow )
3215             nb_col_by_row[ irow ]--;
3216       }
3217
3218       // Make elements
3219
3220       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3221
3222       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3223
3224       for (i = 1; i < nr; i++) // layer by layer
3225       {
3226         nb_col = nb_col_by_row[ i-1 ];
3227         int nb_next = curr_base_len - nb_col * 2;
3228         if (nb_next < nt) nb_next = nt;
3229
3230         const double y = uv_el[ i ].normParam;
3231
3232         if ( i + 1 == nr ) // top
3233         {
3234           next_base = uv_et;
3235         }
3236         else
3237         {
3238           next_base.clear();
3239           next_base.resize( nb_next, nullUVPtStruct );
3240           next_base.front() = uv_el[i];
3241           next_base.back()  = uv_er[i];
3242
3243           // compute normalized param u
3244           double du = 1. / ( nb_next - 1 );
3245           next_base[0].normParam = 0.;
3246           for ( j = 1; j < nb_next; ++j )
3247             next_base[j].normParam = next_base[j-1].normParam + du;
3248         }
3249         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3250         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3251
3252         int free_left = ( curr_base_len - 1 - nb_col * col_base_size ) / 2;
3253         int free_middle = curr_base_len - 1 - nb_col * col_base_size - 2 * free_left;
3254
3255         // not reduced left elements
3256         for (j = 0; j < free_left; j++)
3257         {
3258           // f (i + 1, j + 1)
3259           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3260           if ( !Nf )
3261             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3262
3263           myHelper->AddFace(curr_base[ j ].node,
3264                             curr_base[ j+1 ].node,
3265                             Nf,
3266                             next_base[ next_base_len-1 ].node);
3267         }
3268
3269         for (int icol = 1; icol <= nb_col; icol++)
3270         {
3271           // add "H"
3272           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3273
3274           j += reduce_grp_size;
3275
3276           // elements in the middle of "columns" added for symmetry
3277           if ( free_middle > 0 && ( nb_col % 2 == 0 ) && icol == nb_col / 2 )
3278           {
3279             for (int imiddle = 1; imiddle <= free_middle; imiddle++) {
3280               // f (i + 1, j + imiddle)
3281               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3282               if ( !Nf )
3283                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3284
3285               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3286                                 curr_base[ j  +imiddle ].node,
3287                                 Nf,
3288                                 next_base[ next_base_len-1 ].node);
3289             }
3290             j += free_middle;
3291           }
3292         }
3293
3294         // not reduced right elements
3295         for (; j < curr_base_len-1; j++) {
3296           // f (i + 1, j + 1)
3297           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3298           if ( !Nf )
3299             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3300
3301           myHelper->AddFace(curr_base[ j ].node,
3302                             curr_base[ j+1 ].node,
3303                             Nf,
3304                             next_base[ next_base_len-1 ].node);
3305         }
3306
3307         curr_base_len = next_base_len + 1;
3308         next_base_len = 0;
3309         curr_base.swap( next_base );
3310       }
3311
3312     }
3313     else if ( is_tree_42 || is_tree_31 )
3314     {
3315       // "tree" simple reduce "42": 2->4->8->16->32->...
3316       //
3317       //  .-------------------------------.-------------------------------. nr
3318       //  |    \                          |                          /    |
3319       //  |         \     .---------------.---------------.     /         |
3320       //  |               |               |               |               |
3321       //  .---------------.---------------.---------------.---------------.
3322       //  | \             |             / | \             |             / |
3323       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3324       //  |       |       |       |       |       |       |       |       |
3325       //  .-------.-------.-------.-------.-------.-------.-------.-------. i
3326       //  |\      |      /|\      |      /|\      |      /|\      |      /|
3327       //  |  \.---.---./  |  \.---.---./  |  \.---.---./  |  \.---.---./  |
3328       //  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
3329       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.
3330       //  |\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|
3331       //  | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. |
3332       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
3333       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
3334       //  1                               j                               nb
3335
3336       // "tree" simple reduce "31": 1->3->9->27->...
3337       //
3338       //  .-----------------------------------------------------. nr
3339       //  |        \                                   /        |
3340       //  |                 .-----------------.                 |
3341       //  |                 |                 |                 |
3342       //  .-----------------.-----------------.-----------------.
3343       //  |   \         /   |   \         /   |   \         /   |
3344       //  |     .-----.     |     .-----.     |     .-----.     | i
3345       //  |     |     |     |     |     |     |     |     |     |
3346       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.
3347       //  |\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|
3348       //  | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. |
3349       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | |
3350       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
3351       //  1                          j                          nb
3352
3353       PReduceFunction reduceFunction = & ( is_tree_42 ? reduce42 : reduce31 );
3354
3355       const int reduce_grp_size = is_tree_42 ? 4 : 3;
3356
3357       for (i = 1; i < nr; i++) // layer by layer
3358       {
3359         // to stop reducing, if number of nodes reaches nt
3360         int delta = curr_base_len - nt;
3361
3362         // to calculate normalized parameter, we must know number of points in next layer
3363         int nb_reduce_groups = (curr_base_len - 1) / reduce_grp_size;
3364         int nb_next = nb_reduce_groups * (reduce_grp_size-2) + (curr_base_len - nb_reduce_groups*reduce_grp_size);
3365         if (nb_next < nt) nb_next = nt;
3366
3367         const double y = uv_el[ i ].normParam;
3368
3369         if ( i + 1 == nr ) // top
3370         {
3371           next_base = uv_et;
3372         }
3373         else
3374         {
3375           next_base.clear();
3376           next_base.resize( nb_next, nullUVPtStruct );
3377           next_base.front() = uv_el[i];
3378           next_base.back()  = uv_er[i];
3379
3380           // compute normalized param u
3381           double du = 1. / ( nb_next - 1 );
3382           next_base[0].normParam = 0.;
3383           for ( j = 1; j < nb_next; ++j )
3384             next_base[j].normParam = next_base[j-1].normParam + du;
3385         }
3386         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3387         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3388
3389         for (j = 0; j+reduce_grp_size < curr_base_len && delta > 0; j+=reduce_grp_size, delta-=2)
3390         {
3391           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3392         }
3393
3394         // not reduced side elements (if any)
3395         for (; j < curr_base_len-1; j++)
3396         {
3397           // f (i + 1, j + 1)
3398           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3399           if ( !Nf )
3400             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3401           
3402           myHelper->AddFace(curr_base[ j ].node,
3403                             curr_base[ j+1 ].node,
3404                             Nf,
3405                             next_base[ next_base_len-1 ].node);
3406         }
3407         curr_base_len = next_base_len + 1;
3408         next_base_len = 0;
3409         curr_base.swap( next_base );
3410       }
3411     } // end "tree" simple reduce
3412
3413     else if ( is_lin_42 || is_lin_31 ) {
3414       // "linear" simple reduce "31": 2->6->10->14
3415       //
3416       //  .-----------------------------.-----------------------------. nr
3417       //  |     \                 /     |     \                 /     |
3418       //  |         .---------.         |         .---------.         |
3419       //  |         |         |         |         |         |         |
3420       //  .---------.---------.---------.---------.---------.---------.
3421       //  |        / \       / \        |        / \       / \        |
3422       //  |       /   .-----.   \       |       /   .-----.   \       | i
3423       //  |      /    |     |    \      |      /    |     |    \      |
3424       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.-----.
3425       //  |    /     / \   / \     \    |    /     / \   / \     \    |
3426       //  |   /     /   .-.   \     \   |   /     /   .-.   \     \   |
3427       //  |  /     /   /   \   \     \  |  /     /   /   \   \     \  |
3428       //  .--.----.---.-----.---.-----.-.--.----.---.-----.---.-----.-. 1
3429       //  1                             j                             nb
3430
3431       // "linear" simple reduce "42": 4->8->12->16
3432       //
3433       //  .---------------.---------------.---------------.---------------. nr
3434       //  | \             |             / | \             |             / |
3435       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3436       //  |       |       |       |       |       |       |       |       |
3437       //  .-------.-------.-------.-------.-------.-------.-------.-------.
3438       //  |      / \      |      / \      |      / \      |      / \      |
3439       //  |     /   \.----.----./   \     |     /   \.----.----./   \     | i
3440       //  |     /    |    |    |    \     |     /    |    |    |    \     |
3441       //  .-----.----.----.----.----.-----.-----.----.----.----.----.-----.
3442       //  |     /   / \   |  /  \   \     |     /   / \   |  /  \   \     |
3443       //  |    /   /    .-.-.    \   \    |    /   /    .-.-.    \   \    |
3444       //  |   /   /    /  |  \    \   \   |   /   /    /  |  \    \   \   |
3445       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---. 1
3446       //  1                               j                               nb
3447
3448       // nt = 5, nb = 7, nr = 4
3449       //int delta_all = 2;
3450       //int delta_one_col = 6;
3451       //int nb_col = 0;
3452       //int remainder = 2;
3453       //if (remainder > 0) nb_col++;
3454       //nb_col = 1;
3455       //int free_left = 1;
3456       //free_left += 2;
3457       //int free_middle = 4;
3458
3459       int delta_all = nb - nt;
3460       int delta_one_col = (nr - 1) * 2;
3461       int nb_col = delta_all / delta_one_col;
3462       int remainder = delta_all - nb_col * delta_one_col;
3463       if (remainder > 0) {
3464         nb_col++;
3465       }
3466       const int col_top_size = is_lin_42 ? 2 : 1;
3467       int free_left = ((nt - 1) - nb_col * col_top_size) / 2;
3468       free_left += nr - 2;
3469       int free_middle = (nr - 2) * 2;
3470       if (remainder > 0 && nb_col == 1) {
3471         int nb_rows_short_col = remainder / 2;
3472         int nb_rows_thrown = (nr - 1) - nb_rows_short_col;
3473         free_left -= nb_rows_thrown;
3474       }
3475
3476       // nt = 5, nb = 17, nr = 4
3477       //int delta_all = 12;
3478       //int delta_one_col = 6;
3479       //int nb_col = 2;
3480       //int remainder = 0;
3481       //int free_left = 2;
3482       //int free_middle = 4;
3483
3484       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3485
3486       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3487
3488       for (i = 1; i < nr; i++, free_middle -= 2, free_left -= 1) // layer by layer
3489       {
3490         // to calculate normalized parameter, we must know number of points in next layer
3491         int nb_next = curr_base_len - nb_col * 2;
3492         if (remainder > 0 && i > remainder / 2)
3493           // take into account short "column"
3494           nb_next += 2;
3495         if (nb_next < nt) nb_next = nt;
3496
3497         const double y = uv_el[ i ].normParam;
3498
3499         if ( i + 1 == nr ) // top
3500         {
3501           next_base = uv_et;
3502         }
3503         else
3504         {
3505           next_base.clear();
3506           next_base.resize( nb_next, nullUVPtStruct );
3507           next_base.front() = uv_el[i];
3508           next_base.back()  = uv_er[i];
3509
3510           // compute normalized param u
3511           double du = 1. / ( nb_next - 1 );
3512           next_base[0].normParam = 0.;
3513           for ( j = 1; j < nb_next; ++j )
3514             next_base[j].normParam = next_base[j-1].normParam + du;
3515         }
3516         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3517         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3518
3519         // not reduced left elements
3520         for (j = 0; j < free_left; j++)
3521         {
3522           // f (i + 1, j + 1)
3523           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3524           if ( !Nf )
3525             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3526
3527           myHelper->AddFace(curr_base[ j ].node,
3528                             curr_base[ j+1 ].node,
3529                             Nf,
3530                             next_base[ next_base_len-1 ].node);
3531         }
3532
3533         for (int icol = 1; icol <= nb_col; icol++) {
3534
3535           if (remainder > 0 && icol == nb_col && i > remainder / 2)
3536             // stop short "column"
3537             break;
3538
3539           // add "H"
3540           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3541
3542           j += reduce_grp_size;
3543
3544           // not reduced middle elements
3545           if (icol < nb_col) {
3546             if (remainder > 0 && icol == nb_col - 1 && i > remainder / 2)
3547               // pass middle elements before stopped short "column"
3548               break;
3549
3550             int free_add = free_middle;
3551             if (remainder > 0 && icol == nb_col - 1)
3552               // next "column" is short
3553               free_add -= (nr - 1) - (remainder / 2);
3554
3555             for (int imiddle = 1; imiddle <= free_add; imiddle++) {
3556               // f (i + 1, j + imiddle)
3557               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3558               if ( !Nf )
3559                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3560
3561               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3562                                 curr_base[ j  +imiddle ].node,
3563                                 Nf,
3564                                 next_base[ next_base_len-1 ].node);
3565             }
3566             j += free_add;
3567           }
3568         }
3569
3570         // not reduced right elements
3571         for (; j < curr_base_len-1; j++) {
3572           // f (i + 1, j + 1)
3573           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3574           if ( !Nf )
3575             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3576
3577           myHelper->AddFace(curr_base[ j ].node,
3578                             curr_base[ j+1 ].node,
3579                             Nf,
3580                             next_base[ next_base_len-1 ].node);
3581         }
3582
3583         curr_base_len = next_base_len + 1;
3584         next_base_len = 0;
3585         curr_base.swap( next_base );
3586       }
3587
3588     } // end "linear" simple reduce
3589
3590     else {
3591       return false;
3592     }
3593   } // end Simple Reduce implementation
3594
3595   bool isOk = true;
3596   return isOk;
3597 }
3598
3599 //================================================================================
3600 namespace // data for smoothing
3601 {
3602   struct TSmoothNode;
3603   // --------------------------------------------------------------------------------
3604   /*!
3605    * \brief Structure used to check validity of node position after smoothing.
3606    *        It holds two nodes connected to a smoothed node and belonging to
3607    *        one mesh face
3608    */
3609   struct TTriangle
3610   {
3611     TSmoothNode* _n1;
3612     TSmoothNode* _n2;
3613     TTriangle( TSmoothNode* n1=0, TSmoothNode* n2=0 ): _n1(n1), _n2(n2) {}
3614
3615     inline bool IsForward( gp_UV uv ) const;
3616   };
3617   // --------------------------------------------------------------------------------
3618   /*!
3619    * \brief Data of a smoothed node
3620    */
3621   struct TSmoothNode
3622   {
3623     gp_XY  _uv;
3624     gp_XYZ _xyz;
3625     vector< TTriangle > _triangles; // if empty, then node is not movable
3626   };
3627   // --------------------------------------------------------------------------------
3628   inline bool TTriangle::IsForward( gp_UV uv ) const
3629   {
3630     gp_Vec2d v1( uv, _n1->_uv ), v2( uv, _n2->_uv );
3631     double d = v1 ^ v2;
3632     return d > 1e-100;
3633   }
3634 }
3635
3636 //================================================================================
3637 /*!
3638  * \brief Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3639  *
3640  * WARNING: this method must be called AFTER retrieving UVPtStruct's from quad
3641  */
3642 //================================================================================
3643
3644 void StdMeshers_Quadrangle_2D::updateDegenUV(FaceQuadStruct::Ptr quad)
3645 {
3646   if ( myNeedSmooth )
3647
3648     // Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3649     // --------------------------------------------------------------------------
3650     for ( unsigned i = 0; i < quad->side.size(); ++i )
3651     {
3652       const vector<UVPtStruct>& uvVec = quad->side[i].GetUVPtStruct();
3653
3654       // find which end of the side is on degenerated shape
3655       int degenInd = -1;
3656       if ( myHelper->IsDegenShape( uvVec[0].node->getshapeId() ))
3657         degenInd = 0;
3658       else if ( myHelper->IsDegenShape( uvVec.back().node->getshapeId() ))
3659         degenInd = uvVec.size() - 1;
3660       else
3661         continue;
3662
3663       // find another side sharing the degenerated shape
3664       bool isPrev = ( degenInd == 0 );
3665       if ( i >= QUAD_TOP_SIDE )
3666         isPrev = !isPrev;
3667       int i2 = ( isPrev ? ( i + 3 ) : ( i + 1 )) % 4;
3668       const vector<UVPtStruct>& uvVec2 = quad->side[ i2 ].GetUVPtStruct();
3669       int degenInd2 = -1;
3670       if (      uvVec[ degenInd ].node == uvVec2.front().node )
3671         degenInd2 = 0;
3672       else if ( uvVec[ degenInd ].node == uvVec2.back().node )
3673         degenInd2 = uvVec2.size() - 1;
3674       else
3675         throw SALOME_Exception( LOCALIZED( "Logical error" ));
3676
3677       // move UV in the middle
3678       uvPtStruct& uv1 = const_cast<uvPtStruct&>( uvVec [ degenInd  ]);
3679       uvPtStruct& uv2 = const_cast<uvPtStruct&>( uvVec2[ degenInd2 ]);
3680       uv1.u = uv2.u = 0.5 * ( uv1.u + uv2.u );
3681       uv1.v = uv2.v = 0.5 * ( uv1.v + uv2.v );
3682     }
3683
3684   else if ( quad->side.size() == 4 && myQuadType == QUAD_STANDARD)
3685
3686     // Set number of nodes on a degenerated side to be same as on an opposite side
3687     // ----------------------------------------------------------------------------
3688     for ( unsigned i = 0; i < quad->side.size(); ++i )
3689     {
3690       StdMeshers_FaceSidePtr degSide = quad->side[i];
3691       if ( !myHelper->IsDegenShape( degSide->EdgeID(0) ))
3692         continue;
3693       StdMeshers_FaceSidePtr oppSide = quad->side[( i+2 ) % quad->side.size() ];
3694       if ( degSide->NbSegments() == oppSide->NbSegments() )
3695         continue;
3696
3697       // make new side data
3698       const vector<UVPtStruct>& uvVecDegOld = degSide->GetUVPtStruct();
3699       const SMDS_MeshNode*   n = uvVecDegOld[0].node;
3700       Handle(Geom2d_Curve) c2d = degSide->Curve2d(0);
3701       double f = degSide->FirstU(0), l = degSide->LastU(0);
3702       gp_Pnt2d p1 = uvVecDegOld.front().UV();
3703       gp_Pnt2d p2 = uvVecDegOld.back().UV();
3704
3705       quad->side[i] = StdMeshers_FaceSide::New( oppSide.get(), n, &p1, &p2, c2d, f, l );
3706     }
3707 }
3708
3709 //================================================================================
3710 /*!
3711  * \brief Perform smoothing of 2D elements on a FACE with ignored degenerated EDGE
3712  */
3713 //================================================================================
3714
3715 void StdMeshers_Quadrangle_2D::smooth (FaceQuadStruct::Ptr quad)
3716 {
3717   if ( !myNeedSmooth ) return;
3718
3719   // Get nodes to smooth
3720
3721   typedef map< const SMDS_MeshNode*, TSmoothNode, TIDCompare > TNo2SmooNoMap;
3722   TNo2SmooNoMap smooNoMap;
3723
3724   const TopoDS_Face&  geomFace = TopoDS::Face( myHelper->GetSubShape() );
3725   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
3726   double U1, U2, V1, V2;
3727   surface->Bounds(U1, U2, V1, V2);
3728   GeomAPI_ProjectPointOnSurf proj;
3729   proj.Init( surface, U1, U2, V1, V2, BRep_Tool::Tolerance( geomFace ) );
3730
3731   SMESHDS_Mesh*        meshDS = myHelper->GetMeshDS();
3732   SMESHDS_SubMesh*   fSubMesh = meshDS->MeshElements( geomFace );
3733   SMDS_NodeIteratorPtr    nIt = fSubMesh->GetNodes();
3734   while ( nIt->more() ) // loop on nodes bound to a FACE
3735   {
3736     const SMDS_MeshNode* node = nIt->next();
3737     TSmoothNode & sNode = smooNoMap[ node ];
3738     sNode._uv  = myHelper->GetNodeUV( geomFace, node );
3739     sNode._xyz = SMESH_TNodeXYZ( node );
3740
3741     // set sNode._triangles
3742     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator( SMDSAbs_Face );
3743     while ( fIt->more() )
3744     {
3745       const SMDS_MeshElement* face = fIt->next();
3746       const int nbN     = face->NbCornerNodes();
3747       const int nInd    = face->GetNodeIndex( node );
3748       const int prevInd = myHelper->WrapIndex( nInd - 1, nbN );
3749       const int nextInd = myHelper->WrapIndex( nInd + 1, nbN );
3750       const SMDS_MeshNode* prevNode = face->GetNode( prevInd );
3751       const SMDS_MeshNode* nextNode = face->GetNode( nextInd );
3752       sNode._triangles.push_back( TTriangle( & smooNoMap[ prevNode ],
3753                                              & smooNoMap[ nextNode ]));
3754     }
3755   }
3756   // set _uv of smooth nodes on FACE boundary
3757   for ( unsigned i = 0; i < quad->side.size(); ++i )
3758   {
3759     const vector<UVPtStruct>& uvVec = quad->side[i].GetUVPtStruct();
3760     for ( unsigned j = 0; j < uvVec.size(); ++j )
3761     {
3762       TSmoothNode & sNode = smooNoMap[ uvVec[j].node ];
3763       sNode._uv  = uvVec[j].UV();
3764       sNode._xyz = SMESH_TNodeXYZ( uvVec[j].node );
3765     }
3766   }
3767
3768   // define refernce orientation in 2D
3769   TNo2SmooNoMap::iterator n2sn = smooNoMap.begin();
3770   for ( ; n2sn != smooNoMap.end(); ++n2sn )
3771     if ( !n2sn->second._triangles.empty() )
3772       break;
3773   if ( n2sn == smooNoMap.end() ) return;
3774   const TSmoothNode & sampleNode = n2sn->second;
3775   const bool refForward = ( sampleNode._triangles[0].IsForward( sampleNode._uv ));
3776
3777   // Smoothing
3778
3779   for ( int iLoop = 0; iLoop < 5; ++iLoop )
3780   {
3781     for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3782     {
3783       TSmoothNode& sNode = n2sn->second;
3784       if ( sNode._triangles.empty() )
3785         continue; // not movable node
3786
3787       gp_XY newUV;
3788       bool isValid = false;
3789       bool use3D   = ( iLoop > 2 ); // 3 loops in 2D and 2, in 3D
3790
3791       if ( use3D )
3792       {
3793         // compute a new XYZ
3794         gp_XYZ newXYZ (0,0,0);
3795         for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3796           newXYZ += sNode._triangles[i]._n1->_xyz;
3797         newXYZ /= sNode._triangles.size();
3798
3799         // compute a new UV by projection
3800         proj.Perform( newXYZ );
3801         isValid = ( proj.IsDone() && proj.NbPoints() > 0 );
3802         if ( isValid )
3803         {
3804           // check validity of the newUV
3805           Quantity_Parameter u,v;
3806           proj.LowerDistanceParameters( u, v );
3807           newUV.SetCoord( u, v );
3808           for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3809             isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3810         }
3811       }
3812       if ( !isValid )
3813       {
3814         // compute a new UV by averaging
3815         newUV.SetCoord(0.,0.);
3816         for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3817           newUV += sNode._triangles[i]._n1->_uv;
3818         newUV /= sNode._triangles.size();
3819
3820         // check validity of the newUV
3821         isValid = true;
3822         for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3823           isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3824       }
3825       if ( isValid )
3826       {
3827         sNode._uv = newUV;
3828         sNode._xyz = surface->Value( newUV.X(), newUV.Y() ).XYZ();
3829       }
3830     }
3831   }
3832
3833   // Set new XYZ to the smoothed nodes
3834
3835   for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3836   {
3837     TSmoothNode& sNode = n2sn->second;
3838     if ( sNode._triangles.empty() )
3839       continue; // not movable node
3840
3841     SMDS_MeshNode* node = const_cast< SMDS_MeshNode*>( n2sn->first );
3842     gp_Pnt xyz = surface->Value( sNode._uv.X(), sNode._uv.Y() );
3843     meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
3844
3845     // store the new UV
3846     node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( sNode._uv.X(), sNode._uv.Y() )));
3847   }
3848
3849   // Move medium nodes in quadratic mesh
3850   if ( _quadraticMesh )
3851   {
3852     const TLinkNodeMap& links = myHelper->GetTLinkNodeMap();
3853     TLinkNodeMap::const_iterator linkIt = links.begin();
3854     for ( ; linkIt != links.end(); ++linkIt )
3855     {
3856       const SMESH_TLink& link = linkIt->first;
3857       SMDS_MeshNode*     node = const_cast< SMDS_MeshNode*>( linkIt->second );
3858
3859       if ( node->getshapeId() != myHelper->GetSubShapeID() )
3860         continue; // medium node is on EDGE or VERTEX
3861
3862       gp_XY uv1 = myHelper->GetNodeUV( geomFace, link.node1(), node );
3863       gp_XY uv2 = myHelper->GetNodeUV( geomFace, link.node2(), node );
3864
3865       gp_XY uv  = myHelper->GetMiddleUV( surface, uv1, uv2 );
3866       node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( uv.X(), uv.Y() )));
3867       
3868       gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
3869       meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
3870     }
3871   }
3872 }
3873
3874 /*//================================================================================
3875 /*!
3876  * \brief Finds vertices at the most sharp face corners
3877  *  \param [in] theFace - the FACE
3878  *  \param [in,out] theWire - the ordered edges of the face. It can be modified to
3879  *         have the first VERTEX of the first EDGE in \a vertices
3880  *  \param [out] theVertices - the found corner vertices in the order corresponding to
3881  *         the order of EDGEs in \a theWire
3882  *  \param [out] theNbDegenEdges - nb of degenerated EDGEs in theFace
3883  *  \param [in] theConsiderMesh - if \c true, only meshed VERTEXes are considered
3884  *         as possible corners
3885  *  \return int - number of quad sides found: 0, 3 or 4
3886  */
3887 //================================================================================
3888
3889 int StdMeshers_Quadrangle_2D::getCorners(const TopoDS_Face&          theFace,
3890                                          SMESH_Mesh &                theMesh,
3891                                          std::list<TopoDS_Edge>&     theWire,
3892                                          std::vector<TopoDS_Vertex>& theVertices,
3893                                          int &                       theNbDegenEdges,
3894                                          const bool                  theConsiderMesh)
3895 {
3896   theNbDegenEdges = 0;
3897
3898   SMESH_MesherHelper helper( theMesh );
3899
3900   // sort theVertices by angle
3901   multimap<double, TopoDS_Vertex> vertexByAngle;
3902   TopTools_DataMapOfShapeReal angleByVertex;
3903   TopoDS_Edge prevE = theWire.back();
3904   if ( SMESH_Algo::isDegenerated( prevE ))
3905   {
3906     list<TopoDS_Edge>::reverse_iterator edge = ++theWire.rbegin();
3907     while ( SMESH_Algo::isDegenerated( *edge ))
3908       ++edge;
3909     if ( edge == theWire.rend() )
3910       return false;
3911     prevE = *edge;
3912   }
3913   list<TopoDS_Edge>::iterator edge = theWire.begin();
3914   for ( ; edge != theWire.end(); ++edge )
3915   {
3916     if ( SMESH_Algo::isDegenerated( *edge ))
3917     {
3918       ++theNbDegenEdges;
3919       continue;
3920     }
3921     TopoDS_Vertex v = helper.IthVertex( 0, *edge );
3922     if ( !theConsiderMesh || SMESH_Algo::VertexNode( v, helper.GetMeshDS() ))
3923     {
3924       double angle = SMESH_MesherHelper::GetAngle( prevE, *edge, theFace );
3925       vertexByAngle.insert( make_pair( angle, v ));
3926       angleByVertex.Bind( v, angle );
3927     }
3928     prevE = *edge;
3929   }
3930
3931   // find out required nb of corners (3 or 4)
3932   int nbCorners = 4;
3933   TopoDS_Shape triaVertex = helper.GetMeshDS()->IndexToShape( myTriaVertexID );
3934   if ( !triaVertex.IsNull() &&
3935        triaVertex.ShapeType() == TopAbs_VERTEX &&
3936        helper.IsSubShape( triaVertex, theFace ))
3937     nbCorners = 3;
3938   else
3939     triaVertex.Nullify();
3940
3941   // check nb of available corners
3942   if ( nbCorners == 3 )
3943   {
3944     if ( vertexByAngle.size() < 3 )
3945       return error(COMPERR_BAD_SHAPE,
3946                    TComm("Face must have 3 sides but not ") << vertexByAngle.size() );
3947   }
3948   else
3949   {
3950     if ( vertexByAngle.size() == 3 && theNbDegenEdges == 0 )
3951     {
3952       if ( myTriaVertexID < 1 )
3953         return error(COMPERR_BAD_PARMETERS,
3954                      "No Base vertex provided for a trilateral geometrical face");
3955         
3956       TComm comment("Invalid Base vertex: ");
3957       comment << myTriaVertexID << " its ID is not among [ ";
3958       multimap<double, TopoDS_Vertex>::iterator a2v = vertexByAngle.begin();
3959       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << ", "; a2v++;
3960       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << ", "; a2v++;
3961       comment << helper.GetMeshDS()->ShapeToIndex( a2v->second ) << " ]";
3962       return error(COMPERR_BAD_PARMETERS, comment );
3963     }
3964     if ( vertexByAngle.size() + ( theNbDegenEdges > 0 ) < 4 &&
3965          vertexByAngle.size() + theNbDegenEdges != 4 )
3966       return error(COMPERR_BAD_SHAPE,
3967                    TComm("Face must have 4 sides but not ") << vertexByAngle.size() );
3968   }
3969
3970   // put all corner vertices in a map
3971   TopTools_MapOfShape vMap;
3972   if ( nbCorners == 3 )
3973     vMap.Add( triaVertex );
3974   multimap<double, TopoDS_Vertex>::reverse_iterator a2v = vertexByAngle.rbegin();
3975   for ( ; a2v != vertexByAngle.rend() && vMap.Extent() < nbCorners; ++a2v )
3976     vMap.Add( (*a2v).second );
3977
3978   // check if there are possible variations in choosing corners
3979   bool isThereVariants = false;
3980   if ( vertexByAngle.size() > nbCorners )
3981   {
3982     double lostAngle = a2v->first;
3983     double lastAngle = ( --a2v, a2v->first );
3984     isThereVariants  = ( lostAngle * 1.1 >= lastAngle );
3985   }
3986
3987   // make theWire begin from a corner vertex or triaVertex
3988   if ( nbCorners == 3 )
3989     while ( !triaVertex.IsSame( ( helper.IthVertex( 0, theWire.front() ))) ||
3990             SMESH_Algo::isDegenerated( theWire.front() ))
3991       theWire.splice( theWire.end(), theWire, theWire.begin() );
3992   else
3993     while ( !vMap.Contains( helper.IthVertex( 0, theWire.front() )) ||
3994             SMESH_Algo::isDegenerated( theWire.front() ))
3995       theWire.splice( theWire.end(), theWire, theWire.begin() );
3996
3997   // fill the result vector and prepare for its refinement
3998   theVertices.clear();
3999   vector< double >      angles;
4000   vector< TopoDS_Edge > edgeVec;
4001   vector< int >         cornerInd, nbSeg;
4002   angles.reserve( vertexByAngle.size() );
4003   edgeVec.reserve( vertexByAngle.size() );
4004   nbSeg.reserve( vertexByAngle.size() );
4005   cornerInd.reserve( nbCorners );
4006   for ( edge = theWire.begin(); edge != theWire.end(); ++edge )
4007   {
4008     if ( SMESH_Algo::isDegenerated( *edge ))
4009       continue;
4010     TopoDS_Vertex v = helper.IthVertex( 0, *edge );
4011     bool   isCorner = vMap.Contains( v );
4012     if ( isCorner )
4013     {
4014       theVertices.push_back( v );
4015       cornerInd.push_back( angles.size() );
4016     }
4017     angles.push_back( angleByVertex.IsBound( v ) ? angleByVertex( v ) : -M_PI );
4018     edgeVec.push_back( *edge );
4019     if ( theConsiderMesh && isThereVariants )
4020     {
4021       if ( SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( *edge ))
4022         nbSeg.push_back( sm->NbNodes() + 1 );
4023       else
4024         nbSeg.push_back( 0 );
4025     }
4026   }
4027
4028   // refine the result vector - make sides elual by length if
4029   // there are several equal angles
4030   if ( isThereVariants )
4031   {
4032     if ( nbCorners == 3 )
4033       angles[0] = 2 * M_PI; // not to move the base triangle VERTEX
4034
4035     set< int > refinedCorners;
4036     for ( size_t iC = 0; iC < cornerInd.size(); ++iC )
4037     {
4038       int iV = cornerInd[iC];
4039       if ( !refinedCorners.insert( iV ).second )
4040         continue;
4041       list< int > equalVertices;
4042       equalVertices.push_back( iV );
4043       int nbC[2] = { 0, 0 };
4044       // find equal angles backward and forward from the iV-th corner vertex
4045       for ( int isFwd = 0; isFwd < 2; ++isFwd )
4046       {
4047         int     dV = isFwd ? +1 : -1;
4048         int iCNext = helper.WrapIndex( iC + dV, cornerInd.size() );
4049         int iVNext = helper.WrapIndex( iV + dV, angles.size() );
4050         while ( iVNext != iV )
4051         {
4052           bool equal = Abs( angles[iV] - angles[iVNext] ) < 0.1 * angles[iV];
4053           if ( equal )
4054             equalVertices.insert( isFwd ? equalVertices.end() : equalVertices.begin(), iVNext );
4055           if ( iVNext == cornerInd[ iCNext ])
4056           {
4057             if ( !equal )
4058               break;
4059             nbC[ isFwd ]++;
4060             refinedCorners.insert( cornerInd[ iCNext ] );
4061             iCNext = helper.WrapIndex( iCNext + dV, cornerInd.size() );
4062           }
4063           iVNext = helper.WrapIndex( iVNext + dV, angles.size() );
4064         }
4065       }
4066       // move corners to make sides equal by length
4067       int nbEqualV  = equalVertices.size();
4068       int nbExcessV = nbEqualV - ( 1 + nbC[0] + nbC[1] );
4069       if ( nbExcessV > 0 )
4070       {
4071         // calculate normalized length of each side enclosed between neighbor equalVertices
4072         vector< double > curLengths;
4073         double totalLen = 0;
4074         vector< int > evVec( equalVertices.begin(), equalVertices.end() );
4075         int   iEV = 0;
4076         int    iE = cornerInd[ helper.WrapIndex( iC - nbC[0] - 1, cornerInd.size() )];
4077         int iEEnd = cornerInd[ helper.WrapIndex( iC + nbC[1] + 1, cornerInd.size() )];
4078         while ( curLengths.size() < nbEqualV + 1 )
4079         {
4080           curLengths.push_back( totalLen );
4081           do {
4082             curLengths.back() += SMESH_Algo::EdgeLength( edgeVec[ iE ]);
4083             iE = helper.WrapIndex( iE + 1, edgeVec.size());
4084             if ( iEV < evVec.size() && iE == evVec[ iEV++ ] )
4085               break;
4086           }
4087           while( iE != iEEnd );
4088           totalLen = curLengths.back();
4089         }
4090         curLengths.resize( equalVertices.size() );
4091         for ( size_t iS = 0; iS < curLengths.size(); ++iS )
4092           curLengths[ iS ] /= totalLen;
4093
4094         // find equalVertices most close to the ideal sub-division of all sides
4095         int iBestEV = 0;
4096         int iCorner = helper.WrapIndex( iC - nbC[0], cornerInd.size() );
4097         int nbSides = 2 + nbC[0] + nbC[1];
4098         for ( int iS = 1; iS < nbSides; ++iS, ++iBestEV )
4099         {
4100           double idealLen = iS / double( nbSides );
4101           double d, bestDist = 1.;
4102           for ( iEV = iBestEV; iEV < curLengths.size(); ++iEV )
4103             if (( d = Abs( idealLen - curLengths[ iEV ])) < bestDist )
4104             {
4105               bestDist = d;
4106               iBestEV  = iEV;
4107             }
4108           if ( iBestEV > iS-1 + nbExcessV )
4109             iBestEV = iS-1 + nbExcessV;
4110           theVertices[ iCorner ] = helper.IthVertex( 0, edgeVec[ evVec[ iBestEV ]]);
4111           iCorner = helper.WrapIndex( iCorner + 1, cornerInd.size() );
4112         }
4113       }
4114     }
4115   }
4116
4117   return nbCorners;
4118 }
4119
4120 //================================================================================
4121 /*!
4122  * \brief Constructor of a side of quad
4123  */
4124 //================================================================================
4125
4126 FaceQuadStruct::Side::Side(StdMeshers_FaceSidePtr theGrid)
4127   : grid(theGrid), nbNodeOut(0), from(0), to(theGrid ? theGrid->NbPoints() : 0 )
4128 {
4129 }
4130
4131 //=============================================================================
4132 /*!
4133  * \brief Constructor of a quad
4134  */
4135 //=============================================================================
4136
4137 FaceQuadStruct::FaceQuadStruct(const TopoDS_Face& F) : face( F )
4138 {
4139   side.reserve(4);
4140 }
4141
4142 //================================================================================
4143 /*!
4144  * \brief Fills myForcedPnts
4145  */
4146 //================================================================================
4147
4148 bool StdMeshers_Quadrangle_2D::getEnforcedUV()
4149 {
4150   myForcedPnts.clear();
4151   if ( !myParams ) return true; // missing hypothesis
4152
4153   std::vector< TopoDS_Shape > shapes;
4154   std::vector< gp_Pnt >       points;
4155   myParams->GetEnforcedNodes( shapes, points );
4156
4157   TopTools_IndexedMapOfShape vMap;
4158   for ( size_t i = 0; i < shapes.size(); ++i )
4159     if ( !shapes[i].IsNull() )
4160       TopExp::MapShapes( shapes[i], TopAbs_VERTEX, vMap );
4161
4162   size_t nbPoints = points.size();
4163   for ( int i = 1; i <= vMap.Extent(); ++i )
4164     points.push_back( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))));
4165
4166   // find out if all points must be in the FACE, which is so if
4167   // myParams is a local hypothesis on the FACE being meshed
4168   bool isStrictCheck = false;
4169   {
4170     SMESH_HypoFilter paramFilter( SMESH_HypoFilter::Is( myParams ));
4171     TopoDS_Shape assignedTo;
4172     if ( myHelper->GetMesh()->GetHypothesis( myHelper->GetSubShape(),
4173                                              paramFilter,
4174                                              /*ancestors=*/true,
4175                                              &assignedTo ))
4176       isStrictCheck = ( assignedTo.IsSame( myHelper->GetSubShape() ));
4177   }
4178
4179   multimap< double, ForcedPoint > sortedFP; // sort points by distance from EDGEs
4180
4181   Standard_Real u1,u2,v1,v2;
4182   const TopoDS_Face&   face = TopoDS::Face( myHelper->GetSubShape() );
4183   const double          tol = BRep_Tool::Tolerance( face );
4184   Handle(Geom_Surface) surf = BRep_Tool::Surface( face );
4185   surf->Bounds( u1,u2,v1,v2 );
4186   GeomAPI_ProjectPointOnSurf project;
4187   project.Init(surf, u1,u2, v1,v2, tol );
4188
4189   for ( size_t iP = 0; iP < points.size(); ++iP )
4190   {
4191     project.Perform( points[ iP ]);
4192     if ( !project.IsDone() )
4193     {
4194       if ( isStrictCheck && iP < nbPoints )
4195         return error
4196           (TComm("Projection of an enforced point to the face failed - (")
4197            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4198       continue;
4199     }
4200     if ( project.LowerDistance() > tol*1000 )
4201     {
4202       if ( isStrictCheck && iP < nbPoints )
4203         return error
4204           (COMPERR_BAD_PARMETERS, TComm("An enforced point is too far from the face, dist = ")
4205            << project.LowerDistance() << " - ("
4206            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4207       continue;
4208     }
4209     Quantity_Parameter u, v;
4210     project.LowerDistanceParameters(u, v);
4211     gp_Pnt2d uv( u, v );
4212     BRepClass_FaceClassifier clsf ( face, uv, tol );
4213     switch ( clsf.State() ) {
4214     case TopAbs_IN:
4215     {
4216       double edgeDist =  ( Min( Abs( u - u1 ), Abs( u - u2 )) +
4217                            Min( Abs( v - v1 ), Abs( v - v2 )));
4218       ForcedPoint fp;
4219       fp.uv  = uv.XY();
4220       fp.xyz = points[ iP ].XYZ();
4221       if ( iP >= nbPoints )
4222         fp.vertex = TopoDS::Vertex( vMap( iP - nbPoints + 1 ));
4223
4224       sortedFP.insert( make_pair( edgeDist, fp ));
4225       break;
4226     }
4227     case TopAbs_OUT:
4228     {
4229       if ( isStrictCheck && iP < nbPoints )
4230         return error
4231           (COMPERR_BAD_PARMETERS, TComm("An enforced point is out of the face boundary - ")
4232            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4233       break;
4234     }
4235     case TopAbs_ON:
4236     {
4237       if ( isStrictCheck && iP < nbPoints )
4238         return error
4239           (COMPERR_BAD_PARMETERS, TComm("An enforced point is on the face boundary - ")
4240            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4241       break;
4242     }
4243     default:
4244     {
4245       if ( isStrictCheck && iP < nbPoints )
4246         return error
4247           (TComm("Classification of an enforced point ralative to the face boundary failed - ")
4248            << points[ iP ].X() << ", "<< points[ iP ].Y() << ", "<< points[ iP ].Z() << " )");
4249     }
4250     }
4251   }
4252
4253   multimap< double, ForcedPoint >::iterator d2uv = sortedFP.begin();
4254   for ( ; d2uv != sortedFP.end(); ++d2uv )
4255     myForcedPnts.push_back( (*d2uv).second );
4256
4257   return true;
4258 }
4259
4260 //================================================================================
4261 /*!
4262  * \brief Splits quads by adding points of enforced nodes and create nodes on
4263  *        the sides shared by quads
4264  */
4265 //================================================================================
4266
4267 bool StdMeshers_Quadrangle_2D::addEnforcedNodes()
4268 {
4269   // if ( myForcedPnts.empty() )
4270   //   return true;
4271
4272   // make a map of quads sharing a side
4273   map< StdMeshers_FaceSidePtr, vector< FaceQuadStruct::Ptr > > quadsBySide;
4274   list< FaceQuadStruct::Ptr >::iterator quadIt = myQuadList.begin();
4275   for ( ; quadIt != myQuadList.end(); ++quadIt )
4276     for ( size_t iSide = 0; iSide < (*quadIt)->side.size(); ++iSide )
4277       quadsBySide[ (*quadIt)->side[iSide] ].push_back( *quadIt );
4278
4279   SMESH_Mesh*          mesh = myHelper->GetMesh();
4280   SMESHDS_Mesh*      meshDS = myHelper->GetMeshDS();
4281   const TopoDS_Face&   face = TopoDS::Face( myHelper->GetSubShape() );
4282   Handle(Geom_Surface) surf = BRep_Tool::Surface( face );
4283
4284   for ( size_t iFP = 0; iFP < myForcedPnts.size(); ++iFP )
4285   {
4286     bool isNodeEnforced = false;
4287
4288     // look for a quad enclosing a enforced point
4289     for ( quadIt = myQuadList.begin(); quadIt != myQuadList.end(); ++quadIt )
4290     {
4291       FaceQuadStruct::Ptr quad = *quadIt;
4292       int i,j;
4293       if ( !setNormalizedGrid( quad ))
4294         return false;
4295       if ( !quad->findCell( myForcedPnts[ iFP ], i, j ))
4296         continue;
4297
4298       // a grid cell is found, select a node of the cell to move
4299       // to the enforced point to and to split the quad at
4300       multimap< double, pair< int, int > > ijByDist;
4301       for ( int di = 0; di < 2; ++di )
4302         for ( int dj = 0; dj < 2; ++dj )
4303         {
4304           double dist2 = ( myForcedPnts[ iFP ].uv - quad->UVPt( i+di,j+dj ).UV() ).SquareModulus();
4305           ijByDist.insert( make_pair( dist2, make_pair( i+di,j+dj )));
4306         }
4307       // try all nodes starting from the closest one
4308       set< FaceQuadStruct::Ptr > changedQuads;
4309       multimap< double, pair< int, int > >::iterator d2ij = ijByDist.begin();
4310       for ( ; !isNodeEnforced  &&  d2ij != ijByDist.end(); ++d2ij )
4311       {
4312         i = d2ij->second.first;
4313         j = d2ij->second.second;
4314
4315         // check if a node is at a side
4316         int iSide = -1;
4317         if ( j == 0 )
4318           iSide = QUAD_BOTTOM_SIDE;
4319         else if ( j+1 == quad->jSize )
4320           iSide = QUAD_TOP_SIDE;
4321         else if ( i == 0 )
4322           iSide = QUAD_LEFT_SIDE;
4323         else if ( i+1 == quad->iSize )
4324           iSide = QUAD_RIGHT_SIDE;
4325
4326         if ( iSide > -1 ) // ----- node is at a side
4327         {
4328           FaceQuadStruct::Side& side = quad->side[ iSide ];
4329           // check if this node can be moved
4330           if ( quadsBySide[ side ].size() < 2 )
4331             continue; // its a face boundary -> can't move the node
4332
4333           int quadNodeIndex = ( iSide % 2 ) ? j : i;
4334           int sideNodeIndex = side.ToSideIndex( quadNodeIndex );
4335           if ( side.IsForced( sideNodeIndex ))
4336           {
4337             // the node is already moved to another enforced point
4338             isNodeEnforced = quad->isEqual( myForcedPnts[ iFP ], i, j );
4339             continue;
4340           }
4341           // make a node of a side forced
4342           vector<UVPtStruct>& points = (vector<UVPtStruct>&) side.GetUVPtStruct();
4343           points[ sideNodeIndex ].u = myForcedPnts[ iFP ].U();
4344           points[ sideNodeIndex ].v = myForcedPnts[ iFP ].V();
4345
4346           updateSideUV( side, sideNodeIndex, quadsBySide );
4347
4348           // update adjacent sides
4349           set< StdMeshers_FaceSidePtr > updatedSides;
4350           updatedSides.insert( side );
4351           for ( size_t i = 0; i < side.contacts.size(); ++i )
4352             if ( side.contacts[i].point == sideNodeIndex )
4353             {
4354               const vector< FaceQuadStruct::Ptr >& adjQuads =
4355                 quadsBySide[ *side.contacts[i].other_side ];
4356               if ( adjQuads.size() > 1 &&
4357                    updatedSides.insert( * side.contacts[i].other_side ).second )
4358               {
4359                 updateSideUV( *side.contacts[i].other_side,
4360                               side.contacts[i].other_point,
4361                               quadsBySide );
4362               }
4363               changedQuads.insert( adjQuads.begin(), adjQuads.end() );
4364             }
4365           const vector< FaceQuadStruct::Ptr >& adjQuads = quadsBySide[ side ];
4366           changedQuads.insert( adjQuads.begin(), adjQuads.end() );
4367
4368           isNodeEnforced = true;
4369         }
4370         else // ------------------ node is inside the quad
4371         {
4372           // make a new side passing through IJ node and split the quad
4373           int indForced, iNewSide;
4374           if ( quad->iSize < quad->jSize ) // split vertically
4375           {
4376             quad->updateUV( myForcedPnts[ iFP ].uv, i, j, /*isVert=*/true );
4377             indForced = i;
4378             iNewSide  = splitQuad( quad, i, 0 );
4379           }
4380           else
4381           {
4382             quad->updateUV( myForcedPnts[ iFP ].uv, i, j, /*isVert=*/false );
4383             indForced = j;
4384             iNewSide  = splitQuad( quad, 0, j );
4385           }
4386           FaceQuadStruct::Ptr   newQuad = myQuadList.back();
4387           FaceQuadStruct::Side& newSide = newQuad->side[ iNewSide ];
4388
4389           newSide.forced_nodes.insert( indForced );
4390           quad->side[( iNewSide+2 ) % 4 ].forced_nodes.insert( indForced );
4391
4392           quadsBySide[ newSide ].push_back( quad );
4393           quadsBySide[ newSide ].push_back( newQuad );
4394
4395           isNodeEnforced = true;
4396
4397         } // end of "node is inside the quad"
4398
4399       } // loop on nodes of the cell
4400
4401       // remove out-of-date uv grid of changedQuads
4402       set< FaceQuadStruct::Ptr >::iterator qIt = changedQuads.begin();
4403       for ( ; qIt != changedQuads.end(); ++qIt )
4404         (*qIt)->uv_grid.clear();
4405
4406     } // loop on quads
4407
4408     if ( !isNodeEnforced )
4409     {
4410       if ( !myForcedPnts[ iFP ].vertex.IsNull() )
4411         return error(TComm("Unable to move any node to vertex #")
4412                      <<myHelper->GetMeshDS()->ShapeToIndex( myForcedPnts[ iFP ].vertex ));
4413       else
4414         return error(TComm("Unable to move any node to point ( ")
4415                      << myForcedPnts[iFP].xyz.X() << ", "
4416                      << myForcedPnts[iFP].xyz.Y() << ", "
4417                      << myForcedPnts[iFP].xyz.Z() << " )");
4418     }
4419
4420   } // loop on enforced points
4421
4422   // Compute nodes on all sides, where not yet present
4423
4424   for ( quadIt = myQuadList.begin(); quadIt != myQuadList.end(); ++quadIt )
4425   {
4426     FaceQuadStruct::Ptr quad = *quadIt;
4427     for ( int iSide = 0; iSide < 4; ++iSide )
4428     {
4429       FaceQuadStruct::Side & side = quad->side[ iSide ];
4430       if ( side.nbNodeOut > 0 )
4431         continue; // emulated side
4432       vector< FaceQuadStruct::Ptr >& quadVec = quadsBySide[ side ];
4433       if ( quadVec.size() <= 1 )
4434         continue; // outer side
4435
4436       bool missedNodesOnSide = false;
4437       const vector<UVPtStruct>& points = side.grid->GetUVPtStruct();
4438       for ( size_t iC = 0; iC < side.contacts.size(); ++iC )
4439       {
4440         const vector<UVPtStruct>& oGrid = side.contacts[iC].other_side->grid->GetUVPtStruct();
4441         const UVPtStruct&         uvPt  = points[ side.contacts[iC].point ];
4442         if ( side.contacts[iC].other_point >= oGrid.size()      ||
4443              side.contacts[iC].point       >= points.size() )
4444           throw SALOME_Exception( "StdMeshers_Quadrangle_2D::addEnforcedNodes(): wrong contact" );
4445         if ( oGrid[ side.contacts[iC].other_point ].node )
4446           (( UVPtStruct& ) uvPt).node = oGrid[ side.contacts[iC].other_point ].node;
4447       }
4448       for ( size_t iP = 0; iP < points.size(); ++iP )
4449         if ( !points[ iP ].node )
4450         {
4451           UVPtStruct& uvPnt = ( UVPtStruct& ) points[ iP ];
4452           gp_Pnt P = surf->Value( uvPnt.u, uvPnt.v );
4453           uvPnt.node = meshDS->AddNode(P.X(), P.Y(), P.Z());
4454           meshDS->SetNodeOnFace( uvPnt.node, myHelper->GetSubShapeID(), uvPnt.u, uvPnt.v );
4455           missedNodesOnSide = true;
4456         }
4457       if ( missedNodesOnSide )
4458       {
4459         // clear uv_grid where nodes are missing
4460         for ( size_t iQ = 0; iQ < quadVec.size(); ++iQ )
4461           quadVec[ iQ ]->uv_grid.clear();
4462       }
4463     }
4464   }
4465
4466   return true;
4467 }
4468
4469 //================================================================================
4470 /*!
4471  * \brief Splits a quad at I or J. Returns an index of a new side in the new quad
4472  */
4473 //================================================================================
4474
4475 int StdMeshers_Quadrangle_2D::splitQuad(FaceQuadStruct::Ptr quad, int I, int J)
4476 {
4477   FaceQuadStruct* newQuad = new FaceQuadStruct( quad->face );
4478   myQuadList.push_back( FaceQuadStruct::Ptr( newQuad ));
4479
4480   vector<UVPtStruct> points;
4481   if ( I > 0 )
4482   {
4483     points.reserve( quad->jSize );
4484     for ( int jP = 0; jP < quad->jSize; ++jP )
4485       points.push_back( quad->UVPt( I, jP ));
4486
4487     newQuad->side.resize( 4 );
4488     newQuad->side[ QUAD_BOTTOM_SIDE ] = quad->side[ QUAD_BOTTOM_SIDE ];
4489     newQuad->side[ QUAD_RIGHT_SIDE  ] = quad->side[ QUAD_RIGHT_SIDE  ];
4490     newQuad->side[ QUAD_TOP_SIDE    ] = quad->side[ QUAD_TOP_SIDE    ];
4491     newQuad->side[ QUAD_LEFT_SIDE   ] = StdMeshers_FaceSide::New( points, quad->face );
4492
4493     FaceQuadStruct::Side& newSide  = newQuad->side[ QUAD_LEFT_SIDE ];
4494     FaceQuadStruct::Side& newSide2 = quad->side   [ QUAD_RIGHT_SIDE ];
4495
4496     quad->side[ QUAD_RIGHT_SIDE  ] = newSide;
4497
4498     int iBot = quad->side[ QUAD_BOTTOM_SIDE ].ToSideIndex( I );
4499     int iTop = quad->side[ QUAD_TOP_SIDE    ].ToSideIndex( I );
4500
4501     newSide.AddContact ( 0,               & quad->side[ QUAD_BOTTOM_SIDE ], iBot );
4502     newSide2.AddContact( 0,               & quad->side[ QUAD_BOTTOM_SIDE ], iBot );
4503     newSide.AddContact ( quad->jSize - 1, & quad->side[ QUAD_TOP_SIDE    ], iTop );
4504     newSide2.AddContact( quad->jSize - 1, & quad->side[ QUAD_TOP_SIDE    ], iTop );
4505     // cout << "Contact: L " << &newSide << " "<< newSide.NbPoints()
4506     //      << " R " << &newSide2 << " "<< newSide2.NbPoints()
4507     //      << " B " << &quad->side[ QUAD_BOTTOM_SIDE ] << " "<< quad->side[ QUAD_BOTTOM_SIDE].NbPoints()
4508     //      << " T " << &quad->side[ QUAD_TOP_SIDE ]  << " "<< quad->side[ QUAD_TOP_SIDE].NbPoints()<< endl;
4509
4510     newQuad->side[ QUAD_BOTTOM_SIDE ].from = iBot;
4511     newQuad->side[ QUAD_TOP_SIDE    ].from = iTop;
4512
4513     quad->side[ QUAD_BOTTOM_SIDE ].to = iBot + 1;
4514     quad->side[ QUAD_TOP_SIDE    ].to = iTop + 1;
4515     quad->uv_grid.clear();
4516
4517     return QUAD_LEFT_SIDE;
4518   }
4519   else if ( J > 0 ) //// split horizontally
4520   {
4521     points.reserve( quad->iSize );
4522     for ( int iP = 0; iP < quad->iSize; ++iP )
4523       points.push_back( quad->UVPt( iP, J ));
4524
4525     newQuad->side.resize( 4 );
4526     newQuad->side[ QUAD_BOTTOM_SIDE ] = quad->side[ QUAD_BOTTOM_SIDE ];
4527     newQuad->side[ QUAD_RIGHT_SIDE  ] = quad->side[ QUAD_RIGHT_SIDE  ];
4528     newQuad->side[ QUAD_TOP_SIDE    ] = StdMeshers_FaceSide::New( points, quad->face );
4529     newQuad->side[ QUAD_LEFT_SIDE   ] = quad->side[ QUAD_LEFT_SIDE   ];
4530
4531     FaceQuadStruct::Side& newSide  = newQuad->side[ QUAD_TOP_SIDE    ];
4532     FaceQuadStruct::Side& newSide2 = quad->side   [ QUAD_BOTTOM_SIDE ];
4533
4534     quad->side[ QUAD_BOTTOM_SIDE ] = newSide;
4535
4536     int iLft = quad->side[ QUAD_LEFT_SIDE  ].ToSideIndex( J );
4537     int iRgt = quad->side[ QUAD_RIGHT_SIDE ].ToSideIndex( J );
4538
4539     newSide.AddContact ( 0,               & quad->side[ QUAD_LEFT_SIDE  ], iLft );
4540     newSide2.AddContact( 0,               & quad->side[ QUAD_LEFT_SIDE  ], iLft );
4541     newSide.AddContact ( quad->iSize - 1, & quad->side[ QUAD_RIGHT_SIDE ], iRgt );
4542     newSide2.AddContact( quad->iSize - 1, & quad->side[ QUAD_RIGHT_SIDE ], iRgt );
4543     // cout << "Contact: T " << &newSide << " "<< newSide.NbPoints()
4544     //      << " B " << &newSide2 << " "<< newSide2.NbPoints()
4545     //      << " L " << &quad->side[ QUAD_LEFT_SIDE ] << " "<< quad->side[ QUAD_LEFT_SIDE].NbPoints()
4546     //      << " R " << &quad->side[ QUAD_RIGHT_SIDE ]  << " "<< quad->side[ QUAD_RIGHT_SIDE].NbPoints()<< endl;
4547
4548     newQuad->side[ QUAD_RIGHT_SIDE ].to = iRgt+1;
4549     newQuad->side[ QUAD_LEFT_SIDE  ].to = iLft+1;
4550
4551     quad->side[ QUAD_RIGHT_SIDE ].from = iRgt;
4552     quad->side[ QUAD_LEFT_SIDE  ].from = iLft;
4553     quad->uv_grid.clear();
4554
4555     return QUAD_TOP_SIDE;
4556   }
4557 }
4558
4559 //================================================================================
4560 /*!
4561  * \brief Updates UV of a side after moving its node
4562  */
4563 //================================================================================
4564
4565 void StdMeshers_Quadrangle_2D::updateSideUV( FaceQuadStruct::Side&  side,
4566                                              int                    iForced,
4567                                              const TQuadsBySide&    quadsBySide,
4568                                              int *                  iNext)
4569 {
4570   if ( !iNext )
4571   {
4572     side.forced_nodes.insert( iForced );
4573
4574     // update parts of the side before and after iForced
4575
4576     set<int>::iterator iIt = side.forced_nodes.upper_bound( iForced );
4577     int iEnd = Min( side.NbPoints()-1, ( iIt == side.forced_nodes.end() ) ? int(1e7) : *iIt );
4578     if ( iForced + 1 < iEnd )
4579       updateSideUV( side, iForced, quadsBySide, &iEnd );
4580
4581     iIt = side.forced_nodes.lower_bound( iForced );
4582     int iBeg = Max( 0, ( iIt == side.forced_nodes.begin() ) ? 0 : *--iIt );
4583     if ( iForced - 1 > iBeg )
4584       updateSideUV( side, iForced, quadsBySide, &iBeg );
4585
4586     return;
4587   }
4588
4589   const int iFrom    = Min ( iForced, *iNext );
4590   const int iTo      = Max ( iForced, *iNext ) + 1;
4591   const int sideSize = iTo - iFrom;
4592
4593   vector<UVPtStruct> points[4];
4594
4595   // get from the quads grid points adjacent to the side
4596   // to make two sides of another temporary quad
4597   vector< FaceQuadStruct::Ptr > quads = quadsBySide.find( side )->second; // copy!
4598   for ( int is2nd = 0; is2nd < 2; ++is2nd )
4599   {
4600     points[ is2nd ].reserve( sideSize );
4601     int nbLoops = 0;
4602     while ( points[is2nd].size() < sideSize )
4603     {
4604       int iCur = iFrom + points[is2nd].size() - int( !points[is2nd].empty() );
4605
4606       // look for a quad adjacent to iCur-th point of the side
4607       for ( size_t iQ = 0; iQ < quads.size(); ++iQ )
4608       {
4609         FaceQuadStruct::Ptr q = quads[ iQ ];
4610         if ( !q ) continue;
4611         size_t iS;
4612         for ( iS = 0; iS < q->side.size(); ++iS )
4613           if ( side.grid == q->side[ iS ].grid )
4614             break;
4615         bool isOut;
4616         if ( !q->side[ iS ].IsReversed() )
4617           isOut = ( q->side[ iS ].from > iCur || q->side[ iS ].to-1 <= iCur );
4618         else
4619           isOut = ( q->side[ iS ].to  >= iCur || q->side[ iS ].from <= iCur );
4620         if ( isOut )
4621           continue;
4622
4623         // found - copy points
4624         int i,j,di,dj,nb;
4625         if ( iS % 2 ) // right ot left
4626         {
4627           i  = ( iS == QUAD_LEFT_SIDE ) ? 1 : q->iSize-2;
4628           j  = q->side[ iS ].ToQuadIndex( iCur );
4629           di = 0;
4630           dj = ( q->side[ iS ].IsReversed() ) ? -1  : +1;
4631           nb = ( q->side[ iS ].IsReversed() ) ? j+1 : q->jSize-j;
4632         }
4633         else // bottom or top
4634         {
4635           i  = q->side[ iS ].ToQuadIndex( iCur );
4636           j  = ( iS == QUAD_BOTTOM_SIDE )  ?  1 : q->jSize-2;
4637           di = ( q->side[ iS ].IsReversed() ) ? -1  : +1;
4638           dj = 0;
4639           nb = ( q->side[ iS ].IsReversed() ) ? i+1 : q->iSize-i;
4640         }
4641         if ( !points[is2nd].empty() )
4642         {
4643           gp_UV lastUV = points[is2nd].back().UV();
4644           gp_UV quadUV = q->UVPt( i, j ).UV();
4645           if ( ( lastUV - quadUV ).SquareModulus() > 1e-10 )
4646             continue; // quad is on the other side of the side
4647           i += di; j += dj; --nb;
4648         }
4649         for ( ; nb > 0 ; --nb )
4650         {
4651           points[ is2nd ].push_back( q->UVPt( i, j ));
4652           if ( points[is2nd].size() >= sideSize )
4653             break;
4654           i += di; j += dj;
4655         }
4656         quads[ iQ ].reset(); // not to use this quad anymore
4657
4658         if ( points[is2nd].size() >= sideSize )
4659           break;
4660       } // loop on quads
4661
4662       if ( nbLoops++ > quads.size() )
4663         throw SALOME_Exception( "StdMeshers_Quadrangle_2D::updateSideUV() bug: infinite loop" );
4664
4665     } // while ( points[is2nd].size() < sideSize )
4666   } // two loops to fill points[0] and points[1]
4667
4668   // points for other pair of opposite sides of the temporary quad
4669
4670   enum { L,R,B,T }; // side index of points[]
4671
4672   points[B].push_back( points[L].front() );
4673   points[B].push_back( side.GetUVPtStruct()[ iFrom ]);
4674   points[B].push_back( points[R].front() );
4675
4676   points[T].push_back( points[L].back() );
4677   points[T].push_back( side.GetUVPtStruct()[ iTo-1 ]);
4678   points[T].push_back( points[R].back() );
4679
4680   // make the temporary quad
4681   FaceQuadStruct::Ptr tmpQuad( new FaceQuadStruct( TopoDS::Face( myHelper->GetSubShape() )));
4682   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[B] )); // bottom
4683   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[R] )); // right
4684   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[T] ));
4685   tmpQuad->side.push_back( StdMeshers_FaceSide::New( points[L] ));
4686
4687   // compute new UV of the side
4688   setNormalizedGrid( tmpQuad );
4689   gp_UV uv = tmpQuad->UVPt(1,0).UV();
4690   tmpQuad->updateUV( uv, 1,0, /*isVertical=*/true );
4691
4692   // update UV of the side
4693   vector<UVPtStruct>& sidePoints = (vector<UVPtStruct>&) side.GetUVPtStruct();
4694   for ( int i = iFrom; i < iTo; ++i )
4695     sidePoints[ i ] = tmpQuad->UVPt( 1, i-iFrom );
4696 }
4697
4698 //================================================================================
4699 /*!
4700  * \brief Finds indices of a grid quad enclosing the given enforced UV
4701  */
4702 //================================================================================
4703
4704 bool FaceQuadStruct::findCell( const gp_XY& UV, int & I, int & J )
4705 {
4706   // setNormalizedGrid() must be called before!
4707   if ( uv_box.IsOut( UV ))
4708     return false;
4709
4710   // find an approximate position
4711   double x = 0.5, y = 0.5;
4712   gp_XY t0 = UVPt( iSize - 1, 0 ).UV();
4713   gp_XY t1 = UVPt( 0, jSize - 1 ).UV();
4714   gp_XY t2 = UVPt( 0, 0         ).UV();
4715   SMESH_MeshAlgos::GetBarycentricCoords( UV, t0, t1, t2, x, y );
4716   x = Min( 1., Max( 0., x ));
4717   y = Min( 1., Max( 0., y ));
4718
4719   // precise the position
4720   //int i, j;
4721   normPa2IJ( x,y, I,J );
4722   if ( !isNear( UV, I,J ))
4723   {
4724     // look for the most close IJ by traversing uv_grid in the middle
4725     double dist2, minDist2 = ( UV - UVPt( I,J ).UV() ).SquareModulus();
4726     for ( int isU = 0; isU < 2; ++isU )
4727     {
4728       int ind1 = isU ? 0 : iSize / 2;
4729       int ind2 = isU ? jSize / 2 : 0;
4730       int di1  = isU ? Max( 2, iSize / 20 ) : 0;
4731       int di2  = isU ? 0 : Max( 2, jSize / 20 );
4732       int i,nb = isU ? iSize / di1 : jSize / di2;
4733       for ( i = 0; i < nb; ++i, ind1 += di1, ind2 += di2 )
4734         if (( dist2 = ( UV - UVPt( ind1,ind2 ).UV() ).SquareModulus() ) < minDist2 )
4735         {
4736           I = ind1;
4737           J = ind2;
4738           if ( isNear( UV, I,J ))
4739             return true;
4740           minDist2 = ( UV - UVPt( I,J ).UV() ).SquareModulus();
4741         }
4742     }
4743     if ( !isNear( UV, I,J, Max( iSize, jSize ) /2 ))
4744       return false;
4745   }
4746   return true;
4747 }
4748
4749 //================================================================================
4750 /*!
4751  * \brief Find indices (i,j) of a point in uv_grid by normalized parameters (x,y)
4752  */
4753 //================================================================================
4754
4755 void FaceQuadStruct::normPa2IJ(double X, double Y, int & I, int & J )
4756 {
4757
4758   I = Min( int ( iSize * X ), iSize - 2 );
4759   J = Min( int ( jSize * Y ), jSize - 2 );
4760
4761   int oldI, oldJ;
4762   do
4763   {
4764     oldI = I, oldJ = J;
4765     while ( X <= UVPt( I,J ).x   && I != 0 )
4766       --I;
4767     while ( X >  UVPt( I+1,J ).x && I+1 < iSize )
4768       ++I;
4769     while ( Y <= UVPt( I,J ).y   && J != 0 )
4770       --J;
4771     while ( Y >  UVPt( I,J+1 ).y && J+1 < jSize )
4772       ++J;
4773   } while ( oldI != I || oldJ != J );
4774 }
4775
4776 //================================================================================
4777 /*!
4778  * \brief Looks for UV in quads around a given (I,J) and precise (I,J)
4779  */
4780 //================================================================================
4781
4782 bool FaceQuadStruct::isNear( const gp_XY& UV, int & I, int & J, int nbLoops )
4783 {
4784   if ( I+1 >= iSize ) I = iSize - 2;
4785   if ( J+1 >= jSize ) J = jSize - 2;
4786
4787   double bcI, bcJ;
4788   gp_XY uvI, uvJ, uv0, uv1;
4789   for ( int iLoop = 0; iLoop < nbLoops; ++iLoop )
4790   {
4791     int oldI = I, oldJ = J;
4792
4793     uvI = UVPt( I+1, J ).UV();
4794     uvJ = UVPt( I, J+1 ).UV();
4795     uv0 = UVPt( I, J   ).UV();
4796     SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv0, bcI, bcJ );
4797     if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
4798       return true;
4799
4800     if ( I > 0       && bcI < 0. ) --I;
4801     if ( I+1 < iSize && bcI > 1. ) ++I;
4802     if ( J > 0       && bcJ < 0. ) --J;
4803     if ( J+1 < jSize && bcJ > 1. ) ++J;
4804
4805     uv1 = UVPt( I+1,J+1).UV();
4806     if ( I != oldI || J != oldJ )
4807     {
4808       uvI = UVPt( I+1, J ).UV();
4809       uvJ = UVPt( I, J+1 ).UV();
4810     }
4811     SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv1, bcI, bcJ );
4812     if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
4813       return true;
4814
4815     if ( I > 0       && bcI > 1. ) --I;
4816     if ( I+1 < iSize && bcI < 0. ) ++I;
4817     if ( J > 0       && bcJ > 1. ) --J;
4818     if ( J+1 < jSize && bcJ < 0. ) ++J;
4819
4820     if ( I == oldI && J == oldJ )
4821       return false;
4822
4823     if ( iLoop+1 == nbLoops )
4824     {
4825       uvI = UVPt( I+1, J ).UV();
4826       uvJ = UVPt( I, J+1 ).UV();
4827       uv0 = UVPt( I, J   ).UV();
4828       SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv0, bcI, bcJ );
4829       if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
4830         return true;
4831
4832       uv1 = UVPt( I+1,J+1).UV();
4833       SMESH_MeshAlgos::GetBarycentricCoords( UV, uvI, uvJ, uv1, bcI, bcJ );
4834       if ( bcI >= 0. && bcJ >= 0. && bcI + bcJ <= 1.)
4835         return true;
4836     }
4837   }
4838   return false;
4839 }
4840
4841 //================================================================================
4842 /*!
4843  * \brief Checks if a given UV is equal to a given frid point
4844  */
4845 //================================================================================
4846
4847 bool FaceQuadStruct::isEqual( const gp_XY& UV, int I, int J )
4848 {
4849   TopLoc_Location loc;
4850   Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
4851   gp_Pnt p1 = surf->Value( UV.X(), UV.Y() );
4852   gp_Pnt p2 = surf->Value( UVPt( I,J ).u, UVPt( I,J ).v );
4853
4854   double dist2 = 1e100;
4855   for ( int di = -1; di < 2; di += 2 )
4856   {
4857     int i = I + di;
4858     if ( i < 0 || i+1 >= iSize ) continue;
4859     for ( int dj = -1; dj < 2; dj += 2 )
4860     {
4861       int j = J + dj;
4862       if ( j < 0 || j+1 >= jSize ) continue;
4863
4864       dist2 = Min( dist2,
4865                    p2.SquareDistance( surf->Value( UVPt( i,j ).u, UVPt( i,j ).v )));
4866     }
4867   }
4868   double tol2 = dist2 / 1000.;
4869   return p1.SquareDistance( p2 ) < tol2;
4870 }
4871
4872 //================================================================================
4873 /*!
4874  * \brief Recompute UV of grid points around a moved point in one direction
4875  */
4876 //================================================================================
4877
4878 void FaceQuadStruct::updateUV( const gp_XY& UV, int I, int J, bool isVertical )
4879 {
4880   UVPt( I, J ).u = UV.X();
4881   UVPt( I, J ).v = UV.Y();
4882
4883   if ( isVertical )
4884   {
4885     // above J
4886     if ( J+1 < jSize-1 )
4887     {
4888       gp_UV a0 = UVPt( 0,       J       ).UV();
4889       gp_UV a1 = UVPt( iSize-1, J       ).UV();
4890       gp_UV a2 = UVPt( iSize-1, jSize-1 ).UV();
4891       gp_UV a3 = UVPt( 0,       jSize-1 ).UV();
4892
4893       gp_UV p0 = UVPt( I, J       ).UV();
4894       gp_UV p2 = UVPt( I, jSize-1 ).UV();
4895       const double y0 = UVPt( I, J ).y, dy = 1. - y0;
4896       for (int j = J+1; j < jSize-1; j++)
4897       {
4898         gp_UV p1 = UVPt( iSize-1, j ).UV();
4899         gp_UV p3 = UVPt( 0,       j ).UV();
4900
4901         UVPtStruct& uvPt = UVPt( I, j );
4902         gp_UV uv = calcUV( uvPt.x, ( uvPt.y - y0 ) / dy, a0,a1,a2,a3, p0,p1,p2,p3);
4903         uvPt.u = uv.X();
4904         uvPt.v = uv.Y();
4905       }
4906     }
4907     // under J
4908     if ( J-1 > 0 )
4909     {
4910       gp_UV a0 = UVPt( 0,       0 ).UV();
4911       gp_UV a1 = UVPt( iSize-1, 0 ).UV();
4912       gp_UV a2 = UVPt( iSize-1, J ).UV();
4913       gp_UV a3 = UVPt( 0,       J ).UV();
4914
4915       gp_UV p0 = UVPt( I, 0 ).UV();
4916       gp_UV p2 = UVPt( I, J ).UV();
4917       const double y0 = 0., dy = UVPt( I, J ).y - y0;
4918       for (int j = 1; j < J; j++)
4919       {
4920         gp_UV p1 = UVPt( iSize-1, j ).UV();
4921         gp_UV p3 = UVPt( 0,       j ).UV();
4922
4923         UVPtStruct& uvPt = UVPt( I, j );
4924         gp_UV uv = calcUV( uvPt.x, ( uvPt.y - y0 ) / dy, a0,a1,a2,a3, p0,p1,p2,p3);
4925         uvPt.u = uv.X();
4926         uvPt.v = uv.Y();
4927       }
4928     }
4929   }
4930   else  // horizontally
4931   {
4932     // before I
4933     if ( I-1 > 0 )
4934     {
4935       gp_UV a0 = UVPt( 0, 0 ).UV();
4936       gp_UV a1 = UVPt( I, 0 ).UV();
4937       gp_UV a2 = UVPt( I, jSize-1 ).UV();
4938       gp_UV a3 = UVPt( 0, jSize-1 ).UV();
4939
4940       gp_UV p1 = UVPt( I, J ).UV();
4941       gp_UV p3 = UVPt( 0, J ).UV();
4942       const double x0 = 0., dx = UVPt( I, J ).x - x0;
4943       for (int i = 1; i < I; i++)
4944       {
4945         gp_UV p0 = UVPt( i, 0       ).UV();
4946         gp_UV p2 = UVPt( i, jSize-1 ).UV();
4947
4948         UVPtStruct& uvPt = UVPt( i, J );
4949         gp_UV uv = calcUV(( uvPt.x - x0 ) / dx , uvPt.y, a0,a1,a2,a3, p0,p1,p2,p3);
4950         uvPt.u = uv.X();
4951         uvPt.v = uv.Y();
4952       }
4953     }
4954     // after I
4955     if ( I+1 < iSize-1 )
4956     {
4957       gp_UV a0 = UVPt( I,       0 ).UV();
4958       gp_UV a1 = UVPt( iSize-1, 0 ).UV();
4959       gp_UV a2 = UVPt( iSize-1, jSize-1 ).UV();
4960       gp_UV a3 = UVPt( I,       jSize-1 ).UV();
4961
4962       gp_UV p1 = UVPt( iSize-1, J ).UV();
4963       gp_UV p3 = UVPt( I,       J ).UV();
4964       const double x0 = UVPt( I, J ).x, dx = 1. - x0;
4965       for (int i = I+1; i < iSize-1; i++)
4966       {
4967         gp_UV p0 = UVPt( i, 0       ).UV();
4968         gp_UV p2 = UVPt( i, jSize-1 ).UV();
4969
4970         UVPtStruct& uvPt = UVPt( i, J );
4971         gp_UV uv = calcUV(( uvPt.x - x0 ) / dx , uvPt.y, a0,a1,a2,a3, p0,p1,p2,p3);
4972         uvPt.u = uv.X();
4973         uvPt.v = uv.Y();
4974       }
4975     }
4976   }
4977 }
4978
4979 //================================================================================
4980 /*!
4981  * \brief Side copying
4982  */
4983 //================================================================================
4984
4985 FaceQuadStruct::Side& FaceQuadStruct::Side::operator=(const Side& otherSide)
4986 {
4987   grid = otherSide.grid;
4988   from = otherSide.from;
4989   to   = otherSide.to;
4990   forced_nodes = otherSide.forced_nodes;
4991   contacts     = otherSide.contacts;
4992   nbNodeOut    = otherSide.nbNodeOut;
4993
4994   for ( size_t iC = 0; iC < contacts.size(); ++iC )
4995   {
4996     FaceQuadStruct::Side* oSide = contacts[iC].other_side;
4997     for ( size_t iOC = 0; iOC < oSide->contacts.size(); ++iOC )
4998       if ( oSide->contacts[iOC].other_side == & otherSide )
4999       {
5000         // cout << "SHIFT old " << &otherSide << " " << otherSide.NbPoints()
5001         //      << " -> new " << this << " " << this->NbPoints() << endl;
5002         oSide->contacts[iOC].other_side = this;
5003       }
5004   }
5005 }
5006
5007 //================================================================================
5008 /*!
5009  * \brief Converts node index of a quad to node index of this side
5010  */
5011 //================================================================================
5012
5013 int FaceQuadStruct::Side::ToSideIndex( int quadNodeIndex ) const
5014 {
5015   return ( from > to ) ? ( from - quadNodeIndex ) : ( quadNodeIndex + from );
5016 }
5017
5018 //================================================================================
5019 /*!
5020  * \brief Converts node index of this side to node index of a quad
5021  */
5022 //================================================================================
5023
5024 int FaceQuadStruct::Side::ToQuadIndex( int sideNodeIndex ) const
5025 {
5026   return ( from > to ) ? ( from - sideNodeIndex ) : ( sideNodeIndex - from );
5027 }
5028
5029 //================================================================================
5030 /*!
5031  * \brief Checks if a node is enforced
5032  *  \param [in] nodeIndex - an index of a node in a size
5033  *  \return bool - \c true if the node is forced
5034  */
5035 //================================================================================
5036
5037 bool FaceQuadStruct::Side::IsForced( int nodeIndex ) const
5038 {
5039   if ( nodeIndex < 0 || nodeIndex >= grid->NbPoints() )
5040     throw SALOME_Exception( " FaceQuadStruct::Side::IsForced(): wrong index" );
5041
5042   if ( forced_nodes.count( nodeIndex ) )
5043     return true;
5044
5045   for ( size_t i = 0; i < this->contacts.size(); ++i )
5046     if ( contacts[ i ].point == nodeIndex &&
5047          contacts[ i ].other_side->forced_nodes.count( contacts[ i ].other_point ))
5048       return true;
5049
5050   return false;
5051 }
5052
5053 //================================================================================
5054 /*!
5055  * \brief Sets up a contact between this and another side
5056  */
5057 //================================================================================
5058
5059 void FaceQuadStruct::Side::AddContact( int ip, Side* side, int iop )
5060 {
5061   if ( ip  >= GetUVPtStruct().size()      ||
5062        iop >= side->GetUVPtStruct().size() )
5063     throw SALOME_Exception( "FaceQuadStruct::Side::AddContact(): wrong point" );
5064   {
5065     contacts.resize( contacts.size() + 1 );
5066     Contact&    c = contacts.back();
5067     c.point       = ip;
5068     c.other_side  = side;
5069     c.other_point = iop;
5070   }
5071   {
5072     side->contacts.resize( side->contacts.size() + 1 );
5073     Contact&    c = side->contacts.back();
5074     c.point       = iop;
5075     c.other_side  = this;
5076     c.other_point = ip;
5077   }
5078 }
5079
5080 //================================================================================
5081 /*!
5082  * \brief Returns a normalized parameter of a point indexed within a quadrangle
5083  */
5084 //================================================================================
5085
5086 double FaceQuadStruct::Side::Param( int i ) const
5087 {
5088   const vector<UVPtStruct>& points = GetUVPtStruct();
5089   return (( points[ from + i ].normParam - points[ from ].normParam ) /
5090           ( points[ to   - 1 ].normParam - points[ from ].normParam ));
5091 }
5092
5093 //================================================================================
5094 /*!
5095  * \brief Returns UV by a parameter normalized within a quadrangle
5096  */
5097 //================================================================================
5098
5099 gp_XY FaceQuadStruct::Side::Value2d( double x ) const
5100 {
5101   const vector<UVPtStruct>& points = GetUVPtStruct();
5102   double u = ( points[ from ].normParam +
5103                x * ( points[ to-1 ].normParam - points[ from ].normParam ));
5104   return grid->Value2d( u ).XY();
5105 }
5106
5107 //================================================================================
5108 /*!
5109  * \brief Returns side length
5110  */
5111 //================================================================================
5112
5113 double FaceQuadStruct::Side::Length(int theFrom, int theTo) const
5114 {
5115   const vector<UVPtStruct>& points = GetUVPtStruct();
5116   double r = ( points[ Max( to,   theTo )-1 ].normParam -
5117                points[ Max( from, theFrom ) ].normParam );
5118   return r * grid->Length();
5119 }