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