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