File: StdMeshers_MEFISTO_2D.cpp

package info (click to toggle)
freecad 0.14.3702+dfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 162,288 kB
  • ctags: 78,057
  • sloc: cpp: 360,157; python: 199,755; xml: 7,653; fortran: 3,878; ansic: 702; lex: 204; yacc: 91; sh: 41; makefile: 18
file content (723 lines) | stat: -rw-r--r-- 22,828 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
//
//  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
//  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
//
//  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
//  SMESH SMESH : implementaion of SMESH idl descriptions
//  File   : StdMeshers_MEFISTO_2D.cxx
//           Moved here from SMESH_MEFISTO_2D.cxx
//  Author : Paul RASCLE, EDF
//  Module : SMESH
//  $Header: /home/server/cvs/SMESH/SMESH_SRC/src/StdMeshers/StdMeshers_MEFISTO_2D.cxx,v 1.11.2.3 2008/11/27 13:03:49 abd Exp $
//
#include "StdMeshers_MEFISTO_2D.hxx"

#include "SMESH_Gen.hxx"
#include "SMESH_Mesh.hxx"
#include "SMESH_subMesh.hxx"
#include "SMESH_Block.hxx"
#include "SMESH_MesherHelper.hxx"
#include "SMESH_Comment.hxx"

#include "StdMeshers_FaceSide.hxx"
#include "StdMeshers_MaxElementArea.hxx"
#include "StdMeshers_LengthFromEdges.hxx"

#include "Rn.h"
#include "aptrte.h"

#include "SMDS_MeshElement.hxx"
#include "SMDS_MeshNode.hxx"
#include "SMDS_EdgePosition.hxx"
#include "SMDS_FacePosition.hxx"

#include "utilities.h"

#include <BRepTools.hxx>
#include <BRep_Tool.hxx>
#include <Geom2d_Curve.hxx>
#include <Geom_Surface.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Iterator.hxx>
#include <gp_Pnt2d.hxx>

using namespace std;

//=============================================================================
/*!
 *  
 */
//=============================================================================

StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
  SMESH_2D_Algo(hypId, studyId, gen)
{
  MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
  _name = "MEFISTO_2D";
  _shapeType = (1 << TopAbs_FACE);
  _compatibleHypothesis.push_back("MaxElementArea");
  _compatibleHypothesis.push_back("LengthFromEdges");

  _edgeLength = 0;
  _maxElementArea = 0;
  _hypMaxElementArea = NULL;
  _hypLengthFromEdges = NULL;
  myTool = 0;
}

//=============================================================================
/*!
 *  
 */
//=============================================================================

StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
{
  MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
}

//=============================================================================
/*!
 *  
 */
//=============================================================================

bool StdMeshers_MEFISTO_2D::CheckHypothesis
                         (SMESH_Mesh&                          aMesh,
                          const TopoDS_Shape&                  aShape,
                          SMESH_Hypothesis::Hypothesis_Status& aStatus)
{
  _hypMaxElementArea = NULL;
  _hypLengthFromEdges = NULL;
  _edgeLength = 0;
  _maxElementArea = 0;

  list <const SMESHDS_Hypothesis * >::const_iterator itl;
  const SMESHDS_Hypothesis *theHyp;

  const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
  int nbHyp = hyps.size();
  if (!nbHyp)
  {
    aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
    return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
  }

  itl = hyps.begin();
  theHyp = (*itl); // use only the first hypothesis

  string hypName = theHyp->GetName();

  bool isOk = false;

  if (hypName == "MaxElementArea")
  {
    _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
    ASSERT(_hypMaxElementArea);
    _maxElementArea = _hypMaxElementArea->GetMaxArea();
    isOk = true;
    aStatus = SMESH_Hypothesis::HYP_OK;
  }

  else if (hypName == "LengthFromEdges")
  {
    _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
    ASSERT(_hypLengthFromEdges);
    isOk = true;
    aStatus = SMESH_Hypothesis::HYP_OK;
  }
  else
    aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;

  if (isOk)
  {
    isOk = false;
    if (_maxElementArea > 0)
    {
      //_edgeLength = 2 * sqrt(_maxElementArea);        // triangles : minorant
      _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
      isOk = true;
    }
    else
      isOk = (_hypLengthFromEdges != NULL);     // **** check mode
    if (!isOk)
      aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
  }

  return isOk;
}

