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