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