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