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