//=============================================================================
/*!
 *  
 */
//=============================================================================

bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
{
  MESSAGE("StdMeshers_MEFISTO_2D::Compute");

  TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));

  // helper builds quadratic mesh if necessary
  SMESH_MesherHelper helper(aMesh);
  myTool = &helper;
  _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
  const bool ignoreMediumNodes = _quadraticMesh;

  // get all edges of a face
  TError problem;
  TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
  int nbWires = wires.size();
  if ( (problem!=NULL) && !problem->IsOK() ) return error( problem );
  if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
  if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
    return error(COMPERR_BAD_INPUT_MESH,
                 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());

  // compute average edge length
  if (!_hypMaxElementArea)
  {
    _edgeLength = 0;
    int nbSegments = 0;
    for ( int iW = 0; iW < nbWires; ++iW )
    {
      StdMeshers_FaceSidePtr wire = wires[ iW ];
      _edgeLength += wire->Length();
      nbSegments  += wire->NbSegments();
    }
    if ( nbSegments )
      _edgeLength /= nbSegments;
  }

  if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
    _edgeLength = 100;

  Z nblf;                 //nombre de lignes fermees (enveloppe en tete)
  Z *nudslf = NULL;       //numero du dernier sommet de chaque ligne fermee
  R_2 *uvslf = NULL;       
  Z nbpti = 0;            //nombre points internes futurs sommets de la triangulation
  R_2 *uvpti = NULL;
  
  Z nbst;
  R_2 *uvst = NULL;
  Z nbt;
  Z *nust = NULL;
  Z ierr = 0;

  Z nutysu = 1;           // 1: il existe un fonction areteideale_()
  // Z  nutysu=0;         // 0: on utilise aretmx
  R aretmx = _edgeLength; // longueur max aretes future triangulation
  
  nblf = nbWires;
  
  nudslf = new Z[1 + nblf];
  nudslf[0] = 0;
  int iw = 1;
  int nbpnt = 0;

  // count nb of input points
  for ( int iW = 0; iW < nbWires; ++iW )
  {
    nbpnt += wires[iW]->NbPoints() - 1;
    nudslf[iw++] = nbpnt;
  }

  uvslf = new R_2[nudslf[nblf]];

  double scalex, scaley;
  ComputeScaleOnFace(aMesh, F, scalex, scaley);

  // correspondence mefisto index --> Nodes
  vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);

  bool isOk = false;

  // fill input points UV
  if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
  {
    // Compute
    aptrte(nutysu, aretmx,
           nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);

    if (ierr == 0)
    {
      MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
      MESSAGE("                                    Node Number " << nbst);
      StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
      isOk = true;
    }
    else
    {
      error(ierr,"Error in Triangulation (aptrte())");
    }
  }
  if (nudslf != NULL) delete[]nudslf;
  if (uvslf != NULL)  delete[]uvslf;
  if (uvst != NULL)   delete[]uvst;
  if (nust != NULL)   delete[]nust;

  return isOk;
}

//=======================================================================
//function : fixOverlappedLinkUV
//purpose  : prevent failure due to overlapped adjacent links
//=======================================================================

