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