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