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