static bool fixOverlappedLinkUV( R_2& uv0, const R_2& uv1, const R_2& uv2 )
{
  gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
  gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );

  double tol2 = DBL_MIN * DBL_MIN;
  double sqMod1 = v1.SquareModulus();
  if ( sqMod1 <= tol2 ) return false;
  double sqMod2 = v2.SquareModulus();
  if ( sqMod2 <= tol2 ) return false;

  double dot = v1*v2;

  // check sinus >= 1.e-3
  const double minSin = 1.e-3;
  if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
    MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
    v1.SetCoord( -v1.Y(), v1.X() );
    double delta = sqrt( sqMod1 ) * minSin;
    if ( v1.X() < 0 )
      uv0.x -= delta;
    else
      uv0.x += delta;
    if ( v1.Y() < 0 )
      uv0.y -= delta;
    else
      uv0.y += delta;
// #ifdef _DEBUG_
//     MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
//     MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
//       "v2( " << v2.X() << " " << v2.Y() << " ) ");
//    MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
//     v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
//     v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
//     gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
//     sqMod1 = v1.SquareModulus();
//     sqMod2 = v2.SquareModulus();
//     dot = v1*v2;
//     double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
//     MESSAGE("NEW SIN: " << sin);
// #endif
    return true;
  }
  return false;
}

//=======================================================================
//function : fixCommonVertexUV
//purpose  : 
//=======================================================================

static bool fixCommonVertexUV (R_2 &                 theUV,
                               const TopoDS_Vertex& theV,
                               const TopoDS_Face&   theF,
                               const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
                               SMESH_Mesh &         theMesh,
                               const double         theScaleX,
                               const double         theScaleY,
                               const bool           theCreateQuadratic)
{
  if( !theVWMap.Contains( theV )) return false;

  // check if there is another wire sharing theV
  const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
  TopTools_ListIteratorOfListOfShape aWIt;
  TopTools_MapOfShape aWires;
  for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
    aWires.Add( aWIt.Value() );
  if ( aWires.Extent() < 2 ) return false;

  TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
  TopoDS_Shape anInnerWire;
  for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
    if ( !anOuterWire.IsSame( aWIt.Value() ))
      anInnerWire = aWIt.Value();

  TopTools_ListOfShape EList;
  list< double >       UList;

  // find edges of theW sharing theV
  // and find 2d normal to them at theV
  gp_Vec2d N(0.,0.);
  TopoDS_Iterator itE( anInnerWire );
  for (  ; itE.More(); itE.Next() )
  {
    const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
    TopoDS_Iterator itV( E );
    for ( ; itV.More(); itV.Next() )
    {
      const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
      if ( !V.IsSame( theV ))
        continue;
      EList.Append( E );
      Standard_Real u = BRep_Tool::Parameter( V, E );
      UList.push_back( u );
      double f, l;
      Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
      gp_Vec2d d1;
      gp_Pnt2d p;
      C2d->D1( u, p, d1 );
      gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
      if ( E.Orientation() == TopAbs_REVERSED )
        n.Reverse();
      N += n.Normalized();
    }
  }

  // define step size by which to move theUV

  gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
  gp_Pnt2d thisUV( theUV.x, theUV.y );
  double maxDist = -DBL_MAX;
  TopTools_ListIteratorOfListOfShape aEIt (EList);
  list< double >::iterator aUIt = UList.begin();
  for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
  {
    const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
    double f, l;
    Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);

    double umin = DBL_MAX, umax = -DBL_MAX;
    SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
    if ( !nIt->more() ) // no nodes on edge, only on vertices
    {
      umin = l;
      umax = f;
    }
    else {
      while ( nIt->more() ) {
        const SMDS_MeshNode* node = nIt->next();
        // check if node is medium
        if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
          continue;
        const SMDS_EdgePosition* epos =
          static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
        double u = epos->GetUParameter();
        if ( u < umin )
          umin = u;
        if ( u > umax )
          umax = u;
      }
    }
    bool isFirstCommon = ( *aUIt == f );
    gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
    double dist = thisUV.SquareDistance( uv );
    if ( dist > maxDist ) {
      maxDist = dist;
      nextUV  = uv;
    }
  }
  R_2 uv0, uv1, uv2;
  uv0.x = thisUV.X();   uv0.y = thisUV.Y();
  uv1.x = nextUV.X();   uv1.y = nextUV.Y(); 
  uv2.x = thisUV.X();   uv2.y = thisUV.Y();

  uv1.x *= theScaleX;   uv1.y *= theScaleY; 

  if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
  {
    double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));

    // move theUV along the normal by the step

    N *= step;

    MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
            << ") by (" << N.X() << " " << N.Y() << ")" 
            << endl << "--- MAX DIST " << maxDist);

    theUV.x += N.X();
    theUV.y += N.Y();

    return true;
  }
  return false;
}

