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