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