//=============================================================================
/*!
 *  
 */
//=============================================================================

bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector &                 wires,
                                       R_2 *                          uvslf,
                                       vector<const SMDS_MeshNode*>& mefistoToDS,
                                       double                        scalex,
                                       double                        scaley)
{
  // to avoid passing same uv points for a vertex common to 2 wires
  TopoDS_Face F;
  TopTools_IndexedDataMapOfShapeListOfShape VWMap;
  if ( wires.size() > 1 )
  {
    F = TopoDS::Face( myTool->GetSubShape() );
    TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
    int nbVertices = 0;
    for ( int iW = 0; iW < wires.size(); ++iW )
      nbVertices += wires[ iW ]->NbEdges();
    if ( nbVertices == VWMap.Extent() )
      VWMap.Clear(); // wires have no common vertices
  }

  int m = 0;

  for ( int iW = 0; iW < wires.size(); ++iW )
  {
    const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
    if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
      return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
                   << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
                   << ", probably because of invalid node parameters on geom edges");
    }
    if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
      MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
      return error("Internal error");
    }
    
    list< int > mOnVertex;
    vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
    for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
    {
      // bind mefisto ID to node
      mefistoToDS[m] = uvPt->node;
      // set UV
      uvslf[m].x = uvPt->u * scalex;
      uvslf[m].y = uvPt->v * scaley;
      if ( uvPt->node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
        mOnVertex.push_back( m );
      m++;
    }

    int mFirst = mOnVertex.front(), mLast = m - 1;
    list< int >::iterator mIt = mOnVertex.begin();
    for ( ; mIt != mOnVertex.end(); ++mIt)
    {
      int m = *mIt;
      if ( iW && !VWMap.IsEmpty()) { // except outer wire
        // avoid passing same uv point for a vertex common to 2 wires
        int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
        TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
        if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
                                scalex, scaley, _quadraticMesh )) {
          myNodesOnCommonV.push_back( mefistoToDS[m] );
          continue;
        }
      }
      // prevent failure on overlapped adjacent links,
      // check only links ending in vertex nodes
      int mB = m - 1, mA = m + 1; // indices Before and After
      if ( mB < mFirst ) mB = mLast;
      if ( mA > mLast )  mA = mFirst;
      fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
    }
  }

  return true;
}

//=============================================================================
/*!
 *  
 */
//=============================================================================

