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