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