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