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