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