Salome HOME
d75a5aac2de8c7be2bd8f4387197e17d9199ae3f
[modules/smesh.git] / src / StdMeshers / StdMeshers_Quadrangle_2D.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  File   : StdMeshers_Quadrangle_2D.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26
27 #include "StdMeshers_Quadrangle_2D.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshNode.hxx"
33 #include "SMESH_Block.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Mesh.hxx"
37 #include "SMESH_MesherHelper.hxx"
38 #include "SMESH_subMesh.hxx"
39 #include "StdMeshers_FaceSide.hxx"
40 #include "StdMeshers_QuadrangleParams.hxx"
41 #include "StdMeshers_ViscousLayers2D.hxx"
42
43 #include <BRep_Tool.hxx>
44 #include <Geom_Surface.hxx>
45 #include <NCollection_DefineArray2.hxx>
46 #include <Precision.hxx>
47 #include <TColStd_SequenceOfReal.hxx>
48 #include <TColStd_SequenceOfInteger.hxx>
49 #include <TColgp_SequenceOfXY.hxx>
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_ListIteratorOfListOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
54 #include <TopoDS.hxx>
55
56 #include "utilities.h"
57 #include "Utils_ExceptHandlers.hxx"
58
59 #ifndef StdMeshers_Array2OfNode_HeaderFile
60 #define StdMeshers_Array2OfNode_HeaderFile
61 typedef const SMDS_MeshNode* SMDS_MeshNodePtr;
62 DEFINE_BASECOLLECTION (StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
63 DEFINE_ARRAY2(StdMeshers_Array2OfNode,
64               StdMeshers_BaseCollectionNodePtr, SMDS_MeshNodePtr)
65 #endif
66
67 using namespace std;
68
69 typedef gp_XY gp_UV;
70 typedef SMESH_Comment TComm;
71
72 //=============================================================================
73 /*!
74  *  
75  */
76 //=============================================================================
77
78 StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D (int hypId, int studyId,
79                                                     SMESH_Gen* gen)
80   : SMESH_2D_Algo(hypId, studyId, gen),
81     myHelper( 0 )
82 {
83   MESSAGE("StdMeshers_Quadrangle_2D::StdMeshers_Quadrangle_2D");
84   _name = "Quadrangle_2D";
85   _shapeType = (1 << TopAbs_FACE);
86   _compatibleHypothesis.push_back("QuadrangleParams");
87   _compatibleHypothesis.push_back("QuadranglePreference");
88   _compatibleHypothesis.push_back("TrianglePreference");
89   _compatibleHypothesis.push_back("ViscousLayers2D");
90 }
91
92 //=============================================================================
93 /*!
94  *  
95  */
96 //=============================================================================
97
98 StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D()
99 {
100   MESSAGE("StdMeshers_Quadrangle_2D::~StdMeshers_Quadrangle_2D");
101 }
102
103 //=============================================================================
104 /*!
105  *  
106  */
107 //=============================================================================
108
109 bool StdMeshers_Quadrangle_2D::CheckHypothesis
110                          (SMESH_Mesh&                          aMesh,
111                           const TopoDS_Shape&                  aShape,
112                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
113 {
114   bool isOk = true;
115   aStatus = SMESH_Hypothesis::HYP_OK;
116
117   const list <const SMESHDS_Hypothesis * >& hyps =
118     GetUsedHypothesis(aMesh, aShape, false);
119   const SMESHDS_Hypothesis * aHyp = 0;
120
121   myTriaVertexID = -1;
122   myQuadType = QUAD_STANDARD;
123   myQuadranglePreference = false;
124   myTrianglePreference = false;
125
126   bool isFirstParams = true;
127
128   // First assigned hypothesis (if any) is processed now
129   if (hyps.size() > 0) {
130     aHyp = hyps.front();
131     if (strcmp("QuadrangleParams", aHyp->GetName()) == 0) {
132       const StdMeshers_QuadrangleParams* aHyp1 = 
133         (const StdMeshers_QuadrangleParams*)aHyp;
134       myTriaVertexID = aHyp1->GetTriaVertex();
135       myQuadType = aHyp1->GetQuadType();
136       if (myQuadType == QUAD_QUADRANGLE_PREF ||
137           myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
138         myQuadranglePreference = true;
139       else if (myQuadType == QUAD_TRIANGLE_PREF)
140         myTrianglePreference = true;
141     }
142     else if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
143       isFirstParams = false;
144       myQuadranglePreference = true;
145     }
146     else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
147       isFirstParams = false;
148       myTrianglePreference = true; 
149     }
150     else {
151       isFirstParams = false;
152     }
153   }
154
155   // Second(last) assigned hypothesis (if any) is processed now
156   if (hyps.size() > 1) {
157     aHyp = hyps.back();
158     if (isFirstParams) {
159       if (strcmp("QuadranglePreference", aHyp->GetName()) == 0) {
160         myQuadranglePreference = true;
161         myTrianglePreference = false; 
162         myQuadType = QUAD_STANDARD;
163       }
164       else if (strcmp("TrianglePreference", aHyp->GetName()) == 0){
165         myQuadranglePreference = false;
166         myTrianglePreference = true; 
167         myQuadType = QUAD_STANDARD;
168       }
169     }
170     else {
171       const StdMeshers_QuadrangleParams* aHyp2 = 
172         (const StdMeshers_QuadrangleParams*)aHyp;
173       myTriaVertexID = aHyp2->GetTriaVertex();
174
175       if (!myQuadranglePreference && !myTrianglePreference) { // priority of hypos
176         myQuadType = aHyp2->GetQuadType();
177         if (myQuadType == QUAD_QUADRANGLE_PREF ||
178             myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
179           myQuadranglePreference = true;
180         else if (myQuadType == QUAD_TRIANGLE_PREF)
181           myTrianglePreference = true;
182       }
183     }
184   }
185
186   return isOk;
187 }
188
189 //=============================================================================
190 /*!
191  *  
192  */
193 //=============================================================================
194
195 bool StdMeshers_Quadrangle_2D::Compute (SMESH_Mesh&         aMesh,
196                                         const TopoDS_Shape& aShape)
197 {
198   const TopoDS_Face& F = TopoDS::Face(aShape);
199   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
200
201   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
202   aMesh.GetSubMesh(aShape);
203
204   SMESH_MesherHelper helper (aMesh);
205   myHelper = &helper;
206
207   myProxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
208   if ( !myProxyMesh )
209     return false;
210
211   _quadraticMesh = myHelper->IsQuadraticSubMesh(aShape);
212   myNeedSmooth = false;
213
214   FaceQuadStruct *quad = CheckNbEdges(aMesh, aShape);
215   std::auto_ptr<FaceQuadStruct> quadDeleter (quad); // to delete quad at exit from Compute()
216   if (!quad)
217     return false;
218
219   if (myQuadranglePreference) {
220     int n1 = quad->side[0]->NbPoints();
221     int n2 = quad->side[1]->NbPoints();
222     int n3 = quad->side[2]->NbPoints();
223     int n4 = quad->side[3]->NbPoints();
224     int nfull = n1+n2+n3+n4;
225     int ntmp = nfull/2;
226     ntmp = ntmp*2;
227     if (nfull == ntmp && ((n1 != n3) || (n2 != n4))) {
228       // special path for using only quandrangle faces
229       bool ok = ComputeQuadPref(aMesh, aShape, quad);
230       if ( ok && myNeedSmooth )
231         Smooth( quad ); 
232       return ok;
233     }
234   }
235   else if (myQuadType == QUAD_REDUCED) {
236     int n1 = quad->side[0]->NbPoints();
237     int n2 = quad->side[1]->NbPoints();
238     int n3 = quad->side[2]->NbPoints();
239     int n4 = quad->side[3]->NbPoints();
240     int n13 = n1 - n3;
241     int n24 = n2 - n4;
242     int n13tmp = n13/2; n13tmp = n13tmp*2;
243     int n24tmp = n24/2; n24tmp = n24tmp*2;
244     if ((n1 == n3 && n2 != n4 && n24tmp == n24) ||
245         (n2 == n4 && n1 != n3 && n13tmp == n13)) {
246       bool ok = ComputeReduced(aMesh, aShape, quad);
247       if ( ok && myNeedSmooth )
248         Smooth( quad ); 
249       return ok;
250     }
251   }
252
253   // set normalized grid on unit square in parametric domain
254   
255   if (!SetNormalizedGrid(aMesh, aShape, quad))
256     return false;
257
258   // --- compute 3D values on points, store points & quadrangles
259
260   int nbdown  = quad->side[0]->NbPoints();
261   int nbup    = quad->side[2]->NbPoints();
262
263   int nbright = quad->side[1]->NbPoints();
264   int nbleft  = quad->side[3]->NbPoints();
265
266   int nbhoriz  = Min(nbdown, nbup);
267   int nbvertic = Min(nbright, nbleft);
268
269   // internal mesh nodes
270   int i, j, geomFaceID = meshDS->ShapeToIndex(F);
271   for (i = 1; i < nbhoriz - 1; i++) {
272     for (j = 1; j < nbvertic - 1; j++) {
273       int ij = j * nbhoriz + i;
274       double u = quad->uv_grid[ij].u;
275       double v = quad->uv_grid[ij].v;
276       gp_Pnt P = S->Value(u, v);
277       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
278       meshDS->SetNodeOnFace(node, geomFaceID, u, v);
279       quad->uv_grid[ij].node = node;
280     }
281   }
282   
283   // mesh faces
284
285   //             [2]
286   //      --.--.--.--.--.--  nbvertic
287   //     |                 | ^
288   //     |                 | ^
289   // [3] |                 | ^ j  [1]
290   //     |                 | ^
291   //     |                 | ^
292   //      ---.----.----.---  0
293   //     0 > > > > > > > > nbhoriz
294   //              i
295   //             [0]
296   
297   i = 0;
298   int ilow = 0;
299   int iup = nbhoriz - 1;
300   if (quad->isEdgeOut[3]) { ilow++; } else { if (quad->isEdgeOut[1]) iup--; }
301   
302   int jlow = 0;
303   int jup = nbvertic - 1;
304   if (quad->isEdgeOut[0]) { jlow++; } else { if (quad->isEdgeOut[2]) jup--; }
305   
306   // regular quadrangles
307   for (i = ilow; i < iup; i++) {
308     for (j = jlow; j < jup; j++) {
309       const SMDS_MeshNode *a, *b, *c, *d;
310       a = quad->uv_grid[j       * nbhoriz + i    ].node;
311       b = quad->uv_grid[j       * nbhoriz + i + 1].node;
312       c = quad->uv_grid[(j + 1) * nbhoriz + i + 1].node;
313       d = quad->uv_grid[(j + 1) * nbhoriz + i    ].node;
314       SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
315       if (face) {
316         meshDS->SetMeshElementOnShape(face, geomFaceID);
317       }
318     }
319   }
320
321   const vector<UVPtStruct>& uv_e0 = quad->side[0]->GetUVPtStruct(true,0);
322   const vector<UVPtStruct>& uv_e1 = quad->side[1]->GetUVPtStruct(false,1);
323   const vector<UVPtStruct>& uv_e2 = quad->side[2]->GetUVPtStruct(true,1);
324   const vector<UVPtStruct>& uv_e3 = quad->side[3]->GetUVPtStruct(false,0);
325
326   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
327     return error(COMPERR_BAD_INPUT_MESH);
328
329   double eps = Precision::Confusion();
330
331   // Boundary quadrangles
332   
333   if (quad->isEdgeOut[0]) {
334     // Down edge is out
335     // 
336     // |___|___|___|___|___|___|
337     // |   |   |   |   |   |   |
338     // |___|___|___|___|___|___|
339     // |   |   |   |   |   |   |
340     // |___|___|___|___|___|___| __ first row of the regular grid
341     // .  .  .  .  .  .  .  .  . __ down edge nodes
342     // 
343     // >->->->->->->->->->->->-> -- direction of processing
344       
345     int g = 0; // number of last processed node in the regular grid
346     
347     // number of last node of the down edge to be processed
348     int stop = nbdown - 1;
349     // if right edge is out, we will stop at a node, previous to the last one
350     if (quad->isEdgeOut[1]) stop--;
351     
352     // for each node of the down edge find nearest node
353     // in the first row of the regular grid and link them
354     for (i = 0; i < stop; i++) {
355       const SMDS_MeshNode *a, *b, *c, *d;
356       a = uv_e0[i].node;
357       b = uv_e0[i + 1].node;
358       gp_Pnt pb (b->X(), b->Y(), b->Z());
359       
360       // find node c in the regular grid, which will be linked with node b
361       int near = g;
362       if (i == stop - 1) {
363         // right bound reached, link with the rightmost node
364         near = iup;
365         c = quad->uv_grid[nbhoriz + iup].node;
366       }
367       else {
368         // find in the grid node c, nearest to the b
369         double mind = RealLast();
370         for (int k = g; k <= iup; k++) {
371           
372           const SMDS_MeshNode *nk;
373           if (k < ilow) // this can be, if left edge is out
374             nk = uv_e3[1].node; // get node from the left edge
375           else
376             nk = quad->uv_grid[nbhoriz + k].node; // get one of middle nodes
377
378           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
379           double dist = pb.Distance(pnk);
380           if (dist < mind - eps) {
381             c = nk;
382             near = k;
383             mind = dist;
384           } else {
385             break;
386           }
387         }
388       }
389
390       if (near == g) { // make triangle
391         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
392         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
393       }
394       else { // make quadrangle
395         if (near - 1 < ilow)
396           d = uv_e3[1].node;
397         else
398           d = quad->uv_grid[nbhoriz + near - 1].node;
399         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
400         
401         if (!myTrianglePreference){
402           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
403           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
404         }
405         else {
406           SplitQuad(meshDS, geomFaceID, a, b, c, d);
407         }
408
409         // if node d is not at position g - make additional triangles
410         if (near - 1 > g) {
411           for (int k = near - 1; k > g; k--) {
412             c = quad->uv_grid[nbhoriz + k].node;
413             if (k - 1 < ilow)
414               d = uv_e3[1].node;
415             else
416               d = quad->uv_grid[nbhoriz + k - 1].node;
417             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
418             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
419           }
420         }
421         g = near;
422       }
423     }
424   } else {
425     if (quad->isEdgeOut[2]) {
426       // Up edge is out
427       // 
428       // <-<-<-<-<-<-<-<-<-<-<-<-< -- direction of processing
429       // 
430       // .  .  .  .  .  .  .  .  . __ up edge nodes
431       //  ___ ___ ___ ___ ___ ___  __ first row of the regular grid
432       // |   |   |   |   |   |   |
433       // |___|___|___|___|___|___|
434       // |   |   |   |   |   |   |
435       // |___|___|___|___|___|___|
436       // |   |   |   |   |   |   |
437
438       int g = nbhoriz - 1; // last processed node in the regular grid
439
440       int stop = 0;
441       // if left edge is out, we will stop at a second node
442       if (quad->isEdgeOut[3]) stop++;
443
444       // for each node of the up edge find nearest node
445       // in the first row of the regular grid and link them
446       for (i = nbup - 1; i > stop; i--) {
447         const SMDS_MeshNode *a, *b, *c, *d;
448         a = uv_e2[i].node;
449         b = uv_e2[i - 1].node;
450         gp_Pnt pb (b->X(), b->Y(), b->Z());
451
452         // find node c in the grid, which will be linked with node b
453         int near = g;
454         if (i == stop + 1) { // left bound reached, link with the leftmost node
455           c = quad->uv_grid[nbhoriz*(nbvertic - 2) + ilow].node;
456           near = ilow;
457         } else {
458           // find node c in the grid, nearest to the b
459           double mind = RealLast();
460           for (int k = g; k >= ilow; k--) {
461             const SMDS_MeshNode *nk;
462             if (k > iup)
463               nk = uv_e1[nbright - 2].node;
464             else
465               nk = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
466             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
467             double dist = pb.Distance(pnk);
468             if (dist < mind - eps) {
469               c = nk;
470               near = k;
471               mind = dist;
472             } else {
473               break;
474             }
475           }
476         }
477
478         if (near == g) { // make triangle
479           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
480           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
481         }
482         else { // make quadrangle
483           if (near + 1 > iup)
484             d = uv_e1[nbright - 2].node;
485           else
486             d = quad->uv_grid[nbhoriz*(nbvertic - 2) + near + 1].node;
487           //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
488           if (!myTrianglePreference){
489             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
490             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
491           }
492           else {
493             SplitQuad(meshDS, geomFaceID, a, b, c, d);
494           }
495
496           if (near + 1 < g) { // if d not is at g - make additional triangles
497             for (int k = near + 1; k < g; k++) {
498               c = quad->uv_grid[nbhoriz*(nbvertic - 2) + k].node;
499               if (k + 1 > iup)
500                 d = uv_e1[nbright - 2].node;
501               else
502                 d = quad->uv_grid[nbhoriz*(nbvertic - 2) + k + 1].node;
503               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
504               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
505             }
506           }
507           g = near;
508         }
509       }
510     }
511   }
512
513   // right or left boundary quadrangles
514   if (quad->isEdgeOut[1]) {
515 //    MESSAGE("right edge is out");
516     int g = 0; // last processed node in the grid
517     int stop = nbright - 1;
518     if (quad->isEdgeOut[2]) stop--;
519     for (i = 0; i < stop; i++) {
520       const SMDS_MeshNode *a, *b, *c, *d;
521       a = uv_e1[i].node;
522       b = uv_e1[i + 1].node;
523       gp_Pnt pb (b->X(), b->Y(), b->Z());
524
525       // find node c in the grid, nearest to the b
526       int near = g;
527       if (i == stop - 1) { // up bondary reached
528         c = quad->uv_grid[nbhoriz*(jup + 1) - 2].node;
529         near = jup;
530       } else {
531         double mind = RealLast();
532         for (int k = g; k <= jup; k++) {
533           const SMDS_MeshNode *nk;
534           if (k < jlow)
535             nk = uv_e0[nbdown - 2].node;
536           else
537             nk = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
538           gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
539           double dist = pb.Distance(pnk);
540           if (dist < mind - eps) {
541             c = nk;
542             near = k;
543             mind = dist;
544           } else {
545             break;
546           }
547         }
548       }
549
550       if (near == g) { // make triangle
551         SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
552         if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
553       }
554       else { // make quadrangle
555         if (near - 1 < jlow)
556           d = uv_e0[nbdown - 2].node;
557         else
558           d = quad->uv_grid[nbhoriz*near - 2].node;
559         //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
560
561         if (!myTrianglePreference){
562           SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
563           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
564         }
565         else {
566           SplitQuad(meshDS, geomFaceID, a, b, c, d);
567         }
568
569         if (near - 1 > g) { // if d not is at g - make additional triangles
570           for (int k = near - 1; k > g; k--) {
571             c = quad->uv_grid[nbhoriz*(k + 1) - 2].node;
572             if (k - 1 < jlow)
573               d = uv_e0[nbdown - 2].node;
574             else
575               d = quad->uv_grid[nbhoriz*k - 2].node;
576             SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
577             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
578           }
579         }
580         g = near;
581       }
582     }
583   } else {
584     if (quad->isEdgeOut[3]) {
585 //      MESSAGE("left edge is out");
586       int g = nbvertic - 1; // last processed node in the grid
587       int stop = 0;
588       if (quad->isEdgeOut[0]) stop++;
589       for (i = nbleft - 1; i > stop; i--) {
590         const SMDS_MeshNode *a, *b, *c, *d;
591         a = uv_e3[i].node;
592         b = uv_e3[i - 1].node;
593         gp_Pnt pb (b->X(), b->Y(), b->Z());
594
595         // find node c in the grid, nearest to the b
596         int near = g;
597         if (i == stop + 1) { // down bondary reached
598           c = quad->uv_grid[nbhoriz*jlow + 1].node;
599           near = jlow;
600         } else {
601           double mind = RealLast();
602           for (int k = g; k >= jlow; k--) {
603             const SMDS_MeshNode *nk;
604             if (k > jup)
605               nk = uv_e2[1].node;
606             else
607               nk = quad->uv_grid[nbhoriz*k + 1].node;
608             gp_Pnt pnk (nk->X(), nk->Y(), nk->Z());
609             double dist = pb.Distance(pnk);
610             if (dist < mind - eps) {
611               c = nk;
612               near = k;
613               mind = dist;
614             } else {
615               break;
616             }
617           }
618         }
619
620         if (near == g) { // make triangle
621           SMDS_MeshFace* face = myHelper->AddFace(a, b, c);
622           if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
623         }
624         else { // make quadrangle
625           if (near + 1 > jup)
626             d = uv_e2[1].node;
627           else
628             d = quad->uv_grid[nbhoriz*(near + 1) + 1].node;
629           //SMDS_MeshFace* face = meshDS->AddFace(a, b, c, d);
630           if (!myTrianglePreference){
631             SMDS_MeshFace* face = myHelper->AddFace(a, b, c, d);
632             if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
633           }
634           else {
635             SplitQuad(meshDS, geomFaceID, a, b, c, d);
636           }
637
638           if (near + 1 < g) { // if d not is at g - make additional triangles
639             for (int k = near + 1; k < g; k++) {
640               c = quad->uv_grid[nbhoriz*k + 1].node;
641               if (k + 1 > jup)
642                 d = uv_e2[1].node;
643               else
644                 d = quad->uv_grid[nbhoriz*(k + 1) + 1].node;
645               SMDS_MeshFace* face = myHelper->AddFace(a, c, d);
646               if (face) meshDS->SetMeshElementOnShape(face, geomFaceID);
647             }
648           }
649           g = near;
650         }
651       }
652     }
653   }
654
655   if ( myNeedSmooth )
656     Smooth( quad );
657
658   bool isOk = true;
659   return isOk;
660 }
661
662
663 //=============================================================================
664 /*!
665  *  Evaluate
666  */
667 //=============================================================================
668
669 bool StdMeshers_Quadrangle_2D::Evaluate(SMESH_Mesh& aMesh,
670                                         const TopoDS_Shape& aShape,
671                                         MapShapeNbElems& aResMap)
672
673 {
674   aMesh.GetSubMesh(aShape);
675
676   std::vector<int> aNbNodes(4);
677   bool IsQuadratic = false;
678   if (!CheckNbEdgesForEvaluate(aMesh, aShape, aResMap, aNbNodes, IsQuadratic)) {
679     std::vector<int> aResVec(SMDSEntity_Last);
680     for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
681     SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
682     aResMap.insert(std::make_pair(sm,aResVec));
683     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
684     smError.reset(new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
685     return false;
686   }
687
688   if (myQuadranglePreference) {
689     int n1 = aNbNodes[0];
690     int n2 = aNbNodes[1];
691     int n3 = aNbNodes[2];
692     int n4 = aNbNodes[3];
693     int nfull = n1+n2+n3+n4;
694     int ntmp = nfull/2;
695     ntmp = ntmp*2;
696     if (nfull==ntmp && ((n1!=n3) || (n2!=n4))) {
697       // special path for using only quandrangle faces
698       return EvaluateQuadPref(aMesh, aShape, aNbNodes, aResMap, IsQuadratic);
699       //return true;
700     }
701   }
702
703   int nbdown  = aNbNodes[0];
704   int nbup    = aNbNodes[2];
705
706   int nbright = aNbNodes[1];
707   int nbleft  = aNbNodes[3];
708
709   int nbhoriz  = Min(nbdown, nbup);
710   int nbvertic = Min(nbright, nbleft);
711
712   int dh = Max(nbdown, nbup) - nbhoriz;
713   int dv = Max(nbright, nbleft) - nbvertic;
714
715   //int kdh = 0;
716   //if (dh>0) kdh = 1;
717   //int kdv = 0;
718   //if (dv>0) kdv = 1;
719
720   int nbNodes = (nbhoriz-2)*(nbvertic-2);
721   //int nbFaces3 = dh + dv + kdh*(nbvertic-1)*2 + kdv*(nbhoriz-1)*2;
722   int nbFaces3 = dh + dv;
723   //if (kdh==1 && kdv==1) nbFaces3 -= 2;
724   //if (dh>0 && dv>0) nbFaces3 -= 2;
725   //int nbFaces4 = (nbhoriz-1-kdh)*(nbvertic-1-kdv);
726   int nbFaces4 = (nbhoriz-1)*(nbvertic-1);
727
728   std::vector<int> aVec(SMDSEntity_Last);
729   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
730   if (IsQuadratic) {
731     aVec[SMDSEntity_Quad_Triangle] = nbFaces3;
732     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4;
733     int nbbndedges = nbdown + nbup + nbright + nbleft -4;
734     int nbintedges = (nbFaces4*4 + nbFaces3*3 - nbbndedges) / 2;
735     aVec[SMDSEntity_Node] = nbNodes + nbintedges;
736     if (aNbNodes.size()==5) {
737       aVec[SMDSEntity_Quad_Triangle] = nbFaces3 + aNbNodes[3] -1;
738       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces4 - aNbNodes[3] +1;
739     }
740   }
741   else {
742     aVec[SMDSEntity_Node] = nbNodes;
743     aVec[SMDSEntity_Triangle] = nbFaces3;
744     aVec[SMDSEntity_Quadrangle] = nbFaces4;
745     if (aNbNodes.size()==5) {
746       aVec[SMDSEntity_Triangle] = nbFaces3 + aNbNodes[3] - 1;
747       aVec[SMDSEntity_Quadrangle] = nbFaces4 - aNbNodes[3] + 1;
748     }
749   }
750   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
751   aResMap.insert(std::make_pair(sm,aVec));
752
753   return true;
754 }
755
756
757 //================================================================================
758 /*!
759  * \brief Return true if only two given edges meat at their common vertex
760  */
761 //================================================================================
762
763 static bool twoEdgesMeatAtVertex(const TopoDS_Edge& e1,
764                                  const TopoDS_Edge& e2,
765                                  SMESH_Mesh &       mesh)
766 {
767   TopoDS_Vertex v;
768   if (!TopExp::CommonVertex(e1, e2, v))
769     return false;
770   TopTools_ListIteratorOfListOfShape ancestIt(mesh.GetAncestors(v));
771   for (; ancestIt.More() ; ancestIt.Next())
772     if (ancestIt.Value().ShapeType() == TopAbs_EDGE)
773       if (!e1.IsSame(ancestIt.Value()) && !e2.IsSame(ancestIt.Value()))
774         return false;
775   return true;
776 }
777
778 //=============================================================================
779 /*!
780  *  
781  */
782 //=============================================================================
783
784 FaceQuadStruct* StdMeshers_Quadrangle_2D::CheckNbEdges(SMESH_Mesh &         aMesh,
785                                                        const TopoDS_Shape & aShape)
786   //throw(SALOME_Exception)
787 {
788   TopoDS_Face F = TopoDS::Face(aShape);
789   if ( F.Orientation() >= TopAbs_INTERNAL ) F.Orientation( TopAbs_FORWARD );
790   const bool ignoreMediumNodes = _quadraticMesh;
791
792   // verify 1 wire only, with 4 edges
793   TopoDS_Vertex V;
794   list< TopoDS_Edge > edges;
795   list< int > nbEdgesInWire;
796   int nbWire = SMESH_Block::GetOrderedEdges (F, V, edges, nbEdgesInWire);
797   if (nbWire != 1) {
798     error(COMPERR_BAD_SHAPE, TComm("Wrong number of wires: ") << nbWire);
799     return 0;
800   }
801   FaceQuadStruct* quad = new FaceQuadStruct;
802   quad->uv_grid = 0;
803   quad->side.reserve(nbEdgesInWire.front());
804   quad->face = F;
805
806   int nbSides = 0;
807   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
808   if (nbEdgesInWire.front() == 3) // exactly 3 edges
809   {
810     SMESH_Comment comment;
811     SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
812     if (myTriaVertexID == -1)
813     {
814       comment << "No Base vertex parameter provided for a trilateral geometrical face";
815     }
816     else
817     {
818       TopoDS_Vertex V = TopoDS::Vertex(meshDS->IndexToShape(myTriaVertexID));
819       if (!V.IsNull()) {
820         TopoDS_Edge E1,E2,E3;
821         for (; edgeIt != edges.end(); ++edgeIt) {
822           TopoDS_Edge E =  *edgeIt;
823           TopoDS_Vertex VF, VL;
824           TopExp::Vertices(E, VF, VL, true);
825           if (VF.IsSame(V))
826             E1 = E;
827           else if (VL.IsSame(V))
828             E3 = E;
829           else
830             E2 = E;
831         }
832         if (!E1.IsNull() && !E2.IsNull() && !E3.IsNull())
833         {
834           quad->side.push_back(new StdMeshers_FaceSide(F, E1, &aMesh, true,
835                                                        ignoreMediumNodes, myProxyMesh));
836           quad->side.push_back(new StdMeshers_FaceSide(F, E2, &aMesh, true,
837                                                        ignoreMediumNodes, myProxyMesh));
838           quad->side.push_back(new StdMeshers_FaceSide(F, E3, &aMesh, false,
839                                                        ignoreMediumNodes, myProxyMesh));
840           const vector<UVPtStruct>& UVPSleft  = quad->side[0]->GetUVPtStruct(true,0);
841           /*  vector<UVPtStruct>& UVPStop   = */quad->side[1]->GetUVPtStruct(false,1);
842           /*  vector<UVPtStruct>& UVPSright = */quad->side[2]->GetUVPtStruct(true,1);
843           const SMDS_MeshNode* aNode = UVPSleft[0].node;
844           gp_Pnt2d aPnt2d(UVPSleft[0].u, UVPSleft[0].v);
845           quad->side.push_back(new StdMeshers_FaceSide(aNode, aPnt2d, quad->side[1]));
846           return quad;
847         }
848       }
849       comment << "Invalid Base vertex parameter: " << myTriaVertexID << " is not among [";
850       TopTools_MapOfShape vMap;
851       for (TopExp_Explorer v(aShape, TopAbs_VERTEX); v.More(); v.Next())
852         if (vMap.Add(v.Current()))
853           comment << meshDS->ShapeToIndex(v.Current()) << (vMap.Extent()==3 ? "]" : ", ");
854     }
855     error(comment);
856     delete quad;
857     return quad = 0;
858   }
859   else if (nbEdgesInWire.front() == 4) // exactly 4 edges
860   {
861     for (; edgeIt != edges.end(); ++edgeIt, nbSides++)
862       quad->side.push_back(new StdMeshers_FaceSide(F, *edgeIt, &aMesh, nbSides < TOP_SIDE,
863                                                    ignoreMediumNodes, myProxyMesh));
864   }
865   else if (nbEdgesInWire.front() > 4) // more than 4 edges - try to unite some
866   {
867     list< TopoDS_Edge > sideEdges;
868     vector< int > degenSides;
869     while (!edges.empty()) {
870       sideEdges.clear();
871       sideEdges.splice(sideEdges.end(), edges, edges.begin()); // edges.front() -> sideEdges.end()
872       bool sameSide = true;
873       while (!edges.empty() && sameSide) {
874         sameSide = SMESH_Algo::IsContinuous(sideEdges.back(), edges.front());
875         if (sameSide)
876           sideEdges.splice(sideEdges.end(), edges, edges.begin());
877       }
878       if (nbSides == 0) { // go backward from the first edge
879         sameSide = true;
880         while (!edges.empty() && sameSide) {
881           sameSide = SMESH_Algo::IsContinuous(sideEdges.front(), edges.back());
882           if (sameSide)
883             sideEdges.splice(sideEdges.begin(), edges, --edges.end());
884         }
885       }
886       if ( sideEdges.size() == 1 && BRep_Tool::Degenerated( sideEdges.front() ))
887         degenSides.push_back( nbSides );
888
889       quad->side.push_back(new StdMeshers_FaceSide(F, sideEdges, &aMesh, nbSides < TOP_SIDE,
890                                                    ignoreMediumNodes, myProxyMesh));
891       ++nbSides;
892     }
893     if ( !degenSides.empty() && nbSides - degenSides.size() == 4 )
894     {
895       myNeedSmooth = true;
896       for ( unsigned i = TOP_SIDE; i < quad->side.size(); ++i )
897         quad->side[i]->Reverse();
898
899       for ( int i = degenSides.size()-1; i > -1; --i )
900       {
901         StdMeshers_FaceSide* degenSide = quad->side[ degenSides[ i ]];
902         delete degenSide;
903         quad->side.erase( quad->side.begin() + degenSides[ i ] );
904       }
905       for ( unsigned i = TOP_SIDE; i < quad->side.size(); ++i )
906         quad->side[i]->Reverse();
907
908       nbSides -= degenSides.size();
909     }
910     // issue 20222. Try to unite only edges shared by two same faces
911     if (nbSides < 4) {
912       // delete found sides
913       { FaceQuadStruct cleaner(*quad); }
914       quad->side.clear();
915       quad->side.reserve(nbEdgesInWire.front());
916       nbSides = 0;
917
918       SMESH_Block::GetOrderedEdges (F, V, edges, nbEdgesInWire);
919       while (!edges.empty()) {
920         sideEdges.clear();
921         sideEdges.splice(sideEdges.end(), edges, edges.begin());
922         bool sameSide = true;
923         while (!edges.empty() && sameSide) {
924           sameSide =
925             SMESH_Algo::IsContinuous(sideEdges.back(), edges.front()) &&
926             twoEdgesMeatAtVertex(sideEdges.back(), edges.front(), aMesh);
927           if (sameSide)
928             sideEdges.splice(sideEdges.end(), edges, edges.begin());
929         }
930         if (nbSides == 0) { // go backward from the first edge
931           sameSide = true;
932           while (!edges.empty() && sameSide) {
933             sameSide =
934               SMESH_Algo::IsContinuous(sideEdges.front(), edges.back()) &&
935               twoEdgesMeatAtVertex(sideEdges.front(), edges.back(), aMesh);
936             if (sameSide)
937               sideEdges.splice(sideEdges.begin(), edges, --edges.end());
938           }
939         }
940         quad->side.push_back(new StdMeshers_FaceSide(F, sideEdges, &aMesh,
941                                                      nbSides < TOP_SIDE,
942                                                      ignoreMediumNodes, myProxyMesh));
943         ++nbSides;
944       }
945     }
946   }
947   if (nbSides != 4) {
948 #ifdef _DEBUG_
949     MESSAGE ("StdMeshers_Quadrangle_2D. Edge IDs of " << nbSides << " sides:\n");
950     for (int i = 0; i < nbSides; ++i) {
951       MESSAGE (" (");
952       for (int e = 0; e < quad->side[i]->NbEdges(); ++e)
953         MESSAGE (myHelper->GetMeshDS()->ShapeToIndex(quad->side[i]->Edge(e)) << " ");
954       MESSAGE (")\n");
955     }
956     //cout << endl;
957 #endif
958     if (!nbSides)
959       nbSides = nbEdgesInWire.front();
960     error(COMPERR_BAD_SHAPE, TComm("Face must have 4 sides but not ") << nbSides);
961     delete quad;
962     quad = 0;
963   }
964
965   return quad;
966 }
967
968
969 //=============================================================================
970 /*!
971  *  
972  */
973 //=============================================================================
974
975 bool StdMeshers_Quadrangle_2D::CheckNbEdgesForEvaluate(SMESH_Mesh& aMesh,
976                                                        const TopoDS_Shape & aShape,
977                                                        MapShapeNbElems& aResMap,
978                                                        std::vector<int>& aNbNodes,
979                                                        bool& IsQuadratic)
980
981 {
982   const TopoDS_Face & F = TopoDS::Face(aShape);
983
984   // verify 1 wire only, with 4 edges
985   TopoDS_Vertex V;
986   list< TopoDS_Edge > edges;
987   list< int > nbEdgesInWire;
988   int nbWire = SMESH_Block::GetOrderedEdges (F, V, edges, nbEdgesInWire);
989   if (nbWire != 1) {
990     return false;
991   }
992
993   aNbNodes.resize(4);
994
995   int nbSides = 0;
996   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
997   SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
998   MapShapeNbElemsItr anIt = aResMap.find(sm);
999   if (anIt==aResMap.end()) {
1000     return false;
1001   }
1002   std::vector<int> aVec = (*anIt).second;
1003   IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
1004   if (nbEdgesInWire.front() == 3) { // exactly 3 edges
1005     if (myTriaVertexID>0) {
1006       SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1007       TopoDS_Vertex V = TopoDS::Vertex(meshDS->IndexToShape(myTriaVertexID));
1008       if (!V.IsNull()) {
1009         TopoDS_Edge E1,E2,E3;
1010         for (; edgeIt != edges.end(); ++edgeIt) {
1011           TopoDS_Edge E =  TopoDS::Edge(*edgeIt);
1012           TopoDS_Vertex VF, VL;
1013           TopExp::Vertices(E, VF, VL, true);
1014           if (VF.IsSame(V))
1015             E1 = E;
1016           else if (VL.IsSame(V))
1017             E3 = E;
1018           else
1019             E2 = E;
1020         }
1021         SMESH_subMesh * sm = aMesh.GetSubMesh(E1);
1022         MapShapeNbElemsItr anIt = aResMap.find(sm);
1023         if (anIt==aResMap.end()) return false;
1024         std::vector<int> aVec = (*anIt).second;
1025         if (IsQuadratic)
1026           aNbNodes[0] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1027         else
1028           aNbNodes[0] = aVec[SMDSEntity_Node] + 2;
1029         sm = aMesh.GetSubMesh(E2);
1030         anIt = aResMap.find(sm);
1031         if (anIt==aResMap.end()) return false;
1032         aVec = (*anIt).second;
1033         if (IsQuadratic)
1034           aNbNodes[1] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1035         else
1036           aNbNodes[1] = aVec[SMDSEntity_Node] + 2;
1037         sm = aMesh.GetSubMesh(E3);
1038         anIt = aResMap.find(sm);
1039         if (anIt==aResMap.end()) return false;
1040         aVec = (*anIt).second;
1041         if (IsQuadratic)
1042           aNbNodes[2] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1043         else
1044           aNbNodes[2] = aVec[SMDSEntity_Node] + 2;
1045         aNbNodes[3] = aNbNodes[1];
1046         aNbNodes.resize(5);
1047         nbSides = 4;
1048       }
1049     }
1050   }
1051   if (nbEdgesInWire.front() == 4) { // exactly 4 edges
1052     for (; edgeIt != edges.end(); edgeIt++) {
1053       SMESH_subMesh * sm = aMesh.GetSubMesh(*edgeIt);
1054       MapShapeNbElemsItr anIt = aResMap.find(sm);
1055       if (anIt==aResMap.end()) {
1056         return false;
1057       }
1058       std::vector<int> aVec = (*anIt).second;
1059       if (IsQuadratic)
1060         aNbNodes[nbSides] = (aVec[SMDSEntity_Node]-1)/2 + 2;
1061       else
1062         aNbNodes[nbSides] = aVec[SMDSEntity_Node] + 2;
1063       nbSides++;
1064     }
1065   }
1066   else if (nbEdgesInWire.front() > 4) { // more than 4 edges - try to unite some
1067     list< TopoDS_Edge > sideEdges;
1068     while (!edges.empty()) {
1069       sideEdges.clear();
1070       sideEdges.splice(sideEdges.end(), edges, edges.begin()); // edges.front() -> sideEdges.end()
1071       bool sameSide = true;
1072       while (!edges.empty() && sameSide) {
1073         sameSide = SMESH_Algo::IsContinuous(sideEdges.back(), edges.front());
1074         if (sameSide)
1075           sideEdges.splice(sideEdges.end(), edges, edges.begin());
1076       }
1077       if (nbSides == 0) { // go backward from the first edge
1078         sameSide = true;
1079         while (!edges.empty() && sameSide) {
1080           sameSide = SMESH_Algo::IsContinuous(sideEdges.front(), edges.back());
1081           if (sameSide)
1082             sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1083         }
1084       }
1085       list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1086       aNbNodes[nbSides] = 1;
1087       for (; ite!=sideEdges.end(); ite++) {
1088         SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1089         MapShapeNbElemsItr anIt = aResMap.find(sm);
1090         if (anIt==aResMap.end()) {
1091           return false;
1092         }
1093         std::vector<int> aVec = (*anIt).second;
1094         if (IsQuadratic)
1095           aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1096         else
1097           aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1098       }
1099       ++nbSides;
1100     }
1101     // issue 20222. Try to unite only edges shared by two same faces
1102     if (nbSides < 4) {
1103       nbSides = 0;
1104       SMESH_Block::GetOrderedEdges (F, V, edges, nbEdgesInWire);
1105       while (!edges.empty()) {
1106         sideEdges.clear();
1107         sideEdges.splice(sideEdges.end(), edges, edges.begin());
1108         bool sameSide = true;
1109         while (!edges.empty() && sameSide) {
1110           sameSide =
1111             SMESH_Algo::IsContinuous(sideEdges.back(), edges.front()) &&
1112             twoEdgesMeatAtVertex(sideEdges.back(), edges.front(), aMesh);
1113           if (sameSide)
1114             sideEdges.splice(sideEdges.end(), edges, edges.begin());
1115         }
1116         if (nbSides == 0) { // go backward from the first edge
1117           sameSide = true;
1118           while (!edges.empty() && sameSide) {
1119             sameSide =
1120               SMESH_Algo::IsContinuous(sideEdges.front(), edges.back()) &&
1121               twoEdgesMeatAtVertex(sideEdges.front(), edges.back(), aMesh);
1122             if (sameSide)
1123               sideEdges.splice(sideEdges.begin(), edges, --edges.end());
1124           }
1125         }
1126         list<TopoDS_Edge>::iterator ite = sideEdges.begin();
1127         aNbNodes[nbSides] = 1;
1128         for (; ite!=sideEdges.end(); ite++) {
1129           SMESH_subMesh * sm = aMesh.GetSubMesh(*ite);
1130           MapShapeNbElemsItr anIt = aResMap.find(sm);
1131           if (anIt==aResMap.end()) {
1132             return false;
1133           }
1134           std::vector<int> aVec = (*anIt).second;
1135           if (IsQuadratic)
1136             aNbNodes[nbSides] += (aVec[SMDSEntity_Node]-1)/2 + 1;
1137           else
1138             aNbNodes[nbSides] += aVec[SMDSEntity_Node] + 1;
1139         }
1140         ++nbSides;
1141       }
1142     }
1143   }
1144   if (nbSides != 4) {
1145     if (!nbSides)
1146       nbSides = nbEdgesInWire.front();
1147     error(COMPERR_BAD_SHAPE, TComm("Face must have 4 sides but not ") << nbSides);
1148     return false;
1149   }
1150
1151   return true;
1152 }
1153
1154
1155 //=============================================================================
1156 /*!
1157  *  CheckAnd2Dcompute
1158  */
1159 //=============================================================================
1160
1161 FaceQuadStruct *StdMeshers_Quadrangle_2D::CheckAnd2Dcompute
1162                            (SMESH_Mesh &         aMesh,
1163                             const TopoDS_Shape & aShape,
1164                             const bool           CreateQuadratic) //throw(SALOME_Exception)
1165 {
1166   _quadraticMesh = CreateQuadratic;
1167
1168   FaceQuadStruct *quad = CheckNbEdges(aMesh, aShape);
1169
1170   if (!quad) return 0;
1171
1172   // set normalized grid on unit square in parametric domain
1173   bool stat = SetNormalizedGrid(aMesh, aShape, quad);
1174   if (!stat) {
1175     if (quad) delete quad;
1176     quad = 0;
1177   }
1178
1179   return quad;
1180 }
1181
1182 //=============================================================================
1183 /*!
1184  *  
1185  */
1186 //=============================================================================
1187
1188 faceQuadStruct::~faceQuadStruct()
1189 {
1190   for (int i = 0; i < side.size(); i++) {
1191     if (side[i])     delete side[i];
1192   }
1193   if (uv_grid)       delete [] uv_grid;
1194 }
1195
1196 namespace {
1197   inline const vector<UVPtStruct>& GetUVPtStructIn(FaceQuadStruct* quad, int i, int nbSeg)
1198   {
1199     bool   isXConst   = (i == BOTTOM_SIDE || i == TOP_SIDE);
1200     double constValue = (i == BOTTOM_SIDE || i == LEFT_SIDE) ? 0 : 1;
1201     return
1202       quad->isEdgeOut[i] ?
1203       quad->side[i]->SimulateUVPtStruct(nbSeg,isXConst,constValue) :
1204       quad->side[i]->GetUVPtStruct(isXConst,constValue);
1205   }
1206   inline gp_UV CalcUV(double x, double y,
1207                       const gp_UV& a0,const gp_UV& a1,const gp_UV& a2,const gp_UV& a3,
1208                       const gp_UV& p0,const gp_UV& p1,const gp_UV& p2,const gp_UV& p3)
1209   {
1210     return
1211       ((1 - y) * p0 + x * p1 + y * p2 + (1 - x) * p3 ) -
1212       ((1 - x) * (1 - y) * a0 + x * (1 - y) * a1 + x * y * a2 + (1 - x) * y * a3);
1213   }
1214 }
1215
1216 //=============================================================================
1217 /*!
1218  *  
1219  */
1220 //=============================================================================
1221
1222 bool StdMeshers_Quadrangle_2D::SetNormalizedGrid (SMESH_Mesh & aMesh,
1223                                                   const TopoDS_Shape& aShape,
1224                                                   FaceQuadStruct* & quad) //throw (SALOME_Exception)
1225 {
1226   // Algorithme décrit dans "Génération automatique de maillages"
1227   // P.L. GEORGE, MASSON, Â§ 6.4.1 p. 84-85
1228   // traitement dans le domaine paramétrique 2d u,v
1229   // transport - projection sur le carré unité
1230
1231 //  MESSAGE("StdMeshers_Quadrangle_2D::SetNormalizedGrid");
1232 //  const TopoDS_Face& F = TopoDS::Face(aShape);
1233
1234   // 1 --- find orientation of the 4 edges, by test on extrema
1235
1236   //      max             min                    0     x1     1
1237   //     |<----north-2-------^                a3 -------------> a2
1238   //     |                   |                   ^1          1^
1239   //    west-3            east-1 =right          |            |
1240   //     |                   |         ==>       |            |
1241   //  y0 |                   | y1                |            |
1242   //     |                   |                   |0          0|
1243   //     v----south-0-------->                a0 -------------> a1
1244   //      min             max                    0     x0     1
1245   //             =down
1246   //
1247
1248   // 3 --- 2D normalized values on unit square [0..1][0..1]
1249
1250   int nbhoriz  = Min(quad->side[0]->NbPoints(), quad->side[2]->NbPoints());
1251   int nbvertic = Min(quad->side[1]->NbPoints(), quad->side[3]->NbPoints());
1252
1253   quad->isEdgeOut[0] = (quad->side[0]->NbPoints() > quad->side[2]->NbPoints());
1254   quad->isEdgeOut[1] = (quad->side[1]->NbPoints() > quad->side[3]->NbPoints());
1255   quad->isEdgeOut[2] = (quad->side[2]->NbPoints() > quad->side[0]->NbPoints());
1256   quad->isEdgeOut[3] = (quad->side[3]->NbPoints() > quad->side[1]->NbPoints());
1257
1258   UVPtStruct *uv_grid = quad->uv_grid = new UVPtStruct[nbvertic * nbhoriz];
1259
1260   const vector<UVPtStruct>& uv_e0 = GetUVPtStructIn(quad, 0, nbhoriz - 1);
1261   const vector<UVPtStruct>& uv_e1 = GetUVPtStructIn(quad, 1, nbvertic - 1);
1262   const vector<UVPtStruct>& uv_e2 = GetUVPtStructIn(quad, 2, nbhoriz - 1);
1263   const vector<UVPtStruct>& uv_e3 = GetUVPtStructIn(quad, 3, nbvertic - 1);
1264
1265   if (uv_e0.empty() || uv_e1.empty() || uv_e2.empty() || uv_e3.empty())
1266     //return error("Can't find nodes on sides");
1267     return error(COMPERR_BAD_INPUT_MESH);
1268
1269   if ( myNeedSmooth )
1270     UpdateDegenUV( quad );
1271
1272   // copy data of face boundary
1273   /*if (! quad->isEdgeOut[0])*/ {
1274     const int j = 0;
1275     for (int i = 0; i < nbhoriz; i++)       // down
1276       uv_grid[ j * nbhoriz + i ] = uv_e0[i];
1277   }
1278   /*if (! quad->isEdgeOut[1])*/ {
1279     const int i = nbhoriz - 1;
1280     for (int j = 0; j < nbvertic; j++)      // right
1281       uv_grid[ j * nbhoriz + i ] = uv_e1[j];
1282   }
1283   /*if (! quad->isEdgeOut[2])*/ {
1284     const int j = nbvertic - 1;
1285     for (int i = 0; i < nbhoriz; i++)       // up
1286       uv_grid[ j * nbhoriz + i ] = uv_e2[i];
1287   }
1288   /*if (! quad->isEdgeOut[3])*/ {
1289     int i = 0;
1290     for (int j = 0; j < nbvertic; j++)      // left
1291       uv_grid[ j * nbhoriz + i ] = uv_e3[j];
1292   }
1293
1294   // normalized 2d parameters on grid
1295   for (int i = 0; i < nbhoriz; i++) {
1296     for (int j = 0; j < nbvertic; j++) {
1297       int ij = j * nbhoriz + i;
1298       // --- droite i cste : x = x0 + y(x1-x0)
1299       double x0 = uv_e0[i].normParam;   // bas - sud
1300       double x1 = uv_e2[i].normParam;   // haut - nord
1301       // --- droite j cste : y = y0 + x(y1-y0)
1302       double y0 = uv_e3[j].normParam;   // gauche-ouest
1303       double y1 = uv_e1[j].normParam;   // droite - est
1304       // --- intersection : x=x0+(y0+x(y1-y0))(x1-x0)
1305       double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1306       double y = y0 + x * (y1 - y0);
1307       uv_grid[ij].x = x;
1308       uv_grid[ij].y = y;
1309       //MESSAGE("-xy-01 "<<x0<<" "<<x1<<" "<<y0<<" "<<y1);
1310       //MESSAGE("-xy-norm "<<i<<" "<<j<<" "<<x<<" "<<y);
1311     }
1312   }
1313
1314   // 4 --- projection on 2d domain (u,v)
1315   gp_UV a0 (uv_e0.front().u, uv_e0.front().v);
1316   gp_UV a1 (uv_e0.back().u,  uv_e0.back().v );
1317   gp_UV a2 (uv_e2.back().u,  uv_e2.back().v );
1318   gp_UV a3 (uv_e2.front().u, uv_e2.front().v);
1319
1320   for (int i = 0; i < nbhoriz; i++)
1321   {
1322     gp_UV p0( uv_e0[i].u, uv_e0[i].v );
1323     gp_UV p2( uv_e2[i].u, uv_e2[i].v );
1324     for (int j = 0; j < nbvertic; j++)
1325     {
1326       gp_UV p1( uv_e1[j].u, uv_e1[j].v );
1327       gp_UV p3( uv_e3[j].u, uv_e3[j].v );
1328
1329       int ij = j * nbhoriz + i;
1330       double x = uv_grid[ij].x;
1331       double y = uv_grid[ij].y;
1332
1333       gp_UV uv = CalcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1334
1335       uv_grid[ij].u = uv.X();
1336       uv_grid[ij].v = uv.Y();
1337     }
1338   }
1339   return true;
1340 }
1341
1342 //=======================================================================
1343 //function : ShiftQuad
1344 //purpose  : auxilary function for ComputeQuadPref
1345 //=======================================================================
1346
1347 static void ShiftQuad(FaceQuadStruct* quad, const int num, bool)
1348 {
1349   StdMeshers_FaceSide* side[4] = { quad->side[0], quad->side[1],
1350                                    quad->side[2], quad->side[3] };
1351   for (int i = BOTTOM_SIDE; i < NB_SIDES; ++i) {
1352     int id = (i + num) % NB_SIDES;
1353     bool wasForward = (i < TOP_SIDE);
1354     bool newForward = (id < TOP_SIDE);
1355     if (wasForward != newForward)
1356       side[ i ]->Reverse();
1357     quad->side[ id ] = side[ i ];
1358   }
1359 }
1360
1361 //=======================================================================
1362 //function : CalcUV
1363 //purpose  : auxilary function for ComputeQuadPref
1364 //=======================================================================
1365
1366 static gp_UV CalcUV(double x0, double x1, double y0, double y1,
1367                     FaceQuadStruct* quad,
1368                     const gp_UV& a0, const gp_UV& a1,
1369                     const gp_UV& a2, const gp_UV& a3)
1370 {
1371   // const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
1372   // const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
1373   // const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
1374   // const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
1375
1376   double x = (x0 + y0 * (x1 - x0)) / (1 - (y1 - y0) * (x1 - x0));
1377   double y = y0 + x * (y1 - y0);
1378
1379   gp_UV p0 = quad->side[BOTTOM_SIDE]->Value2d(x).XY();
1380   gp_UV p1 = quad->side[RIGHT_SIDE ]->Value2d(y).XY();
1381   gp_UV p2 = quad->side[TOP_SIDE   ]->Value2d(x).XY();
1382   gp_UV p3 = quad->side[LEFT_SIDE  ]->Value2d(y).XY();
1383
1384   gp_UV uv = CalcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1385
1386   return uv;
1387 }
1388
1389 //=======================================================================
1390 //function : CalcUV2
1391 //purpose  : auxilary function for ComputeQuadPref
1392 //=======================================================================
1393
1394 static gp_UV CalcUV2(double x, double y,
1395                      FaceQuadStruct* quad,
1396                      const gp_UV& a0, const gp_UV& a1,
1397                      const gp_UV& a2, const gp_UV& a3)
1398 {
1399   gp_UV p0 = quad->side[BOTTOM_SIDE]->Value2d(x).XY();
1400   gp_UV p1 = quad->side[RIGHT_SIDE ]->Value2d(y).XY();
1401   gp_UV p2 = quad->side[TOP_SIDE   ]->Value2d(x).XY();
1402   gp_UV p3 = quad->side[LEFT_SIDE  ]->Value2d(y).XY();
1403
1404   gp_UV uv = CalcUV(x,y, a0,a1,a2,a3, p0,p1,p2,p3);
1405
1406   return uv;
1407 }
1408
1409
1410 //=======================================================================
1411 /*!
1412  * Create only quandrangle faces
1413  */
1414 //=======================================================================
1415
1416 bool StdMeshers_Quadrangle_2D::ComputeQuadPref (SMESH_Mesh &        aMesh,
1417                                                 const TopoDS_Shape& aShape,
1418                                                 FaceQuadStruct*     quad)
1419 {
1420   // Auxilary key in order to keep old variant
1421   // of meshing after implementation new variant
1422   // for bug 0016220 from Mantis.
1423   bool OldVersion = false;
1424   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
1425     OldVersion = true;
1426
1427   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
1428   const TopoDS_Face& F = TopoDS::Face(aShape);
1429   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
1430   bool WisF = true;
1431   int i,j,geomFaceID = meshDS->ShapeToIndex(F);
1432
1433   int nb = quad->side[0]->NbPoints();
1434   int nr = quad->side[1]->NbPoints();
1435   int nt = quad->side[2]->NbPoints();
1436   int nl = quad->side[3]->NbPoints();
1437   int dh = abs(nb-nt);
1438   int dv = abs(nr-nl);
1439
1440   if (dh>=dv) {
1441     if (nt>nb) {
1442       // it is a base case => not shift quad but me be replacement is need
1443       ShiftQuad(quad,0,WisF);
1444     }
1445     else {
1446       // we have to shift quad on 2
1447       ShiftQuad(quad,2,WisF);
1448     }
1449   }
1450   else {
1451     if (nr>nl) {
1452       // we have to shift quad on 1
1453       ShiftQuad(quad,1,WisF);
1454     }
1455     else {
1456       // we have to shift quad on 3
1457       ShiftQuad(quad,3,WisF);
1458     }
1459   }
1460
1461   nb = quad->side[0]->NbPoints();
1462   nr = quad->side[1]->NbPoints();
1463   nt = quad->side[2]->NbPoints();
1464   nl = quad->side[3]->NbPoints();
1465   dh = abs(nb-nt);
1466   dv = abs(nr-nl);
1467   int nbh  = Max(nb,nt);
1468   int nbv = Max(nr,nl);
1469   int addh = 0;
1470   int addv = 0;
1471
1472   // ----------- Old version ---------------
1473   // orientation of face and 3 main domain for future faces
1474   //       0   top    1
1475   //      1------------1
1476   //       |   |  |   |
1477   //       |   |  |   |
1478   //       | L |  | R |
1479   //  left |   |  |   | rigth
1480   //       |  /    \  |
1481   //       | /  C   \ |
1482   //       |/        \|
1483   //      0------------0
1484   //       0  bottom  1
1485
1486   // ----------- New version ---------------
1487   // orientation of face and 3 main domain for future faces
1488   //       0   top    1
1489   //      1------------1
1490   //       |  |____|  |
1491   //       |  /    \  |
1492   //       | /  C   \ |
1493   //  left |/________\| rigth
1494   //       |          |
1495   //       |          |
1496   //       |          |
1497   //      0------------0
1498   //       0  bottom  1
1499
1500   if (dh>dv) {
1501     addv = (dh-dv)/2;
1502     nbv = nbv + addv;
1503   }
1504   else { // dv>=dh
1505     addh = (dv-dh)/2;
1506     nbh = nbh + addh;
1507   }
1508
1509   const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
1510   const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
1511   const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
1512   const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
1513
1514   if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
1515     return error(COMPERR_BAD_INPUT_MESH);
1516
1517   if ( myNeedSmooth )
1518     UpdateDegenUV( quad );
1519
1520   // arrays for normalized params
1521   //cout<<"Dump B:"<<endl;
1522   TColStd_SequenceOfReal npb, npr, npt, npl;
1523   for (i=0; i<nb; i++) {
1524     npb.Append(uv_eb[i].normParam);
1525     //cout<<"i="<<i<<" par="<<uv_eb[i].normParam<<" npar="<<uv_eb[i].normParam;
1526     //const SMDS_MeshNode* N = uv_eb[i].node;
1527     //cout<<" node("<<N->X()<<","<<N->Y()<<","<<N->Z()<<")"<<endl;
1528   }
1529   for (i=0; i<nr; i++) {
1530     npr.Append(uv_er[i].normParam);
1531   }
1532   for (i=0; i<nt; i++) {
1533     npt.Append(uv_et[i].normParam);
1534   }
1535   for (i=0; i<nl; i++) {
1536     npl.Append(uv_el[i].normParam);
1537   }
1538
1539   int dl,dr;
1540   if (OldVersion) {
1541     // add some params to right and left after the first param
1542     // insert to right
1543     dr = nbv - nr;
1544     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
1545     for (i=1; i<=dr; i++) {
1546       npr.InsertAfter(1,npr.Value(2)-dpr);
1547     }
1548     // insert to left
1549     dl = nbv - nl;
1550     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
1551     for (i=1; i<=dl; i++) {
1552       npl.InsertAfter(1,npl.Value(2)-dpr);
1553     }
1554   }
1555   //cout<<"npb:";
1556   //for (i=1; i<=npb.Length(); i++) {
1557   //  cout<<" "<<npb.Value(i);
1558   //}
1559   //cout<<endl;
1560   
1561   gp_XY a0(uv_eb.front().u, uv_eb.front().v);
1562   gp_XY a1(uv_eb.back().u,  uv_eb.back().v);
1563   gp_XY a2(uv_et.back().u,  uv_et.back().v);
1564   gp_XY a3(uv_et.front().u, uv_et.front().v);
1565   //cout<<" a0("<<a0.X()<<","<<a0.Y()<<")"<<" a1("<<a1.X()<<","<<a1.Y()<<")"
1566   //    <<" a2("<<a2.X()<<","<<a2.Y()<<")"<<" a3("<<a3.X()<<","<<a3.Y()<<")"<<endl;
1567
1568   int nnn = Min(nr,nl);
1569   // auxilary sequence of XY for creation nodes
1570   // in the bottom part of central domain
1571   // Length of UVL and UVR must be == nbv-nnn
1572   TColgp_SequenceOfXY UVL, UVR, UVT;
1573
1574   if (OldVersion) {
1575     // step1: create faces for left domain
1576     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
1577     // add left nodes
1578     for (j=1; j<=nl; j++)
1579       NodesL.SetValue(1,j,uv_el[j-1].node);
1580     if (dl>0) {
1581       // add top nodes
1582       for (i=1; i<=dl; i++) 
1583         NodesL.SetValue(i+1,nl,uv_et[i].node);
1584       // create and add needed nodes
1585       TColgp_SequenceOfXY UVtmp;
1586       for (i=1; i<=dl; i++) {
1587         double x0 = npt.Value(i+1);
1588         double x1 = x0;
1589         // diagonal node
1590         double y0 = npl.Value(i+1);
1591         double y1 = npr.Value(i+1);
1592         gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1593         gp_Pnt P = S->Value(UV.X(),UV.Y());
1594         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1595         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1596         NodesL.SetValue(i+1,1,N);
1597         if (UVL.Length()<nbv-nnn) UVL.Append(UV);
1598         // internal nodes
1599         for (j=2; j<nl; j++) {
1600           double y0 = npl.Value(dl+j);
1601           double y1 = npr.Value(dl+j);
1602           gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1603           gp_Pnt P = S->Value(UV.X(),UV.Y());
1604           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1605           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1606           NodesL.SetValue(i+1,j,N);
1607           if (i==dl) UVtmp.Append(UV);
1608         }
1609       }
1610       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn; i++) {
1611         UVL.Append(UVtmp.Value(i));
1612       }
1613       //cout<<"Dump NodesL:"<<endl;
1614       //for (i=1; i<=dl+1; i++) {
1615       //  cout<<"i="<<i;
1616       //  for (j=1; j<=nl; j++) {
1617       //    cout<<" ("<<NodesL.Value(i,j)->X()<<","<<NodesL.Value(i,j)->Y()<<","<<NodesL.Value(i,j)->Z()<<")";
1618       //  }
1619       //  cout<<endl;
1620       //}
1621       // create faces
1622       for (i=1; i<=dl; i++) {
1623         for (j=1; j<nl; j++) {
1624           if (WisF) {
1625             SMDS_MeshFace* F =
1626               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
1627                               NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
1628             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1629           }
1630           else {
1631             SMDS_MeshFace* F =
1632               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i,j+1),
1633                               NodesL.Value(i+1,j+1), NodesL.Value(i+1,j));
1634             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1635           }
1636         }
1637       }
1638     }
1639     else {
1640       // fill UVL using c2d
1641       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn; i++) {
1642         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
1643       }
1644     }
1645     
1646     // step2: create faces for right domain
1647     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
1648     // add right nodes
1649     for (j=1; j<=nr; j++) 
1650       NodesR.SetValue(1,j,uv_er[nr-j].node);
1651     if (dr>0) {
1652       // add top nodes
1653       for (i=1; i<=dr; i++) 
1654         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
1655       // create and add needed nodes
1656       TColgp_SequenceOfXY UVtmp;
1657       for (i=1; i<=dr; i++) {
1658         double x0 = npt.Value(nt-i);
1659         double x1 = x0;
1660         // diagonal node
1661         double y0 = npl.Value(i+1);
1662         double y1 = npr.Value(i+1);
1663         gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1664         gp_Pnt P = S->Value(UV.X(),UV.Y());
1665         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1666         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1667         NodesR.SetValue(i+1,nr,N);
1668         if (UVR.Length()<nbv-nnn) UVR.Append(UV);
1669         // internal nodes
1670         for (j=2; j<nr; j++) {
1671           double y0 = npl.Value(nbv-j+1);
1672           double y1 = npr.Value(nbv-j+1);
1673           gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1674           gp_Pnt P = S->Value(UV.X(),UV.Y());
1675           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1676           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1677           NodesR.SetValue(i+1,j,N);
1678           if (i==dr) UVtmp.Prepend(UV);
1679         }
1680       }
1681       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn; i++) {
1682         UVR.Append(UVtmp.Value(i));
1683       }
1684       // create faces
1685       for (i=1; i<=dr; i++) {
1686         for (j=1; j<nr; j++) {
1687           if (WisF) {
1688             SMDS_MeshFace* F =
1689               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
1690                               NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
1691             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1692           }
1693           else {
1694             SMDS_MeshFace* F =
1695               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i,j+1),
1696                               NodesR.Value(i+1,j+1), NodesR.Value(i+1,j));
1697             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1698           }
1699         }
1700       }
1701     }
1702     else {
1703       // fill UVR using c2d
1704       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn; i++) {
1705         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
1706       }
1707     }
1708     
1709     // step3: create faces for central domain
1710     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
1711     // add first line using NodesL
1712     for (i=1; i<=dl+1; i++)
1713       NodesC.SetValue(1,i,NodesL(i,1));
1714     for (i=2; i<=nl; i++)
1715       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
1716     // add last line using NodesR
1717     for (i=1; i<=dr+1; i++)
1718       NodesC.SetValue(nb,i,NodesR(i,nr));
1719     for (i=1; i<nr; i++)
1720       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
1721     // add top nodes (last columns)
1722     for (i=dl+2; i<nbh-dr; i++) 
1723       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
1724     // add bottom nodes (first columns)
1725     for (i=2; i<nb; i++)
1726       NodesC.SetValue(i,1,uv_eb[i-1].node);
1727     
1728     // create and add needed nodes
1729     // add linear layers
1730     for (i=2; i<nb; i++) {
1731       double x0 = npt.Value(dl+i);
1732       double x1 = x0;
1733       for (j=1; j<nnn; j++) {
1734         double y0 = npl.Value(nbv-nnn+j);
1735         double y1 = npr.Value(nbv-nnn+j);
1736         gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
1737         gp_Pnt P = S->Value(UV.X(),UV.Y());
1738         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1739         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1740         NodesC.SetValue(i,nbv-nnn+j,N);
1741         if ( j==1 )
1742           UVT.Append( UV );
1743       }
1744     }
1745     // add diagonal layers
1746     //cout<<"UVL.Length()="<<UVL.Length()<<" UVR.Length()="<<UVR.Length()<<endl;
1747     //cout<<"Dump UVL:"<<endl;
1748     //for (i=1; i<=UVL.Length(); i++) {
1749     //  cout<<" ("<<UVL.Value(i).X()<<","<<UVL.Value(i).Y()<<")";
1750     //}
1751     //cout<<endl;
1752     gp_UV A2 = UVR.Value(nbv-nnn);
1753     gp_UV A3 = UVL.Value(nbv-nnn);
1754     for (i=1; i<nbv-nnn; i++) {
1755       gp_UV p1 = UVR.Value(i);
1756       gp_UV p3 = UVL.Value(i);
1757       double y = i / double(nbv-nnn);
1758       for (j=2; j<nb; j++) {
1759         double x = npb.Value(j);
1760         gp_UV p0( uv_eb[j-1].u, uv_eb[j-1].v );
1761         gp_UV p2 = UVT.Value( j-1 );
1762         gp_UV UV = CalcUV(x, y, a0, a1, A2, A3, p0,p1,p2,p3 );
1763         gp_Pnt P = S->Value(UV.X(),UV.Y());
1764         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1765         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
1766         NodesC.SetValue(j,i+1,N);
1767       }
1768     }
1769     // create faces
1770     for (i=1; i<nb; i++) {
1771       for (j=1; j<nbv; j++) {
1772         if (WisF) {
1773           SMDS_MeshFace* F =
1774             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
1775                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
1776           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1777         }
1778         else {
1779           SMDS_MeshFace* F =
1780             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i,j+1),
1781                             NodesC.Value(i+1,j+1), NodesC.Value(i+1,j));
1782           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1783         }
1784       }
1785     }
1786   }
1787
1788   else { // New version (!OldVersion)
1789     // step1: create faces for bottom rectangle domain
1790     StdMeshers_Array2OfNode NodesBRD(1,nb,1,nnn-1);
1791     // fill UVL and UVR using c2d
1792     for (j=0; j<nb; j++) {
1793       NodesBRD.SetValue(j+1,1,uv_eb[j].node);
1794     }
1795     for (i=1; i<nnn-1; i++) {
1796       NodesBRD.SetValue(1,i+1,uv_el[i].node);
1797       NodesBRD.SetValue(nb,i+1,uv_er[i].node);
1798       for (j=2; j<nb; j++) {
1799         double x = npb.Value(j);
1800         double y = (1-x) * npl.Value(i+1) + x * npr.Value(i+1);
1801         gp_UV UV = CalcUV2(x, y, quad, a0, a1, a2, a3);
1802         gp_Pnt P = S->Value(UV.X(),UV.Y());
1803         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1804         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(),UV.Y());
1805         NodesBRD.SetValue(j,i+1,N);
1806       }
1807     }
1808     for (j=1; j<nnn-1; j++) {
1809       for (i=1; i<nb; i++) {
1810         if (WisF) {
1811           SMDS_MeshFace* F =
1812             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i+1,j),
1813                             NodesBRD.Value(i+1,j+1), NodesBRD.Value(i,j+1));
1814           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1815         }
1816         else {
1817           SMDS_MeshFace* F =
1818             myHelper->AddFace(NodesBRD.Value(i,j), NodesBRD.Value(i,j+1),
1819                             NodesBRD.Value(i+1,j+1), NodesBRD.Value(i+1,j));
1820           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1821         }
1822       }
1823     }
1824     int drl = abs(nr-nl);
1825     // create faces for region C
1826     StdMeshers_Array2OfNode NodesC(1,nb,1,drl+1+addv);
1827     // add nodes from previous region
1828     for (j=1; j<=nb; j++) {
1829       NodesC.SetValue(j,1,NodesBRD.Value(j,nnn-1));
1830     }
1831     if ((drl+addv) > 0) {
1832       int n1,n2;
1833       if (nr>nl) {
1834         n1 = 1;
1835         n2 = drl + 1;
1836         TColgp_SequenceOfXY UVtmp;
1837         double drparam = npr.Value(nr) - npr.Value(nnn-1);
1838         double dlparam = npl.Value(nnn) - npl.Value(nnn-1);
1839         double y0,y1;
1840         for (i=1; i<=drl; i++) {
1841           // add existed nodes from right edge
1842           NodesC.SetValue(nb,i+1,uv_er[nnn+i-2].node);
1843           //double dtparam = npt.Value(i+1);
1844           y1 = npr.Value(nnn+i-1); // param on right edge
1845           double dpar = (y1 - npr.Value(nnn-1))/drparam;
1846           y0 = npl.Value(nnn-1) + dpar*dlparam; // param on left edge
1847           double dy = y1 - y0;
1848           for (j=1; j<nb; j++) {
1849             double x = npt.Value(i+1) + npb.Value(j)*(1-npt.Value(i+1));
1850             double y = y0 + dy*x;
1851             gp_UV UV = CalcUV2(x, y, quad, a0, a1, a2, a3);
1852             gp_Pnt P = S->Value(UV.X(),UV.Y());
1853             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1854             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1855             NodesC.SetValue(j,i+1,N);
1856           }
1857         }
1858         double dy0 = (1-y0)/(addv+1);
1859         double dy1 = (1-y1)/(addv+1);
1860         for (i=1; i<=addv; i++) {
1861           double yy0 = y0 + dy0*i;
1862           double yy1 = y1 + dy1*i;
1863           double dyy = yy1 - yy0;
1864           for (j=1; j<=nb; j++) {
1865             double x = npt.Value(i+1+drl) + 
1866               npb.Value(j) * (npt.Value(nt-i) - npt.Value(i+1+drl));
1867             double y = yy0 + dyy*x;
1868             gp_UV UV = CalcUV2(x, y, quad, a0, a1, a2, a3);
1869             gp_Pnt P = S->Value(UV.X(),UV.Y());
1870             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1871             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1872             NodesC.SetValue(j,i+drl+1,N);
1873           }
1874         }
1875       }
1876       else { // nr<nl
1877         n2 = 1;
1878         n1 = drl + 1;
1879         TColgp_SequenceOfXY UVtmp;
1880         double dlparam = npl.Value(nl) - npl.Value(nnn-1);
1881         double drparam = npr.Value(nnn) - npr.Value(nnn-1);
1882         double y0 = npl.Value(nnn-1);
1883         double y1 = npr.Value(nnn-1);
1884         for (i=1; i<=drl; i++) {
1885           // add existed nodes from right edge
1886           NodesC.SetValue(1,i+1,uv_el[nnn+i-2].node);
1887           y0 = npl.Value(nnn+i-1); // param on left edge
1888           double dpar = (y0 - npl.Value(nnn-1))/dlparam;
1889           y1 = npr.Value(nnn-1) + dpar*drparam; // param on right edge
1890           double dy = y1 - y0;
1891           for (j=2; j<=nb; j++) {
1892             double x = npb.Value(j)*npt.Value(nt-i);
1893             double y = y0 + dy*x;
1894             gp_UV UV = CalcUV2(x, y, quad, a0, a1, a2, a3);
1895             gp_Pnt P = S->Value(UV.X(),UV.Y());
1896             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1897             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1898             NodesC.SetValue(j,i+1,N);
1899           }
1900         }
1901         double dy0 = (1-y0)/(addv+1);
1902         double dy1 = (1-y1)/(addv+1);
1903         for (i=1; i<=addv; i++) {
1904           double yy0 = y0 + dy0*i;
1905           double yy1 = y1 + dy1*i;
1906           double dyy = yy1 - yy0;
1907           for (j=1; j<=nb; j++) {
1908             double x = npt.Value(i+1) + 
1909               npb.Value(j) * (npt.Value(nt-i-drl) - npt.Value(i+1));
1910             double y = yy0 + dyy*x;
1911             gp_UV UV = CalcUV2(x, y, quad, a0, a1, a2, a3);
1912             gp_Pnt P = S->Value(UV.X(),UV.Y());
1913             SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
1914             meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
1915             NodesC.SetValue(j,i+drl+1,N);
1916           }
1917         }
1918       }
1919       // create faces
1920       for (j=1; j<=drl+addv; j++) {
1921         for (i=1; i<nb; i++) {
1922           if (WisF) {
1923             SMDS_MeshFace* F =
1924               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
1925                               NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
1926             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1927           }
1928           else {
1929             SMDS_MeshFace* F =
1930               myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i,j+1),
1931                               NodesC.Value(i+1,j+1), NodesC.Value(i+1,j));
1932             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1933           }
1934         }
1935       } // end nr<nl
1936
1937       StdMeshers_Array2OfNode NodesLast(1,nt,1,2);
1938       for (i=1; i<=nt; i++) {
1939         NodesLast.SetValue(i,2,uv_et[i-1].node);
1940       }
1941       int nnn=0;
1942       for (i=n1; i<drl+addv+1; i++) {
1943         nnn++;
1944         NodesLast.SetValue(nnn,1,NodesC.Value(1,i));
1945       }
1946       for (i=1; i<=nb; i++) {
1947         nnn++;
1948         NodesLast.SetValue(nnn,1,NodesC.Value(i,drl+addv+1));
1949       }
1950       for (i=drl+addv; i>=n2; i--) {
1951         nnn++;
1952         NodesLast.SetValue(nnn,1,NodesC.Value(nb,i));
1953       }
1954       for (i=1; i<nt; i++) {
1955         if (WisF) {
1956           SMDS_MeshFace* F =
1957             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i+1,1),
1958                             NodesLast.Value(i+1,2), NodesLast.Value(i,2));
1959           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1960         }
1961         else {
1962           SMDS_MeshFace* F =
1963             myHelper->AddFace(NodesLast.Value(i,1), NodesLast.Value(i,2),
1964                             NodesLast.Value(i+1,2), NodesLast.Value(i+1,2));
1965           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
1966         }
1967       }
1968     } // if ((drl+addv) > 0)
1969
1970   } // end new version implementation
1971
1972   bool isOk = true;
1973   return isOk;
1974 }
1975
1976
1977 //=======================================================================
1978 /*!
1979  * Evaluate only quandrangle faces
1980  */
1981 //=======================================================================
1982
1983 bool StdMeshers_Quadrangle_2D::EvaluateQuadPref(SMESH_Mesh &        aMesh,
1984                                                 const TopoDS_Shape& aShape,
1985                                                 std::vector<int>& aNbNodes,
1986                                                 MapShapeNbElems& aResMap,
1987                                                 bool IsQuadratic)
1988 {
1989   // Auxilary key in order to keep old variant
1990   // of meshing after implementation new variant
1991   // for bug 0016220 from Mantis.
1992   bool OldVersion = false;
1993   if (myQuadType == QUAD_QUADRANGLE_PREF_REVERSED)
1994     OldVersion = true;
1995
1996   const TopoDS_Face& F = TopoDS::Face(aShape);
1997   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
1998
1999   int nb = aNbNodes[0];
2000   int nr = aNbNodes[1];
2001   int nt = aNbNodes[2];
2002   int nl = aNbNodes[3];
2003   int dh = abs(nb-nt);
2004   int dv = abs(nr-nl);
2005
2006   if (dh>=dv) {
2007     if (nt>nb) {
2008       // it is a base case => not shift 
2009     }
2010     else {
2011       // we have to shift on 2
2012       nb = aNbNodes[2];
2013       nr = aNbNodes[3];
2014       nt = aNbNodes[0];
2015       nl = aNbNodes[1];
2016     }
2017   }
2018   else {
2019     if (nr>nl) {
2020       // we have to shift quad on 1
2021       nb = aNbNodes[3];
2022       nr = aNbNodes[0];
2023       nt = aNbNodes[1];
2024       nl = aNbNodes[2];
2025     }
2026     else {
2027       // we have to shift quad on 3
2028       nb = aNbNodes[1];
2029       nr = aNbNodes[2];
2030       nt = aNbNodes[3];
2031       nl = aNbNodes[0];
2032     }
2033   }
2034
2035   dh = abs(nb-nt);
2036   dv = abs(nr-nl);
2037   int nbh  = Max(nb,nt);
2038   int nbv = Max(nr,nl);
2039   int addh = 0;
2040   int addv = 0;
2041
2042   if (dh>dv) {
2043     addv = (dh-dv)/2;
2044     nbv = nbv + addv;
2045   }
2046   else { // dv>=dh
2047     addh = (dv-dh)/2;
2048     nbh = nbh + addh;
2049   }
2050
2051   int dl,dr;
2052   if (OldVersion) {
2053     // add some params to right and left after the first param
2054     // insert to right
2055     dr = nbv - nr;
2056     // insert to left
2057     dl = nbv - nl;
2058   }
2059   
2060   int nnn = Min(nr,nl);
2061
2062   int nbNodes = 0;
2063   int nbFaces = 0;
2064   if (OldVersion) {
2065     // step1: create faces for left domain
2066     if (dl>0) {
2067       nbNodes += dl*(nl-1);
2068       nbFaces += dl*(nl-1);
2069     }
2070     // step2: create faces for right domain
2071     if (dr>0) {
2072       nbNodes += dr*(nr-1);
2073       nbFaces += dr*(nr-1);
2074     }
2075     // step3: create faces for central domain
2076     nbNodes += (nb-2)*(nnn-1) + (nbv-nnn-1)*(nb-2);
2077     nbFaces += (nb-1)*(nbv-1);
2078   }
2079   else { // New version (!OldVersion)
2080     nbNodes += (nnn-2)*(nb-2);
2081     nbFaces += (nnn-2)*(nb-1);
2082     int drl = abs(nr-nl);
2083     nbNodes += drl*(nb-1) + addv*nb;
2084     nbFaces += (drl+addv)*(nb-1) + (nt-1);
2085   } // end new version implementation
2086
2087   std::vector<int> aVec(SMDSEntity_Last);
2088   for (int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
2089   if (IsQuadratic) {
2090     aVec[SMDSEntity_Quad_Quadrangle] = nbFaces;
2091     aVec[SMDSEntity_Node] = nbNodes + nbFaces*4;
2092     if (aNbNodes.size()==5) {
2093       aVec[SMDSEntity_Quad_Triangle] = aNbNodes[3] - 1;
2094       aVec[SMDSEntity_Quad_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2095     }
2096   }
2097   else {
2098     aVec[SMDSEntity_Node] = nbNodes;
2099     aVec[SMDSEntity_Quadrangle] = nbFaces;
2100     if (aNbNodes.size()==5) {
2101       aVec[SMDSEntity_Triangle] = aNbNodes[3] - 1;
2102       aVec[SMDSEntity_Quadrangle] = nbFaces - aNbNodes[3] + 1;
2103     }
2104   }
2105   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
2106   aResMap.insert(std::make_pair(sm,aVec));
2107
2108   return true;
2109 }
2110
2111
2112 //=============================================================================
2113 /*! Split quadrangle in to 2 triangles by smallest diagonal
2114  *   
2115  */
2116 //=============================================================================
2117 void StdMeshers_Quadrangle_2D::SplitQuad(SMESHDS_Mesh *theMeshDS,
2118                                          int theFaceID,
2119                                          const SMDS_MeshNode* theNode1,
2120                                          const SMDS_MeshNode* theNode2,
2121                                          const SMDS_MeshNode* theNode3,
2122                                          const SMDS_MeshNode* theNode4)
2123 {
2124   gp_Pnt a(theNode1->X(),theNode1->Y(),theNode1->Z());
2125   gp_Pnt b(theNode2->X(),theNode2->Y(),theNode2->Z());
2126   gp_Pnt c(theNode3->X(),theNode3->Y(),theNode3->Z());
2127   gp_Pnt d(theNode4->X(),theNode4->Y(),theNode4->Z());
2128   SMDS_MeshFace* face;
2129   if (a.Distance(c) > b.Distance(d)){
2130     face = myHelper->AddFace(theNode2, theNode4 , theNode1);
2131     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2132     face = myHelper->AddFace(theNode2, theNode3, theNode4);
2133     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2134
2135   }
2136   else{
2137     face = myHelper->AddFace(theNode1, theNode2 ,theNode3);
2138     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2139     face = myHelper->AddFace(theNode1, theNode3, theNode4);
2140     if (face) theMeshDS->SetMeshElementOnShape(face, theFaceID);
2141   }
2142 }
2143
2144 namespace
2145 {
2146   enum uvPos { UV_A0, UV_A1, UV_A2, UV_A3, UV_B, UV_R, UV_T, UV_L, UV_SIZE };
2147
2148   inline  SMDS_MeshNode* makeNode( UVPtStruct &         uvPt,
2149                                    const double         y,
2150                                    FaceQuadStruct*      quad,
2151                                    const gp_UV*         UVs,
2152                                    SMESH_MesherHelper*  helper,
2153                                    Handle(Geom_Surface) S)
2154   {
2155     const vector<UVPtStruct>& uv_eb = quad->side[BOTTOM_SIDE]->GetUVPtStruct();
2156     const vector<UVPtStruct>& uv_et = quad->side[TOP_SIDE   ]->GetUVPtStruct();
2157     double rBot = ( uv_eb.size() - 1 ) * uvPt.normParam;
2158     double rTop = ( uv_et.size() - 1 ) * uvPt.normParam;
2159     int iBot = int( rBot );
2160     int iTop = int( rTop );
2161     double xBot = uv_eb[ iBot ].normParam + ( rBot - iBot ) * ( uv_eb[ iBot+1 ].normParam - uv_eb[ iBot ].normParam );
2162     double xTop = uv_et[ iTop ].normParam + ( rTop - iTop ) * ( uv_et[ iTop+1 ].normParam - uv_et[ iTop ].normParam );
2163     double x = xBot + y * ( xTop - xBot );
2164     
2165     gp_UV uv = CalcUV(/*x,y=*/x, y,
2166                       /*a0,...=*/UVs[UV_A0], UVs[UV_A1], UVs[UV_A2], UVs[UV_A3],
2167                       /*p0=*/quad->side[BOTTOM_SIDE]->Value2d( x ).XY(),
2168                       /*p1=*/UVs[ UV_R ],
2169                       /*p2=*/quad->side[TOP_SIDE   ]->Value2d( x ).XY(),
2170                       /*p3=*/UVs[ UV_L ]);
2171     gp_Pnt P = S->Value( uv.X(), uv.Y() );
2172     uvPt.u = uv.X();
2173     uvPt.v = uv.Y();
2174     return helper->AddNode(P.X(), P.Y(), P.Z(), 0, uv.X(), uv.Y() );
2175   }
2176
2177   void reduce42( const vector<UVPtStruct>& curr_base,
2178                  vector<UVPtStruct>&       next_base,
2179                  const int                 j,
2180                  int &                     next_base_len,
2181                  FaceQuadStruct*           quad,
2182                  gp_UV*                    UVs,
2183                  const double              y,
2184                  SMESH_MesherHelper*       helper,
2185                  Handle(Geom_Surface)&     S)
2186   {
2187     // add one "HH": nodes a,b,c,d,e and faces 1,2,3,4,5,6
2188     //
2189     //  .-----a-----b i + 1
2190     //  |\ 5  | 6  /|
2191     //  | \   |   / |
2192     //  |  c--d--e  |
2193     //  |1 |2 |3 |4 |
2194     //  |  |  |  |  |
2195     //  .--.--.--.--. i
2196     //
2197     //  j     j+2   j+4
2198
2199     // a (i + 1, j + 2)
2200     const SMDS_MeshNode*& Na = next_base[ ++next_base_len ].node;
2201     if ( !Na )
2202       Na = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2203
2204     // b (i + 1, j + 4)
2205     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2206     if ( !Nb )
2207       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2208
2209     // c
2210     double u = (curr_base[j + 2].u + next_base[next_base_len - 2].u) / 2.0;
2211     double v = (curr_base[j + 2].v + next_base[next_base_len - 2].v) / 2.0;
2212     gp_Pnt P = S->Value(u,v);
2213     SMDS_MeshNode* Nc = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2214
2215     // d
2216     u = (curr_base[j + 2].u + next_base[next_base_len - 1].u) / 2.0;
2217     v = (curr_base[j + 2].v + next_base[next_base_len - 1].v) / 2.0;
2218     P = S->Value(u,v);
2219     SMDS_MeshNode* Nd = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2220
2221     // e
2222     u = (curr_base[j + 2].u + next_base[next_base_len].u) / 2.0;
2223     v = (curr_base[j + 2].v + next_base[next_base_len].v) / 2.0;
2224     P = S->Value(u,v);
2225     SMDS_MeshNode* Ne = helper->AddNode(P.X(), P.Y(), P.Z(), 0, u, v);
2226
2227     // Faces
2228     helper->AddFace(curr_base[j + 0].node,
2229                     curr_base[j + 1].node, Nc,
2230                     next_base[next_base_len - 2].node);
2231
2232     helper->AddFace(curr_base[j + 1].node,
2233                     curr_base[j + 2].node, Nd, Nc);
2234
2235     helper->AddFace(curr_base[j + 2].node,
2236                     curr_base[j + 3].node, Ne, Nd);
2237
2238     helper->AddFace(curr_base[j + 3].node,
2239                     curr_base[j + 4].node, Nb, Ne);
2240
2241     helper->AddFace(Nc, Nd, Na, next_base[next_base_len - 2].node);
2242
2243     helper->AddFace(Nd, Ne, Nb, Na);
2244   }
2245
2246   void reduce31( const vector<UVPtStruct>& curr_base,
2247                  vector<UVPtStruct>&       next_base,
2248                  const int                 j,
2249                  int &                     next_base_len,
2250                  FaceQuadStruct*           quad,
2251                  gp_UV*                    UVs,
2252                  const double              y,
2253                  SMESH_MesherHelper*       helper,
2254                  Handle(Geom_Surface)&     S)
2255   {
2256     // add one "H": nodes b,c,e and faces 1,2,4,5
2257     //
2258     //  .---------b i + 1
2259     //  |\   5   /|
2260     //  | \     / |
2261     //  |  c---e  |
2262     //  |1 |2  |4 |
2263     //  |  |   |  |
2264     //  .--.---.--. i
2265     //
2266     //  j j+1 j+2 j+3
2267
2268     // b (i + 1, j + 3)
2269     const SMDS_MeshNode*& Nb = next_base[ ++next_base_len ].node;
2270     if ( !Nb )
2271       Nb = makeNode( next_base[ next_base_len ], y, quad, UVs, helper, S );
2272
2273     // c and e
2274     double u1 = (curr_base[ j   ].u + next_base[ next_base_len-1 ].u ) / 2.0;
2275     double u2 = (curr_base[ j+3 ].u + next_base[ next_base_len   ].u ) / 2.0;
2276     double u3 = (u2 - u1) / 3.0;
2277     //
2278     double v1 = (curr_base[ j   ].v + next_base[ next_base_len-1 ].v ) / 2.0;
2279     double v2 = (curr_base[ j+3 ].v + next_base[ next_base_len   ].v ) / 2.0;
2280     double v3 = (v2 - v1) / 3.0;
2281     // c
2282     double u = u1 + u3;
2283     double v = v1 + v3;
2284     gp_Pnt P = S->Value(u,v);
2285     SMDS_MeshNode* Nc = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2286     // e
2287     u = u1 + u3 + u3;
2288     v = v1 + v3 + v3;
2289     P = S->Value(u,v);
2290     SMDS_MeshNode* Ne = helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
2291
2292     // Faces
2293     // 1
2294     helper->AddFace( curr_base[ j + 0 ].node,
2295                      curr_base[ j + 1 ].node,
2296                      Nc,
2297                      next_base[ next_base_len - 1 ].node);
2298     // 2
2299     helper->AddFace( curr_base[ j + 1 ].node,
2300                      curr_base[ j + 2 ].node, Ne, Nc);
2301     // 4
2302     helper->AddFace( curr_base[ j + 2 ].node,
2303                      curr_base[ j + 3 ].node, Nb, Ne);
2304     // 5
2305     helper->AddFace(Nc, Ne, Nb,
2306                     next_base[ next_base_len - 1 ].node);
2307   }
2308
2309   typedef void (* PReduceFunction) ( const vector<UVPtStruct>& curr_base,
2310                                      vector<UVPtStruct>&       next_base,
2311                                      const int                 j,
2312                                      int &                     next_base_len,
2313                                      FaceQuadStruct*           quad,
2314                                      gp_UV*                    UVs,
2315                                      const double              y,
2316                                      SMESH_MesherHelper*       helper,
2317                                      Handle(Geom_Surface)&     S);
2318
2319 } // namespace
2320
2321 //=======================================================================
2322 /*!
2323  *  Implementation of Reduced algorithm (meshing with quadrangles only)
2324  */
2325 //=======================================================================
2326 bool StdMeshers_Quadrangle_2D::ComputeReduced (SMESH_Mesh &        aMesh,
2327                                                const TopoDS_Shape& aShape,
2328                                                FaceQuadStruct*     quad)
2329 {
2330   SMESHDS_Mesh * meshDS = aMesh.GetMeshDS();
2331   const TopoDS_Face& F = TopoDS::Face(aShape);
2332   Handle(Geom_Surface) S = BRep_Tool::Surface(F);
2333   int i,j,geomFaceID = meshDS->ShapeToIndex(F);
2334
2335   int nb = quad->side[0]->NbPoints();
2336   int nr = quad->side[1]->NbPoints();
2337   int nt = quad->side[2]->NbPoints();
2338   int nl = quad->side[3]->NbPoints();
2339
2340   //  Simple Reduce 10->8->6->4 (3 steps)     Multiple Reduce 10->4 (1 step)
2341   //
2342   //  .-----.-----.-----.-----.               .-----.-----.-----.-----.
2343   //  |    / \    |    / \    |               |    / \    |    / \    |
2344   //  |   /    .--.--.    \   |               |    / \    |    / \    |
2345   //  |   /   /   |   \   \   |               |   /  .----.----.  \   |
2346   //  .---.---.---.---.---.---.               |   / / \   |   / \ \   |
2347   //  |   /  / \  |  / \  \   |               |   / / \   |   / \ \   |
2348   //  |  /  /   .-.-.   \  \  |               |  / /  .---.---.  \ \  |
2349   //  |  /  /  /  |  \  \  \  |               |  / / / \  |  / \ \ \  |
2350   //  .--.--.--.--.--.--.--.--.               |  / / /  \ | /  \ \ \  |
2351   //  |  / /  / \ | / \  \ \  |               | / / /   .-.-.   \ \ \ |
2352   //  | / /  /  .-.-.  \  \ \ |               | / / /  /  |  \  \ \ \ |
2353   //  | / / /  /  |  \  \ \ \ |               | / / /  /  |  \  \ \ \ |
2354   //  .-.-.-.--.--.--.--.-.-.-.               .-.-.-.--.--.--.--.-.-.-.
2355
2356   bool MultipleReduce = false;
2357   {
2358     int nb1 = nb;
2359     int nr1 = nr;
2360     int nt1 = nt;
2361
2362     if (nr == nl) {
2363       if (nb < nt) {
2364         nt1 = nb;
2365         nb1 = nt;
2366       }
2367     }
2368     else if (nb == nt) {
2369       nr1 = nb; // and == nt
2370       if (nl < nr) {
2371         nt1 = nl;
2372         nb1 = nr;
2373       }
2374       else {
2375         nt1 = nr;
2376         nb1 = nl;
2377       }
2378     }
2379     else {
2380       return false;
2381     }
2382
2383     // number of rows and columns
2384     int nrows = nr1 - 1;
2385     int ncol_top = nt1 - 1;
2386     int ncol_bot = nb1 - 1;
2387     // number of rows needed to reduce ncol_bot to ncol_top using simple 3->1 "tree" (see below)
2388     int nrows_tree31 = int( log( (double)(ncol_bot / ncol_top) ) / log((double) 3 )); // = log x base 3
2389     if ( nrows < nrows_tree31 )
2390       MultipleReduce = true;
2391   }
2392
2393   if (MultipleReduce) { // == ComputeQuadPref QUAD_QUADRANGLE_PREF_REVERSED
2394     //==================================================
2395     int dh = abs(nb-nt);
2396     int dv = abs(nr-nl);
2397
2398     if (dh >= dv) {
2399       if (nt > nb) {
2400         // it is a base case => not shift quad but may be replacement is need
2401         ShiftQuad(quad,0,true);
2402       }
2403       else {
2404         // we have to shift quad on 2
2405         ShiftQuad(quad,2,true);
2406       }
2407     }
2408     else {
2409       if (nr > nl) {
2410         // we have to shift quad on 1
2411         ShiftQuad(quad,1,true);
2412       }
2413       else {
2414         // we have to shift quad on 3
2415         ShiftQuad(quad,3,true);
2416       }
2417     }
2418
2419     nb = quad->side[0]->NbPoints();
2420     nr = quad->side[1]->NbPoints();
2421     nt = quad->side[2]->NbPoints();
2422     nl = quad->side[3]->NbPoints();
2423     dh = abs(nb-nt);
2424     dv = abs(nr-nl);
2425     int nbh = Max(nb,nt);
2426     int nbv = Max(nr,nl);
2427     int addh = 0;
2428     int addv = 0;
2429
2430     if (dh>dv) {
2431       addv = (dh-dv)/2;
2432       nbv = nbv + addv;
2433     }
2434     else { // dv>=dh
2435       addh = (dv-dh)/2;
2436       nbh = nbh + addh;
2437     }
2438
2439     const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
2440     const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
2441     const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
2442     const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
2443
2444     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2445       return error(COMPERR_BAD_INPUT_MESH);
2446
2447     if ( myNeedSmooth )
2448       UpdateDegenUV( quad );
2449
2450     // arrays for normalized params
2451     TColStd_SequenceOfReal npb, npr, npt, npl;
2452     for (j = 0; j < nb; j++) {
2453       npb.Append(uv_eb[j].normParam);
2454     }
2455     for (i = 0; i < nr; i++) {
2456       npr.Append(uv_er[i].normParam);
2457     }
2458     for (j = 0; j < nt; j++) {
2459       npt.Append(uv_et[j].normParam);
2460     }
2461     for (i = 0; i < nl; i++) {
2462       npl.Append(uv_el[i].normParam);
2463     }
2464
2465     int dl,dr;
2466     // orientation of face and 3 main domain for future faces
2467     //       0   top    1
2468     //      1------------1
2469     //       |   |  |   |
2470     //       |   |  |   |
2471     //       | L |  | R |
2472     //  left |   |  |   | rigth
2473     //       |  /    \  |
2474     //       | /  C   \ |
2475     //       |/        \|
2476     //      0------------0
2477     //       0  bottom  1
2478
2479     // add some params to right and left after the first param
2480     // insert to right
2481     dr = nbv - nr;
2482     double dpr = (npr.Value(2) - npr.Value(1))/(dr+1);
2483     for (i=1; i<=dr; i++) {
2484       npr.InsertAfter(1,npr.Value(2)-dpr);
2485     }
2486     // insert to left
2487     dl = nbv - nl;
2488     dpr = (npl.Value(2) - npl.Value(1))/(dl+1);
2489     for (i=1; i<=dl; i++) {
2490       npl.InsertAfter(1,npl.Value(2)-dpr);
2491     }
2492   
2493     gp_XY a0 (uv_eb.front().u, uv_eb.front().v);
2494     gp_XY a1 (uv_eb.back().u,  uv_eb.back().v);
2495     gp_XY a2 (uv_et.back().u,  uv_et.back().v);
2496     gp_XY a3 (uv_et.front().u, uv_et.front().v);
2497
2498     int nnn = Min(nr,nl);
2499     // auxilary sequence of XY for creation of nodes
2500     // in the bottom part of central domain
2501     // it's length must be == nbv-nnn-1
2502     TColgp_SequenceOfXY UVL;
2503     TColgp_SequenceOfXY UVR;
2504     //==================================================
2505
2506     // step1: create faces for left domain
2507     StdMeshers_Array2OfNode NodesL(1,dl+1,1,nl);
2508     // add left nodes
2509     for (j=1; j<=nl; j++)
2510       NodesL.SetValue(1,j,uv_el[j-1].node);
2511     if (dl>0) {
2512       // add top nodes
2513       for (i=1; i<=dl; i++) 
2514         NodesL.SetValue(i+1,nl,uv_et[i].node);
2515       // create and add needed nodes
2516       TColgp_SequenceOfXY UVtmp;
2517       for (i=1; i<=dl; i++) {
2518         double x0 = npt.Value(i+1);
2519         double x1 = x0;
2520         // diagonal node
2521         double y0 = npl.Value(i+1);
2522         double y1 = npr.Value(i+1);
2523         gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2524         gp_Pnt P = S->Value(UV.X(),UV.Y());
2525         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2526         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2527         NodesL.SetValue(i+1,1,N);
2528         if (UVL.Length()<nbv-nnn-1) UVL.Append(UV);
2529         // internal nodes
2530         for (j=2; j<nl; j++) {
2531           double y0 = npl.Value(dl+j);
2532           double y1 = npr.Value(dl+j);
2533           gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2534           gp_Pnt P = S->Value(UV.X(),UV.Y());
2535           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2536           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2537           NodesL.SetValue(i+1,j,N);
2538           if (i==dl) UVtmp.Append(UV);
2539         }
2540       }
2541       for (i=1; i<=UVtmp.Length() && UVL.Length()<nbv-nnn-1; i++) {
2542         UVL.Append(UVtmp.Value(i));
2543       }
2544       // create faces
2545       for (i=1; i<=dl; i++) {
2546         for (j=1; j<nl; j++) {
2547             SMDS_MeshFace* F =
2548               myHelper->AddFace(NodesL.Value(i,j), NodesL.Value(i+1,j),
2549                                 NodesL.Value(i+1,j+1), NodesL.Value(i,j+1));
2550             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2551         }
2552       }
2553     }
2554     else {
2555       // fill UVL using c2d
2556       for (i=1; i<npl.Length() && UVL.Length()<nbv-nnn-1; i++) {
2557         UVL.Append(gp_UV (uv_el[i].u, uv_el[i].v));
2558       }
2559     }
2560     
2561     // step2: create faces for right domain
2562     StdMeshers_Array2OfNode NodesR(1,dr+1,1,nr);
2563     // add right nodes
2564     for (j=1; j<=nr; j++) 
2565       NodesR.SetValue(1,j,uv_er[nr-j].node);
2566     if (dr>0) {
2567       // add top nodes
2568       for (i=1; i<=dr; i++) 
2569         NodesR.SetValue(i+1,1,uv_et[nt-1-i].node);
2570       // create and add needed nodes
2571       TColgp_SequenceOfXY UVtmp;
2572       for (i=1; i<=dr; i++) {
2573         double x0 = npt.Value(nt-i);
2574         double x1 = x0;
2575         // diagonal node
2576         double y0 = npl.Value(i+1);
2577         double y1 = npr.Value(i+1);
2578         gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2579         gp_Pnt P = S->Value(UV.X(),UV.Y());
2580         SMDS_MeshNode * N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2581         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2582         NodesR.SetValue(i+1,nr,N);
2583         if (UVR.Length()<nbv-nnn-1) UVR.Append(UV);
2584         // internal nodes
2585         for (j=2; j<nr; j++) {
2586           double y0 = npl.Value(nbv-j+1);
2587           double y1 = npr.Value(nbv-j+1);
2588           gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2589           gp_Pnt P = S->Value(UV.X(),UV.Y());
2590           SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2591           meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2592           NodesR.SetValue(i+1,j,N);
2593           if (i==dr) UVtmp.Prepend(UV);
2594         }
2595       }
2596       for (i=1; i<=UVtmp.Length() && UVR.Length()<nbv-nnn-1; i++) {
2597         UVR.Append(UVtmp.Value(i));
2598       }
2599       // create faces
2600       for (i=1; i<=dr; i++) {
2601         for (j=1; j<nr; j++) {
2602             SMDS_MeshFace* F =
2603               myHelper->AddFace(NodesR.Value(i,j), NodesR.Value(i+1,j),
2604                                 NodesR.Value(i+1,j+1), NodesR.Value(i,j+1));
2605             if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2606         }
2607       }
2608     }
2609     else {
2610       // fill UVR using c2d
2611       for (i=1; i<npr.Length() && UVR.Length()<nbv-nnn-1; i++) {
2612         UVR.Append(gp_UV(uv_er[i].u, uv_er[i].v));
2613       }
2614     }
2615     
2616     // step3: create faces for central domain
2617     StdMeshers_Array2OfNode NodesC(1,nb,1,nbv);
2618     // add first line using NodesL
2619     for (i=1; i<=dl+1; i++)
2620       NodesC.SetValue(1,i,NodesL(i,1));
2621     for (i=2; i<=nl; i++)
2622       NodesC.SetValue(1,dl+i,NodesL(dl+1,i));
2623     // add last line using NodesR
2624     for (i=1; i<=dr+1; i++)
2625       NodesC.SetValue(nb,i,NodesR(i,nr));
2626     for (i=1; i<nr; i++)
2627       NodesC.SetValue(nb,dr+i+1,NodesR(dr+1,nr-i));
2628     // add top nodes (last columns)
2629     for (i=dl+2; i<nbh-dr; i++) 
2630       NodesC.SetValue(i-dl,nbv,uv_et[i-1].node);
2631     // add bottom nodes (first columns)
2632     for (i=2; i<nb; i++)
2633       NodesC.SetValue(i,1,uv_eb[i-1].node);
2634     
2635     // create and add needed nodes
2636     // add linear layers
2637     for (i=2; i<nb; i++) {
2638       double x0 = npt.Value(dl+i);
2639       double x1 = x0;
2640       for (j=1; j<nnn; j++) {
2641         double y0 = npl.Value(nbv-nnn+j);
2642         double y1 = npr.Value(nbv-nnn+j);
2643         gp_UV UV = CalcUV(x0, x1, y0, y1, quad, a0, a1, a2, a3);
2644         gp_Pnt P = S->Value(UV.X(),UV.Y());
2645         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2646         meshDS->SetNodeOnFace(N, geomFaceID, UV.X(), UV.Y());
2647         NodesC.SetValue(i,nbv-nnn+j,N);
2648       }
2649     }
2650     // add diagonal layers
2651     for (i=1; i<nbv-nnn; i++) {
2652       double du = UVR.Value(i).X() - UVL.Value(i).X();
2653       double dv = UVR.Value(i).Y() - UVL.Value(i).Y();
2654       for (j=2; j<nb; j++) {
2655         double u = UVL.Value(i).X() + du*npb.Value(j);
2656         double v = UVL.Value(i).Y() + dv*npb.Value(j);
2657         gp_Pnt P = S->Value(u,v);
2658         SMDS_MeshNode* N = meshDS->AddNode(P.X(), P.Y(), P.Z());
2659         meshDS->SetNodeOnFace(N, geomFaceID, u, v);
2660         NodesC.SetValue(j,i+1,N);
2661       }
2662     }
2663     // create faces
2664     for (i=1; i<nb; i++) {
2665       for (j=1; j<nbv; j++) {
2666           SMDS_MeshFace* F =
2667             myHelper->AddFace(NodesC.Value(i,j), NodesC.Value(i+1,j),
2668                             NodesC.Value(i+1,j+1), NodesC.Value(i,j+1));
2669           if (F) meshDS->SetMeshElementOnShape(F, geomFaceID);
2670       }
2671     }
2672     // TODO ???
2673   } // end Multiple Reduce implementation
2674   else { // Simple Reduce (!MultipleReduce)
2675     //=========================================================
2676     if (nr == nl) {
2677       if (nt < nb) {
2678         // it is a base case => not shift quad
2679         //ShiftQuad(quad,0,true);
2680       }
2681       else {
2682         // we have to shift quad on 2
2683         ShiftQuad(quad,2,true);
2684       }
2685     }
2686     else {
2687       if (nl > nr) {
2688         // we have to shift quad on 1
2689         ShiftQuad(quad,1,true);
2690       }
2691       else {
2692         // we have to shift quad on 3
2693         ShiftQuad(quad,3,true);
2694       }
2695     }
2696
2697     nb = quad->side[0]->NbPoints();
2698     nr = quad->side[1]->NbPoints();
2699     nt = quad->side[2]->NbPoints();
2700     nl = quad->side[3]->NbPoints();
2701
2702     // number of rows and columns
2703     int nrows = nr - 1; // and also == nl - 1
2704     int ncol_top = nt - 1;
2705     int ncol_bot = nb - 1;
2706     int npair_top = ncol_top / 2;
2707     // maximum number of bottom elements for "linear" simple reduce 4->2
2708     int max_lin42 = ncol_top + npair_top * 2 * nrows;
2709     // maximum number of bottom elements for "linear" simple reduce 3->1
2710     int max_lin31 = ncol_top + ncol_top * 2 * nrows;
2711     // maximum number of bottom elements for "tree" simple reduce 4->2
2712     int max_tree42 = 0;
2713     // number of rows needed to reduce ncol_bot to ncol_top using simple 4->2 "tree"
2714     int nrows_tree42 = int( log( (double)(ncol_bot / ncol_top) )/log((double)2)  ); // needed to avoid overflow at pow(2) while computing max_tree42
2715     if (nrows_tree42 < nrows) {
2716       max_tree42 = npair_top * pow(2.0, nrows + 1);
2717       if ( ncol_top > npair_top * 2 ) {
2718         int delta = ncol_bot - max_tree42;
2719         for (int irow = 1; irow < nrows; irow++) {
2720           int nfour = delta / 4;
2721           delta -= nfour * 2;
2722         }
2723         if (delta <= (ncol_top - npair_top * 2))
2724           max_tree42 = ncol_bot;
2725       }
2726     }
2727     // maximum number of bottom elements for "tree" simple reduce 3->1
2728     //int max_tree31 = ncol_top * pow(3.0, nrows);
2729     bool is_lin_31 = false;
2730     bool is_lin_42 = false;
2731     bool is_tree_31 = false;
2732     bool is_tree_42 = false;
2733     int max_lin = max_lin42;
2734     if (ncol_bot > max_lin42) {
2735       if (ncol_bot <= max_lin31) {
2736         is_lin_31 = true;
2737         max_lin = max_lin31;
2738       }
2739     }
2740     else {
2741       // if ncol_bot is a 3*n or not 2*n
2742       if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
2743         is_lin_31 = true;
2744         max_lin = max_lin31;
2745       }
2746       else {
2747         is_lin_42 = true;
2748       }
2749     }
2750     if (ncol_bot > max_lin) { // not "linear"
2751       is_tree_31 = (ncol_bot > max_tree42);
2752       if (ncol_bot <= max_tree42) {
2753         if ((ncol_bot/3)*3 == ncol_bot || (ncol_bot/2)*2 != ncol_bot) {
2754           is_tree_31 = true;
2755         }
2756         else {
2757           is_tree_42 = true;
2758         }
2759       }
2760     }
2761
2762     const vector<UVPtStruct>& uv_eb = quad->side[0]->GetUVPtStruct(true,0);
2763     const vector<UVPtStruct>& uv_er = quad->side[1]->GetUVPtStruct(false,1);
2764     const vector<UVPtStruct>& uv_et = quad->side[2]->GetUVPtStruct(true,1);
2765     const vector<UVPtStruct>& uv_el = quad->side[3]->GetUVPtStruct(false,0);
2766
2767     if (uv_eb.size() != nb || uv_er.size() != nr || uv_et.size() != nt || uv_el.size() != nl)
2768       return error(COMPERR_BAD_INPUT_MESH);
2769
2770     myHelper->SetElementsOnShape( true );
2771
2772     gp_UV uv[ UV_SIZE ];
2773     uv[ UV_A0 ].SetCoord( uv_eb.front().u, uv_eb.front().v);
2774     uv[ UV_A1 ].SetCoord( uv_eb.back().u,  uv_eb.back().v );
2775     uv[ UV_A2 ].SetCoord( uv_et.back().u,  uv_et.back().v );
2776     uv[ UV_A3 ].SetCoord( uv_et.front().u, uv_et.front().v);
2777
2778     vector<UVPtStruct> curr_base = uv_eb, next_base;
2779
2780     UVPtStruct nullUVPtStruct; nullUVPtStruct.node = 0;
2781
2782     int curr_base_len = nb;
2783     int next_base_len = 0;
2784
2785     if ( true )
2786     { // ------------------------------------------------------------------
2787       // New algorithm implemented by request of IPAL22856
2788       // "2D quadrangle mesher of reduced type works wrong"
2789       // http://bugtracker.opencascade.com/show_bug.cgi?id=22856
2790
2791       // the algorithm is following: all reduces are centred in horizontal
2792       // direction and are distributed among all rows
2793
2794       if (ncol_bot > max_tree42) {
2795         is_lin_31 = true;
2796       }
2797       else {
2798         if ((ncol_top/3)*3 == ncol_top ) {
2799           is_lin_31 = true;
2800         }
2801         else {
2802           is_lin_42 = true;
2803         }
2804       }
2805
2806       const int col_top_size  = is_lin_42 ? 2 : 1;
2807       const int col_base_size = is_lin_42 ? 4 : 3;
2808
2809       // Compute nb of "columns" (like in "linear" simple reducing) in all rows
2810
2811       vector<int> nb_col_by_row;
2812
2813       int delta_all = nb - nt;
2814       int delta_one_col = nrows * 2;
2815       int nb_col = delta_all / delta_one_col;
2816       int remainder = delta_all - nb_col * delta_one_col;
2817       if (remainder > 0) {
2818         nb_col++;
2819       }
2820       if ( nb_col * col_top_size >= nt ) // == "tree" reducing situation
2821       {
2822         // top row is full (all elements reduced), add "columns" one by one
2823         // in rows below until all bottom elements are reduced
2824         nb_col = ( nt - 1 ) / col_top_size;
2825         nb_col_by_row.resize( nrows, nb_col );
2826         int nbrows_not_full = nrows - 1;
2827         int cur_top_size = nt - 1;
2828         remainder = delta_all - nb_col * delta_one_col;
2829         while ( remainder > 0 )
2830         {
2831           delta_one_col = nbrows_not_full * 2;
2832           int nb_col_add = remainder / delta_one_col;
2833           cur_top_size += 2 * nb_col_by_row[ nbrows_not_full ];
2834           int nb_col_free = cur_top_size / col_top_size - nb_col_by_row[ nbrows_not_full-1 ];
2835           if ( nb_col_add > nb_col_free )
2836             nb_col_add = nb_col_free;
2837           for ( int irow = 0; irow < nbrows_not_full; ++irow )
2838             nb_col_by_row[ irow ] += nb_col_add;
2839           nbrows_not_full --;
2840           remainder -=  nb_col_add * delta_one_col;
2841         }
2842       }
2843       else // == "linear" reducing situation
2844       {
2845         nb_col_by_row.resize( nrows, nb_col );
2846         if (remainder > 0)
2847           for ( int irow = remainder / 2; irow < nrows; ++irow )
2848             nb_col_by_row[ irow ]--;
2849       }
2850
2851       // Make elements
2852
2853       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
2854
2855       const int reduce_grp_size = is_lin_42 ? 4 : 3;
2856
2857       for (i = 1; i < nr; i++) // layer by layer
2858       {
2859         nb_col = nb_col_by_row[ i-1 ];
2860         int nb_next = curr_base_len - nb_col * 2;
2861         if (nb_next < nt) nb_next = nt;
2862
2863         const double y = uv_el[ i ].normParam;
2864
2865         if ( i + 1 == nr ) // top
2866         {
2867           next_base = uv_et;
2868         }
2869         else
2870         {
2871           next_base.clear();
2872           next_base.resize( nb_next, nullUVPtStruct );
2873           next_base.front() = uv_el[i];
2874           next_base.back()  = uv_er[i];
2875
2876           // compute normalized param u
2877           double du = 1. / ( nb_next - 1 );
2878           next_base[0].normParam = 0.;
2879           for ( j = 1; j < nb_next; ++j )
2880             next_base[j].normParam = next_base[j-1].normParam + du;
2881         }
2882         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
2883         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
2884
2885         int free_left = ( curr_base_len - 1 - nb_col * col_base_size ) / 2;
2886         int free_middle = curr_base_len - 1 - nb_col * col_base_size - 2 * free_left;
2887
2888         // not reduced left elements
2889         for (j = 0; j < free_left; j++)
2890         {
2891           // f (i + 1, j + 1)
2892           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
2893           if ( !Nf )
2894             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
2895
2896           myHelper->AddFace(curr_base[ j ].node,
2897                             curr_base[ j+1 ].node,
2898                             Nf,
2899                             next_base[ next_base_len-1 ].node);
2900         }
2901
2902         for (int icol = 1; icol <= nb_col; icol++)
2903         {
2904           // add "H"
2905           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
2906
2907           j += reduce_grp_size;
2908
2909           // elements in the middle of "columns" added for symmetry
2910           if ( free_middle > 0 && ( nb_col % 2 == 0 ) && icol == nb_col / 2 )
2911           {
2912             for (int imiddle = 1; imiddle <= free_middle; imiddle++) {
2913               // f (i + 1, j + imiddle)
2914               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
2915               if ( !Nf )
2916                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
2917
2918               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
2919                                 curr_base[ j  +imiddle ].node,
2920                                 Nf,
2921                                 next_base[ next_base_len-1 ].node);
2922             }
2923             j += free_middle;
2924           }
2925         }
2926
2927         // not reduced right elements
2928         for (; j < curr_base_len-1; j++) {
2929           // f (i + 1, j + 1)
2930           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
2931           if ( !Nf )
2932             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
2933
2934           myHelper->AddFace(curr_base[ j ].node,
2935                             curr_base[ j+1 ].node,
2936                             Nf,
2937                             next_base[ next_base_len-1 ].node);
2938         }
2939
2940         curr_base_len = next_base_len + 1;
2941         next_base_len = 0;
2942         curr_base.swap( next_base );
2943       }
2944
2945     }
2946     else if ( is_tree_42 || is_tree_31 )
2947     {
2948       // "tree" simple reduce "42": 2->4->8->16->32->...
2949       //
2950       //  .-------------------------------.-------------------------------. nr
2951       //  |    \                          |                          /    |
2952       //  |         \     .---------------.---------------.     /         |
2953       //  |               |               |               |               |
2954       //  .---------------.---------------.---------------.---------------.
2955       //  | \             |             / | \             |             / |
2956       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
2957       //  |       |       |       |       |       |       |       |       |
2958       //  .-------.-------.-------.-------.-------.-------.-------.-------. i
2959       //  |\      |      /|\      |      /|\      |      /|\      |      /|
2960       //  |  \.---.---./  |  \.---.---./  |  \.---.---./  |  \.---.---./  |
2961       //  |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
2962       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.
2963       //  |\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|\  |  /|
2964       //  | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. | .-.-. |
2965       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
2966       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
2967       //  1                               j                               nb
2968
2969       // "tree" simple reduce "31": 1->3->9->27->...
2970       //
2971       //  .-----------------------------------------------------. nr
2972       //  |        \                                   /        |
2973       //  |                 .-----------------.                 |
2974       //  |                 |                 |                 |
2975       //  .-----------------.-----------------.-----------------.
2976       //  |   \         /   |   \         /   |   \         /   |
2977       //  |     .-----.     |     .-----.     |     .-----.     | i
2978       //  |     |     |     |     |     |     |     |     |     |
2979       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.
2980       //  |\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|\   /|
2981       //  | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. | .-. |
2982       //  | | | | | | | | | | | | | | | | | | | | | | | | | | | |
2983       //  .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. 1
2984       //  1                          j                          nb
2985
2986       PReduceFunction reduceFunction = & ( is_tree_42 ? reduce42 : reduce31 );
2987
2988       const int reduce_grp_size = is_tree_42 ? 4 : 3;
2989
2990       for (i = 1; i < nr; i++) // layer by layer
2991       {
2992         // to stop reducing, if number of nodes reaches nt
2993         int delta = curr_base_len - nt;
2994
2995         // to calculate normalized parameter, we must know number of points in next layer
2996         int nb_reduce_groups = (curr_base_len - 1) / reduce_grp_size;
2997         int nb_next = nb_reduce_groups * (reduce_grp_size-2) + (curr_base_len - nb_reduce_groups*reduce_grp_size);
2998         if (nb_next < nt) nb_next = nt;
2999
3000         const double y = uv_el[ i ].normParam;
3001
3002         if ( i + 1 == nr ) // top
3003         {
3004           next_base = uv_et;
3005         }
3006         else
3007         {
3008           next_base.clear();
3009           next_base.resize( nb_next, nullUVPtStruct );
3010           next_base.front() = uv_el[i];
3011           next_base.back()  = uv_er[i];
3012
3013           // compute normalized param u
3014           double du = 1. / ( nb_next - 1 );
3015           next_base[0].normParam = 0.;
3016           for ( j = 1; j < nb_next; ++j )
3017             next_base[j].normParam = next_base[j-1].normParam + du;
3018         }
3019         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3020         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3021
3022         for (j = 0; j+reduce_grp_size < curr_base_len && delta > 0; j+=reduce_grp_size, delta-=2)
3023         {
3024           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3025         }
3026
3027         // not reduced side elements (if any)
3028         for (; j < curr_base_len-1; j++)
3029         {
3030           // f (i + 1, j + 1)
3031           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3032           if ( !Nf )
3033             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3034           
3035           myHelper->AddFace(curr_base[ j ].node,
3036                             curr_base[ j+1 ].node,
3037                             Nf,
3038                             next_base[ next_base_len-1 ].node);
3039         }
3040         curr_base_len = next_base_len + 1;
3041         next_base_len = 0;
3042         curr_base.swap( next_base );
3043       }
3044     } // end "tree" simple reduce
3045
3046     else if ( is_lin_42 || is_lin_31 ) {
3047       // "linear" simple reduce "31": 2->6->10->14
3048       //
3049       //  .-----------------------------.-----------------------------. nr
3050       //  |     \                 /     |     \                 /     |
3051       //  |         .---------.         |         .---------.         |
3052       //  |         |         |         |         |         |         |
3053       //  .---------.---------.---------.---------.---------.---------.
3054       //  |        / \       / \        |        / \       / \        |
3055       //  |       /   .-----.   \       |       /   .-----.   \       | i
3056       //  |      /    |     |    \      |      /    |     |    \      |
3057       //  .-----.-----.-----.-----.-----.-----.-----.-----.-----.-----.
3058       //  |    /     / \   / \     \    |    /     / \   / \     \    |
3059       //  |   /     /   .-.   \     \   |   /     /   .-.   \     \   |
3060       //  |  /     /   /   \   \     \  |  /     /   /   \   \     \  |
3061       //  .--.----.---.-----.---.-----.-.--.----.---.-----.---.-----.-. 1
3062       //  1                             j                             nb
3063
3064       // "linear" simple reduce "42": 4->8->12->16
3065       //
3066       //  .---------------.---------------.---------------.---------------. nr
3067       //  | \             |             / | \             |             / |
3068       //  |     \ .-------.-------. /     |     \ .-------.-------. /     |
3069       //  |       |       |       |       |       |       |       |       |
3070       //  .-------.-------.-------.-------.-------.-------.-------.-------.
3071       //  |      / \      |      / \      |      / \      |      / \      |
3072       //  |     /   \.----.----./   \     |     /   \.----.----./   \     | i
3073       //  |     /    |    |    |    \     |     /    |    |    |    \     |
3074       //  .-----.----.----.----.----.-----.-----.----.----.----.----.-----.
3075       //  |     /   / \   |  /  \   \     |     /   / \   |  /  \   \     |
3076       //  |    /   /    .-.-.    \   \    |    /   /    .-.-.    \   \    |
3077       //  |   /   /    /  |  \    \   \   |   /   /    /  |  \    \   \   |
3078       //  .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---. 1
3079       //  1                               j                               nb
3080
3081       // nt = 5, nb = 7, nr = 4
3082       //int delta_all = 2;
3083       //int delta_one_col = 6;
3084       //int nb_col = 0;
3085       //int remainder = 2;
3086       //if (remainder > 0) nb_col++;
3087       //nb_col = 1;
3088       //int free_left = 1;
3089       //free_left += 2;
3090       //int free_middle = 4;
3091
3092       int delta_all = nb - nt;
3093       int delta_one_col = (nr - 1) * 2;
3094       int nb_col = delta_all / delta_one_col;
3095       int remainder = delta_all - nb_col * delta_one_col;
3096       if (remainder > 0) {
3097         nb_col++;
3098       }
3099       const int col_top_size = is_lin_42 ? 2 : 1;
3100       int free_left = ((nt - 1) - nb_col * col_top_size) / 2;
3101       free_left += nr - 2;
3102       int free_middle = (nr - 2) * 2;
3103       if (remainder > 0 && nb_col == 1) {
3104         int nb_rows_short_col = remainder / 2;
3105         int nb_rows_thrown = (nr - 1) - nb_rows_short_col;
3106         free_left -= nb_rows_thrown;
3107       }
3108
3109       // nt = 5, nb = 17, nr = 4
3110       //int delta_all = 12;
3111       //int delta_one_col = 6;
3112       //int nb_col = 2;
3113       //int remainder = 0;
3114       //int free_left = 2;
3115       //int free_middle = 4;
3116
3117       PReduceFunction reduceFunction = & ( is_lin_42 ? reduce42 : reduce31 );
3118
3119       const int reduce_grp_size = is_lin_42 ? 4 : 3;
3120
3121       for (i = 1; i < nr; i++, free_middle -= 2, free_left -= 1) // layer by layer
3122       {
3123         // to calculate normalized parameter, we must know number of points in next layer
3124         int nb_next = curr_base_len - nb_col * 2;
3125         if (remainder > 0 && i > remainder / 2)
3126           // take into account short "column"
3127           nb_next += 2;
3128         if (nb_next < nt) nb_next = nt;
3129
3130         const double y = uv_el[ i ].normParam;
3131
3132         if ( i + 1 == nr ) // top
3133         {
3134           next_base = uv_et;
3135         }
3136         else
3137         {
3138           next_base.clear();
3139           next_base.resize( nb_next, nullUVPtStruct );
3140           next_base.front() = uv_el[i];
3141           next_base.back()  = uv_er[i];
3142
3143           // compute normalized param u
3144           double du = 1. / ( nb_next - 1 );
3145           next_base[0].normParam = 0.;
3146           for ( j = 1; j < nb_next; ++j )
3147             next_base[j].normParam = next_base[j-1].normParam + du;
3148         }
3149         uv[ UV_L ].SetCoord( next_base.front().u, next_base.front().v );
3150         uv[ UV_R ].SetCoord( next_base.back().u,  next_base.back().v );
3151
3152         // not reduced left elements
3153         for (j = 0; j < free_left; j++)
3154         {
3155           // f (i + 1, j + 1)
3156           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3157           if ( !Nf )
3158             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3159
3160           myHelper->AddFace(curr_base[ j ].node,
3161                             curr_base[ j+1 ].node,
3162                             Nf,
3163                             next_base[ next_base_len-1 ].node);
3164         }
3165
3166         for (int icol = 1; icol <= nb_col; icol++) {
3167
3168           if (remainder > 0 && icol == nb_col && i > remainder / 2)
3169             // stop short "column"
3170             break;
3171
3172           // add "H"
3173           reduceFunction( curr_base, next_base, j, next_base_len, quad, uv, y, myHelper, S );
3174
3175           j += reduce_grp_size;
3176
3177           // not reduced middle elements
3178           if (icol < nb_col) {
3179             if (remainder > 0 && icol == nb_col - 1 && i > remainder / 2)
3180               // pass middle elements before stopped short "column"
3181               break;
3182
3183             int free_add = free_middle;
3184             if (remainder > 0 && icol == nb_col - 1)
3185               // next "column" is short
3186               free_add -= (nr - 1) - (remainder / 2);
3187
3188             for (int imiddle = 1; imiddle <= free_add; imiddle++) {
3189               // f (i + 1, j + imiddle)
3190               const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3191               if ( !Nf )
3192                 Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3193
3194               myHelper->AddFace(curr_base[ j-1+imiddle ].node,
3195                                 curr_base[ j  +imiddle ].node,
3196                                 Nf,
3197                                 next_base[ next_base_len-1 ].node);
3198             }
3199             j += free_add;
3200           }
3201         }
3202
3203         // not reduced right elements
3204         for (; j < curr_base_len-1; j++) {
3205           // f (i + 1, j + 1)
3206           const SMDS_MeshNode*& Nf = next_base[++next_base_len].node;
3207           if ( !Nf )
3208             Nf = makeNode( next_base[ next_base_len ], y, quad, uv, myHelper, S );
3209
3210           myHelper->AddFace(curr_base[ j ].node,
3211                             curr_base[ j+1 ].node,
3212                             Nf,
3213                             next_base[ next_base_len-1 ].node);
3214         }
3215
3216         curr_base_len = next_base_len + 1;
3217         next_base_len = 0;
3218         curr_base.swap( next_base );
3219       }
3220
3221     } // end "linear" simple reduce
3222
3223     else {
3224       return false;
3225     }
3226   } // end Simple Reduce implementation
3227
3228   bool isOk = true;
3229   return isOk;
3230 }
3231
3232 //================================================================================
3233 namespace // data for smoothing
3234 {
3235   struct TSmoothNode;
3236   // --------------------------------------------------------------------------------
3237   /*!
3238    * \brief Structure used to check validity of node position after smoothing.
3239    *        It holds two nodes connected to a smoothed node and belonging to
3240    *        one mesh face
3241    */
3242   struct TTriangle
3243   {
3244     TSmoothNode* _n1;
3245     TSmoothNode* _n2;
3246     TTriangle( TSmoothNode* n1=0, TSmoothNode* n2=0 ): _n1(n1), _n2(n2) {}
3247
3248     inline bool IsForward( gp_UV uv ) const;
3249   };
3250   // --------------------------------------------------------------------------------
3251   /*!
3252    * \brief Data of a smoothed node
3253    */
3254   struct TSmoothNode
3255   {
3256     gp_XY _uv;
3257     vector< TTriangle > _triangles; // if empty, then node is not movable
3258   };
3259   // --------------------------------------------------------------------------------
3260   inline bool TTriangle::IsForward( gp_UV uv ) const
3261   {
3262     gp_Vec2d v1( uv, _n1->_uv ), v2( uv, _n2->_uv );
3263     double d = v1 ^ v2;
3264     return d > 1e-100;
3265   }
3266 }
3267
3268 //================================================================================
3269 /*!
3270  * \brief Set UV of nodes on degenerated VERTEXes in the middle of degenerated EDGE
3271  *
3272  * WARNING: this method must be called AFTER retrieving UVPtStruct's from quad
3273  */
3274 //================================================================================
3275
3276 void StdMeshers_Quadrangle_2D::UpdateDegenUV(FaceQuadStruct* quad)
3277 {
3278   for ( unsigned i = 0; i < quad->side.size(); ++i )
3279   {
3280     StdMeshers_FaceSide* side = quad->side[i];
3281     const vector<UVPtStruct>& uvVec = side->GetUVPtStruct();
3282
3283     // find which end of the side is on degenerated shape
3284     int degenInd = -1;
3285     if ( myHelper->IsDegenShape( uvVec[0].node->getshapeId() ))
3286       degenInd = 0;
3287     else if ( myHelper->IsDegenShape( uvVec.back().node->getshapeId() ))
3288       degenInd = uvVec.size() - 1;
3289     else
3290       continue;
3291
3292     // find another side sharing the degenerated shape
3293     bool isPrev = ( degenInd == 0 );
3294     if ( i >= TOP_SIDE )
3295       isPrev = !isPrev;
3296     int i2 = ( isPrev ? ( i + 3 ) : ( i + 1 )) % 4;
3297     StdMeshers_FaceSide* side2 = quad->side[ i2 ];
3298     const vector<UVPtStruct>& uvVec2 = side2->GetUVPtStruct();
3299     int degenInd2 = -1;
3300     if ( uvVec[ degenInd ].node == uvVec2[0].node )
3301       degenInd2 = 0;
3302     else if ( uvVec[ degenInd ].node == uvVec2.back().node )
3303       degenInd2 = uvVec2.size() - 1;
3304     else
3305       throw SALOME_Exception( LOCALIZED( "Logical error" ));
3306
3307     // move UV in the middle
3308     uvPtStruct& uv1 = const_cast<uvPtStruct&>( uvVec [ degenInd  ]);
3309     uvPtStruct& uv2 = const_cast<uvPtStruct&>( uvVec2[ degenInd2 ]);
3310     uv1.u = uv2.u = 0.5 * ( uv1.u + uv2.u );
3311     uv1.v = uv2.v = 0.5 * ( uv1.v + uv2.v );
3312   }
3313 }
3314
3315 //================================================================================
3316 /*!
3317  * \brief Perform smoothing of 2D elements on a FACE with ignored degenerated EDGE
3318  */
3319 //================================================================================
3320
3321 void StdMeshers_Quadrangle_2D::Smooth (FaceQuadStruct* quad)
3322 {
3323   if ( !myNeedSmooth ) return;
3324
3325   // Get nodes to smooth
3326
3327   typedef map< const SMDS_MeshNode*, TSmoothNode, TIDCompare > TNo2SmooNoMap;
3328   TNo2SmooNoMap smooNoMap;
3329
3330   const TopoDS_Face& geomFace = TopoDS::Face( myHelper->GetSubShape() );
3331   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
3332   SMESHDS_SubMesh* fSubMesh = meshDS->MeshElements( geomFace );
3333   SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
3334   while ( nIt->more() ) // loop on nodes bound to a FACE
3335   {
3336     const SMDS_MeshNode* node = nIt->next();
3337     TSmoothNode & sNode = smooNoMap[ node ];
3338     sNode._uv = myHelper->GetNodeUV( geomFace, node );
3339
3340     // set sNode._triangles
3341     SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator( SMDSAbs_Face );
3342     while ( fIt->more() )
3343     {
3344       const SMDS_MeshElement* face = fIt->next();
3345       const int nbN = face->NbCornerNodes();
3346       const int nInd = face->GetNodeIndex( node );
3347       const int prevInd = myHelper->WrapIndex( nInd - 1, nbN );
3348       const int nextInd = myHelper->WrapIndex( nInd + 1, nbN );
3349       const SMDS_MeshNode* prevNode = face->GetNode( prevInd );
3350       const SMDS_MeshNode* nextNode = face->GetNode( nextInd );
3351       sNode._triangles.push_back( TTriangle( & smooNoMap[ prevNode ],
3352                                              & smooNoMap[ nextNode ]));
3353     }
3354   }
3355   // set _uv of smooth nodes on FACE boundary
3356   for ( unsigned i = 0; i < quad->side.size(); ++i )
3357   {
3358     const vector<UVPtStruct>& uvVec = quad->side[i]->GetUVPtStruct();
3359     for ( unsigned j = 0; j < uvVec.size(); ++j )
3360     {
3361       TSmoothNode & sNode = smooNoMap[ uvVec[j].node ];
3362       sNode._uv.SetCoord( uvVec[j].u, uvVec[j].v );
3363     }
3364   }
3365
3366   // define refernce orientation in 2D
3367   TNo2SmooNoMap::iterator n2sn = smooNoMap.begin();
3368   for ( ; n2sn != smooNoMap.end(); ++n2sn )
3369     if ( !n2sn->second._triangles.empty() )
3370       break;
3371   if ( n2sn == smooNoMap.end() ) return;
3372   const TSmoothNode & sampleNode = n2sn->second;
3373   const bool refForward = ( sampleNode._triangles[0].IsForward( sampleNode._uv ));
3374
3375   // Smoothing
3376
3377   for ( int iLoop = 0; iLoop < 5; ++iLoop )
3378   {
3379     for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3380     {
3381       TSmoothNode& sNode = n2sn->second;
3382       if ( sNode._triangles.empty() )
3383         continue; // not movable node
3384
3385       // compute a new UV
3386       gp_XY newUV (0,0);
3387       for ( unsigned i = 0; i < sNode._triangles.size(); ++i )
3388         newUV += sNode._triangles[i]._n1->_uv;
3389       newUV /= sNode._triangles.size();
3390
3391       // check validity of the newUV
3392       bool isValid = true;
3393       for ( unsigned i = 0; i < sNode._triangles.size() && isValid; ++i )
3394         isValid = ( sNode._triangles[i].IsForward( newUV ) == refForward );
3395
3396       if ( isValid )
3397         sNode._uv = newUV;
3398     }
3399   }
3400
3401   // Set new XYZ to the smoothed nodes
3402
3403   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
3404
3405   for ( n2sn = smooNoMap.begin(); n2sn != smooNoMap.end(); ++n2sn )
3406   {
3407     TSmoothNode& sNode = n2sn->second;
3408     if ( sNode._triangles.empty() )
3409       continue; // not movable node
3410
3411     SMDS_MeshNode* node = const_cast< SMDS_MeshNode*>( n2sn->first );
3412     gp_Pnt xyz = surface->Value( sNode._uv.X(), sNode._uv.Y() );
3413     meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
3414
3415     // store the new UV
3416     node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( sNode._uv.X(), sNode._uv.Y() )));
3417   }
3418
3419   // Move medium nodes in quadratic mesh
3420   if ( _quadraticMesh )
3421   {
3422     const TLinkNodeMap& links = myHelper->GetTLinkNodeMap();
3423     TLinkNodeMap::const_iterator linkIt = links.begin();
3424     for ( ; linkIt != links.end(); ++linkIt )
3425     {
3426       const SMESH_TLink& link = linkIt->first;
3427       SMDS_MeshNode*     node = const_cast< SMDS_MeshNode*>( linkIt->second );
3428
3429       if ( node->getshapeId() != myHelper->GetSubShapeID() )
3430         continue; // medium node is on EDGE or VERTEX
3431
3432       gp_XY uv1 = myHelper->GetNodeUV( geomFace, link.node1(), node );
3433       gp_XY uv2 = myHelper->GetNodeUV( geomFace, link.node2(), node );
3434
3435       gp_XY uv  = myHelper->GetMiddleUV( surface, uv1, uv2 );
3436       node->SetPosition( SMDS_PositionPtr( new SMDS_FacePosition( uv.X(), uv.Y() )));
3437       
3438       gp_Pnt xyz = surface->Value( uv.X(), uv.Y() );
3439       meshDS->MoveNode( node, xyz.X(), xyz.Y(), xyz.Z() );
3440     }
3441   }
3442 }