void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh &        aMesh,
                                               const TopoDS_Face & aFace,
                                               double &            scalex,
                                               double &            scaley)
{
  TopoDS_Wire W = BRepTools::OuterWire(aFace);

  double xmin = 1.e300;         // min & max of face 2D parametric coord.
  double xmax = -1.e300;
  double ymin = 1.e300;
  double ymax = -1.e300;
  int nbp = 23;
  scalex = 1;
  scaley = 1;

  TopExp_Explorer wexp(W, TopAbs_EDGE);
  for ( ; wexp.More(); wexp.Next())
  {
    const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
    double f, l;
    Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
    if ( C2d.IsNull() ) continue;
    double du = (l - f) / double (nbp);
    for (int i = 0; i <= nbp; i++)
    {
      double param = f + double (i) * du;
      gp_Pnt2d p = C2d->Value(param);
      if (p.X() < xmin)
        xmin = p.X();
      if (p.X() > xmax)
        xmax = p.X();
      if (p.Y() < ymin)
        ymin = p.Y();
      if (p.Y() > ymax)
        ymax = p.Y();
      //    MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
    }
  }
  //   SCRUTE(xmin);
  //   SCRUTE(xmax);
  //   SCRUTE(ymin);
  //   SCRUTE(ymax);
  double xmoy = (xmax + xmin) / 2.;
  double ymoy = (ymax + ymin) / 2.;
  double xsize = xmax - xmin;
  double ysize = ymax - ymin;

  TopLoc_Location L;
  Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L);       // 3D surface

  double length_x = 0;
  double length_y = 0;
  gp_Pnt PX0 = S->Value(xmin, ymoy);
  gp_Pnt PY0 = S->Value(xmoy, ymin);
  double dx = xsize / double (nbp);
  double dy = ysize / double (nbp);
  for (int i = 1; i <= nbp; i++)
  {
    double x = xmin + double (i) * dx;
    gp_Pnt PX = S->Value(x, ymoy);
    double y = ymin + double (i) * dy;
    gp_Pnt PY = S->Value(xmoy, y);
    length_x += PX.Distance(PX0);
    length_y += PY.Distance(PY0);
    PX0 = PX;
    PY0 = PY;
  }
  scalex = length_x / xsize;
  scaley = length_y / ysize;
//   SCRUTE(xsize);
//   SCRUTE(ysize);
  double xyratio = xsize*scalex/(ysize*scaley);
  const double maxratio = 1.e2;
  //SCRUTE(xyratio);
  if (xyratio > maxratio) {
    SCRUTE( scaley );
    scaley *= xyratio / maxratio;
    SCRUTE( scaley );
  }
  else if (xyratio < 1./maxratio) {
    SCRUTE( scalex );
    scalex *= 1 / xyratio / maxratio;
    SCRUTE( scalex );
  }
  ASSERT(scalex);
  ASSERT(scaley);
}

//=============================================================================
/*!
 *  
 */
//=============================================================================

void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R_2 * uvst, Z nbt, Z * nust,
                                        vector< const SMDS_MeshNode*>&mefistoToDS,
                                        double scalex, double scaley)
{
  SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
  int faceID = myTool->GetSubShapeID();

  TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
  Handle(Geom_Surface) S = BRep_Tool::Surface( F );

  Z n = mefistoToDS.size(); // nb input points
  mefistoToDS.resize( nbst );
  for ( ; n < nbst; n++)
  {
    if (!mefistoToDS[n])
    {
      double u = uvst[n][0] / scalex;
      double v = uvst[n][1] / scaley;
      gp_Pnt P = S->Value(u, v);

      SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
      meshDS->SetNodeOnFace(node, faceID, u, v);

      //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
      mefistoToDS[n] = node;
      //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
    }
  }

  Z m = 0;

  // triangle points must be in trigonometric order if face is Forward
  // else they must be put clockwise

  bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );

  for (n = 1; n <= nbt; n++)
  {
    const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
    const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
    const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];

    SMDS_MeshElement * elt;
    if (triangleIsWellOriented)
      elt = myTool->AddFace(n1, n2, n3);
    else
      elt = myTool->AddFace(n1, n3, n2);

    meshDS->SetMeshElementOnShape(elt, faceID);
    m++;
  }

  // remove bad elements built on vertices shared by wires

  list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
  for ( ; itN != myNodesOnCommonV.end(); itN++ )
  {
    const SMDS_MeshNode* node = *itN;
    SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
    while ( invElemIt->more() )
    {
      const SMDS_MeshElement* elem = invElemIt->next();
      SMDS_ElemIteratorPtr itN = elem->nodesIterator();
      int nbSame = 0;
      while ( itN->more() )
        if ( itN->next() == node)
          nbSame++;
      if (nbSame > 1) {
        MESSAGE( "RM bad element " << elem->GetID());
        meshDS->RemoveElement( elem );
      }
    }
  }
}