Salome HOME
[HYDRO module - Feature #523] river, channel, embankment meshing
[modules/smesh.git] / src / StdMeshers / StdMeshers_MEFISTO_2D.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 //  File   : StdMeshers_MEFISTO_2D.cxx
25 //           Moved here from SMESH_MEFISTO_2D.cxx
26 //  Author : Paul RASCLE, EDF
27 //  Module : SMESH
28 //
29 #include "StdMeshers_MEFISTO_2D.hxx"
30
31 #include "SMDS_EdgePosition.hxx"
32 #include "SMDS_MeshElement.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Mesh.hxx"
37 #include "SMESH_MesherHelper.hxx"
38 #include "SMESH_subMesh.hxx"
39 #include "StdMeshers_FaceSide.hxx"
40 #include "StdMeshers_LengthFromEdges.hxx"
41 #include "StdMeshers_MaxElementArea.hxx"
42 #include "StdMeshers_ViscousLayers2D.hxx"
43
44 #include "utilities.h"
45
46 #include "Rn.h"
47 #include "aptrte.h"
48
49 #include <BRepGProp.hxx>
50 #include <BRepTools.hxx>
51 #include <BRep_Tool.hxx>
52 #include <GProp_GProps.hxx>
53 #include <Geom2d_Curve.hxx>
54 #include <Geom_Curve.hxx>
55 #include <Geom_Surface.hxx>
56 #include <Precision.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopTools_ListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
62 #include <TopoDS.hxx>
63 #include <TopoDS_Edge.hxx>
64 #include <TopoDS_Face.hxx>
65 #include <TopoDS_Iterator.hxx>
66 #include <TopoDS_Wire.hxx>
67 #include <gp_Pnt2d.hxx>
68
69 using namespace std;
70
71 #ifdef _DEBUG_
72 //#define DUMP_POINTS // to print coordinates of MEFISTO input
73 #endif
74
75 //=============================================================================
76 /*!
77  *  
78  */
79 //=============================================================================
80
81 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
82   SMESH_2D_Algo(hypId, studyId, gen)
83 {
84   MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
85   _name = "MEFISTO_2D";
86   _shapeType = (1 << TopAbs_FACE);
87   _compatibleHypothesis.push_back("MaxElementArea");
88   _compatibleHypothesis.push_back("LengthFromEdges");
89   _compatibleHypothesis.push_back("ViscousLayers2D");
90
91   _edgeLength = 0;
92   _maxElementArea = 0;
93   _hypMaxElementArea = NULL;
94   _hypLengthFromEdges = NULL;
95   _helper = 0;
96 }
97
98 //=============================================================================
99 /*!
100  *  
101  */
102 //=============================================================================
103
104 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
105 {
106   MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
107 }
108
109 //=============================================================================
110 /*!
111  *  
112  */
113 //=============================================================================
114
115 bool StdMeshers_MEFISTO_2D::CheckHypothesis
116                          (SMESH_Mesh&                          aMesh,
117                           const TopoDS_Shape&                  aShape,
118                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
119 {
120   _hypMaxElementArea = NULL;
121   _hypLengthFromEdges = NULL;
122   _edgeLength = 0;
123   _maxElementArea = 0;
124
125   if ( !error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
126     return false;
127
128   list <const SMESHDS_Hypothesis * >::const_iterator itl;
129   const SMESHDS_Hypothesis *theHyp;
130
131   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
132   int nbHyp = hyps.size();
133   if (!nbHyp)
134   {
135     aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
136     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
137   }
138
139   itl = hyps.begin();
140   theHyp = (*itl); // use only the first hypothesis
141
142   string hypName = theHyp->GetName();
143
144   bool isOk = false;
145
146   if (hypName == "MaxElementArea")
147   {
148     _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
149     ASSERT(_hypMaxElementArea);
150     _maxElementArea = _hypMaxElementArea->GetMaxArea();
151     isOk = true;
152     aStatus = SMESH_Hypothesis::HYP_OK;
153   }
154
155   else if (hypName == "LengthFromEdges")
156   {
157     _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
158     ASSERT(_hypLengthFromEdges);
159     isOk = true;
160     aStatus = SMESH_Hypothesis::HYP_OK;
161   }
162   else
163     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
164
165   if (isOk)
166   {
167     isOk = false;
168     if (_maxElementArea > 0)
169     {
170       //_edgeLength = 2 * sqrt(_maxElementArea);        // triangles : minorant
171       _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
172       isOk = true;
173     }
174     else
175       isOk = (_hypLengthFromEdges != NULL);     // **** check mode
176     if (!isOk)
177       aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
178   }
179
180   return isOk;
181 }
182
183 //=============================================================================
184 /*!
185  *  
186  */
187 //=============================================================================
188
189 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
190 {
191   MESSAGE("StdMeshers_MEFISTO_2D::Compute");
192
193   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
194
195   // helper builds quadratic mesh if necessary
196   SMESH_MesherHelper helper(aMesh);
197   _helper = &helper;
198   _quadraticMesh = _helper->IsQuadraticSubMesh(aShape);
199   const bool skipMediumNodes = _quadraticMesh;
200
201   // build viscous layers if required
202   SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
203   if ( !proxyMesh )
204     return false;
205
206   // get all edges of a face
207   TError problem;
208   TWireVector wires =
209     StdMeshers_FaceSide::GetFaceWires( F, aMesh, skipMediumNodes, problem, proxyMesh );
210   int nbWires = wires.size();
211   if ( problem && !problem->IsOK() ) return error( problem );
212   if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
213   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
214     return error(COMPERR_BAD_INPUT_MESH,
215                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
216
217   // compute average edge length
218   if (!_hypMaxElementArea)
219   {
220     _edgeLength = 0;
221     int nbSegments = 0;
222     for ( int iW = 0; iW < nbWires; ++iW )
223     {
224       StdMeshers_FaceSidePtr wire = wires[ iW ];
225       _edgeLength += wire->Length();
226       nbSegments  += wire->NbSegments();
227     }
228     if ( nbSegments )
229       _edgeLength /= nbSegments;
230   }
231
232   if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
233     _edgeLength = 100;
234
235   Z nblf;                 //nombre de lignes fermees (enveloppe en tete)
236   Z *nudslf = NULL;       //numero du dernier sommet de chaque ligne fermee
237   R2 *uvslf = NULL;       
238   Z nbpti = 0;            //nombre points internes futurs sommets de la triangulation
239   R2 *uvpti = NULL;
240   
241   Z nbst;
242   R2 *uvst = NULL;
243   Z nbt;
244   Z *nust = NULL;
245   Z ierr = 0;
246
247   Z nutysu = 1;           // 1: il existe un fonction areteideale_()
248   // Z  nutysu=0;         // 0: on utilise aretmx
249   R aretmx = _edgeLength; // longueur max aretes future triangulation
250   if ( _hypMaxElementArea )
251     aretmx *= 1.5;
252   
253   nblf = nbWires;
254   
255   nudslf = new Z[1 + nblf];
256   nudslf[0] = 0;
257   int iw = 1;
258   int nbpnt = 0;
259
260   // count nb of input points
261   for ( int iW = 0; iW < nbWires; ++iW )
262   {
263     nbpnt += wires[iW]->NbPoints() - 1;
264     nudslf[iw++] = nbpnt;
265   }
266
267   uvslf = new R2[nudslf[nblf]];
268
269   double scalex, scaley;
270   ComputeScaleOnFace(aMesh, F, scalex, scaley);
271
272   // correspondence mefisto index --> Nodes
273   vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
274
275   bool isOk = false;
276
277   // fill input points UV
278   if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
279   {
280     // Compute
281     aptrte(nutysu, aretmx,
282            nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
283
284     if (ierr == 0)
285     {
286       MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
287       MESSAGE("                                    Node Number " << nbst);
288       StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
289       isOk = true;
290     }
291     else
292     {
293       error(ierr,"Error in Triangulation (aptrte())");
294     }
295   }
296   if (nudslf != NULL) delete[]nudslf;
297   if (uvslf != NULL)  delete[]uvslf;
298   if (uvst != NULL)   delete[]uvst;
299   if (nust != NULL)   delete[]nust;
300
301   return isOk;
302 }
303
304
305 //=============================================================================
306 /*!
307  *  
308  */
309 //=============================================================================
310
311 bool StdMeshers_MEFISTO_2D::Evaluate(SMESH_Mesh & aMesh,
312                                      const TopoDS_Shape & aShape,
313                                      MapShapeNbElems& aResMap)
314 {
315   MESSAGE("StdMeshers_MEFISTO_2D::Evaluate");
316
317   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
318
319   double aLen = 0.0;
320   int NbSeg = 0;
321   bool IsQuadratic = false;
322   bool IsFirst = true;
323   TopExp_Explorer exp(F,TopAbs_EDGE);
324   for(; exp.More(); exp.Next()) {
325     TopoDS_Edge E = TopoDS::Edge(exp.Current());
326     MapShapeNbElemsItr anIt = aResMap.find( aMesh.GetSubMesh(E) );
327     if( anIt == aResMap.end() ) continue;
328     std::vector<int> aVec = (*anIt).second;
329     int nbe = Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
330     NbSeg += nbe;
331     if(IsFirst) {
332       IsQuadratic = ( aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge] );
333       IsFirst = false;
334     }
335     double a,b;
336     TopLoc_Location L;
337     Handle(Geom_Curve) C = BRep_Tool::Curve(E,L,a,b);
338     gp_Pnt P1;
339     C->D0(a,P1);
340     double dp = (b-a)/nbe;
341     for(int i=1; i<=nbe; i++) {
342       gp_Pnt P2;
343       C->D0(a+i*dp,P2);
344       aLen += P1.Distance(P2);
345       P1 = P2;
346     }
347   }
348   if(NbSeg<1) {
349     std::vector<int> aResVec(SMDSEntity_Last);
350     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
351     SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
352     aResMap.insert(std::make_pair(sm,aResVec));
353     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
354     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
355                                           "Submesh can not be evaluated",this));
356     return false;
357   }
358   aLen = aLen/NbSeg; // middle length
359
360   _edgeLength = Precision::Infinite();
361   double tmpLength = Min( _edgeLength, aLen );
362
363   GProp_GProps G;
364   BRepGProp::SurfaceProperties(aShape,G);
365   double anArea = G.Mass();
366
367   int nbFaces = Precision::IsInfinite( tmpLength ) ? 0 :
368     (int)( anArea/(tmpLength*tmpLength*sqrt(3.)/4) );
369   int nbNodes = (int) ( nbFaces*3 - (NbSeg-1)*2 ) / 6;
370
371   std::vector<int> aVec(SMDSEntity_Last);
372   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i] = 0;
373   if(IsQuadratic) {
374     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
375     aVec[SMDSEntity_Node] = (int)( nbNodes + nbFaces*3 - (NbSeg-1) );
376   }
377   else {
378     aVec[SMDSEntity_Node] = nbNodes;
379     aVec[SMDSEntity_Triangle] = nbFaces;
380   }
381   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
382   aResMap.insert(std::make_pair(sm,aVec));
383
384   return true;
385 }
386
387
388 //=======================================================================
389 //function : fixOverlappedLinkUV
390 //purpose  : prevent failure due to overlapped adjacent links
391 //=======================================================================
392
393 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
394 {
395   gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
396   gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
397
398   double tol2 = DBL_MIN * DBL_MIN;
399   double sqMod1 = v1.SquareModulus();
400   if ( sqMod1 <= tol2 ) return false;
401   double sqMod2 = v2.SquareModulus();
402   if ( sqMod2 <= tol2 ) return false;
403
404   double dot = v1*v2;
405
406   // check sinus >= 1.e-3
407   const double minSin = 1.e-3;
408   if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
409     MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
410     v1.SetCoord( -v1.Y(), v1.X() );
411     double delta = sqrt( sqMod1 ) * minSin;
412     if ( v1.X() < 0 )
413       uv0.x -= delta;
414     else
415       uv0.x += delta;
416     if ( v1.Y() < 0 )
417       uv0.y -= delta;
418     else
419       uv0.y += delta;
420 // #ifdef _DEBUG_
421 //     MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
422 //     MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
423 //       "v2( " << v2.X() << " " << v2.Y() << " ) ");
424 //    MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
425 //     v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
426 //     v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
427 //     gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
428 //     sqMod1 = v1.SquareModulus();
429 //     sqMod2 = v2.SquareModulus();
430 //     dot = v1*v2;
431 //     double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
432 //     MESSAGE("NEW SIN: " << sin);
433 // #endif
434     return true;
435   }
436   return false;
437 }
438
439 //=======================================================================
440 //function : fixCommonVertexUV
441 //purpose  : 
442 //=======================================================================
443
444 static bool fixCommonVertexUV (R2 &                 theUV,
445                                const TopoDS_Vertex& theV,
446                                const TopoDS_Face&   theF,
447                                const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
448                                SMESH_Mesh &         theMesh,
449                                const double         theScaleX,
450                                const double         theScaleY,
451                                const bool           theCreateQuadratic)
452 {
453   if( !theVWMap.Contains( theV )) return false;
454
455   // check if there is another wire sharing theV
456   const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
457   TopTools_ListIteratorOfListOfShape aWIt;
458   TopTools_MapOfShape aWires;
459   for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
460     aWires.Add( aWIt.Value() );
461   if ( aWires.Extent() < 2 ) return false;
462
463   TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
464   TopoDS_Shape anInnerWire;
465   for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
466     if ( !anOuterWire.IsSame( aWIt.Value() ))
467       anInnerWire = aWIt.Value();
468
469   TopTools_ListOfShape EList;
470   list< double >       UList;
471
472   // find edges of theW sharing theV
473   // and find 2d normal to them at theV
474   gp_Vec2d N(0.,0.);
475   TopoDS_Iterator itE( anInnerWire );
476   for (  ; itE.More(); itE.Next() )
477   {
478     const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
479     TopoDS_Iterator itV( E );
480     for ( ; itV.More(); itV.Next() )
481     {
482       const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
483       if ( !V.IsSame( theV ))
484         continue;
485       EList.Append( E );
486       Standard_Real u = BRep_Tool::Parameter( V, E );
487       UList.push_back( u );
488       double f, l;
489       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
490       gp_Vec2d d1;
491       gp_Pnt2d p;
492       C2d->D1( u, p, d1 );
493       gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
494       if ( E.Orientation() == TopAbs_REVERSED )
495         n.Reverse();
496       N += n.Normalized();
497     }
498   }
499
500   // define step size by which to move theUV
501
502   gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
503   gp_Pnt2d thisUV( theUV.x, theUV.y );
504   double maxDist = -DBL_MAX;
505   TopTools_ListIteratorOfListOfShape aEIt (EList);
506   list< double >::iterator aUIt = UList.begin();
507   for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
508   {
509     const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
510     double f, l;
511     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
512
513     double umin = DBL_MAX, umax = -DBL_MAX;
514     SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
515     if ( !nIt->more() ) // no nodes on edge, only on vertices
516     {
517       umin = l;
518       umax = f;
519     }
520     else {
521       while ( nIt->more() ) {
522         const SMDS_MeshNode* node = nIt->next();
523         // check if node is medium
524         if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
525           continue;
526         const SMDS_EdgePosition* epos =
527           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
528         double u = epos->GetUParameter();
529         if ( u < umin )
530           umin = u;
531         if ( u > umax )
532           umax = u;
533       }
534     }
535     bool isFirstCommon = ( *aUIt == f );
536     gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
537     double dist = thisUV.SquareDistance( uv );
538     if ( dist > maxDist ) {
539       maxDist = dist;
540       nextUV  = uv;
541     }
542   }
543   R2 uv0, uv1, uv2;
544   uv0.x = thisUV.X();   uv0.y = thisUV.Y();
545   uv1.x = nextUV.X();   uv1.y = nextUV.Y(); 
546   uv2.x = thisUV.X();   uv2.y = thisUV.Y();
547
548   uv1.x *= theScaleX;   uv1.y *= theScaleY; 
549
550   if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
551   {
552     double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
553
554     // move theUV along the normal by the step
555
556     N *= step;
557
558     MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
559             << ") by (" << N.X() << " " << N.Y() << ")" 
560             << endl << "--- MAX DIST " << maxDist);
561
562     theUV.x += N.X();
563     theUV.y += N.Y();
564
565     return true;
566   }
567   return false;
568 }
569
570 //=============================================================================
571 /*!
572  *  
573  */
574 //=============================================================================
575
576 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector &                 wires,
577                                        R2 *                          uvslf,
578                                        vector<const SMDS_MeshNode*>& mefistoToDS,
579                                        double                        scalex,
580                                        double                        scaley)
581 {
582   // to avoid passing same uv points for a vertex common to 2 wires
583   TopoDS_Face F;
584   TopTools_IndexedDataMapOfShapeListOfShape VWMap;
585   if ( wires.size() > 1 )
586   {
587     F = TopoDS::Face( _helper->GetSubShape() );
588     TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
589     int nbVertices = 0;
590     for ( int iW = 0; iW < wires.size(); ++iW )
591       nbVertices += wires[ iW ]->NbEdges();
592     if ( nbVertices == VWMap.Extent() )
593       VWMap.Clear(); // wires have no common vertices
594   }
595
596   int m = 0;
597
598   for ( int iW = 0; iW < wires.size(); ++iW )
599   {
600     const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
601     if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
602       return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
603                    << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
604                    << ", probably because of invalid node parameters on geom edges");
605     }
606     if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
607       MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
608       return error("Internal error");
609     }
610
611     list< int > mOnVertex;
612     vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
613     for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
614     {
615       // bind mefisto ID to node
616       mefistoToDS[m] = uvPt->node;
617       // set UV
618       uvslf[m].x = uvPt->u * scalex;
619       uvslf[m].y = uvPt->v * scaley;
620       switch ( uvPt->node->GetPosition()->GetTypeOfPosition())
621       {
622       case SMDS_TOP_VERTEX:
623         mOnVertex.push_back( m );
624         break;
625       case SMDS_TOP_EDGE:
626         // In order to detect degenerated faces easily, we replace
627         // nodes on a degenerated edge by node on the vertex of that edge
628         if ( _helper->IsDegenShape( uvPt->node->getshapeId() ))
629         {
630           int edgeID = uvPt->node->getshapeId();
631           SMESH_subMesh* edgeSM = _helper->GetMesh()->GetSubMeshContaining( edgeID );
632           SMESH_subMeshIteratorPtr smIt = edgeSM->getDependsOnIterator( /*includeSelf=*/0,
633                                                                         /*complexShapeFirst=*/0);
634           if ( smIt->more() )
635           {
636             SMESH_subMesh* vertexSM = smIt->next();
637             SMDS_NodeIteratorPtr nIt = vertexSM->GetSubMeshDS()->GetNodes();
638             if ( nIt->more() )
639               mefistoToDS[m] = nIt->next();
640           }
641         }
642         break;
643       default:;
644       }
645       m++;
646     }
647
648     int mFirst = mOnVertex.front(), mLast = m - 1;
649     list< int >::iterator mIt = mOnVertex.begin();
650     for ( ; mIt != mOnVertex.end(); ++mIt)
651     {
652       int m = *mIt;
653       if ( iW && !VWMap.IsEmpty()) { // except outer wire
654         // avoid passing same uv point for a vertex common to 2 wires
655         int vID = mefistoToDS[m]->getshapeId();
656         TopoDS_Vertex V = TopoDS::Vertex( _helper->GetMeshDS()->IndexToShape( vID ));
657         if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *_helper->GetMesh(),
658                                 scalex, scaley, _quadraticMesh )) {
659           myNodesOnCommonV.push_back( mefistoToDS[m] );
660           continue;
661         }
662       }
663       // prevent failure on overlapped adjacent links,
664       // check only links ending in vertex nodes
665       int mB = m - 1, mA = m + 1; // indices Before and After
666       if ( mB < mFirst ) mB = mLast;
667       if ( mA > mLast )  mA = mFirst;
668       fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
669     }
670   }
671
672 #ifdef DUMP_POINTS
673   cout << "MEFISTO INPUT************" << endl;
674   for ( int i =0; i < m; ++i )
675     cout << i << ": \t" << uvslf[i].x << ", " << uvslf[i].y
676          << " Node " << mefistoToDS[i]->GetID()<< endl;
677 #endif
678
679   return true;
680 }
681
682 //=============================================================================
683 /*!
684  *  
685  */
686 //=============================================================================
687
688 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh &        aMesh,
689                                                const TopoDS_Face & aFace,
690                                                double &            scalex,
691                                                double &            scaley)
692 {
693   TopoDS_Wire W = BRepTools::OuterWire(aFace);
694
695   double xmin = 1.e300;         // min & max of face 2D parametric coord.
696   double xmax = -1.e300;
697   double ymin = 1.e300;
698   double ymax = -1.e300;
699   const int nbp = 23;
700   scalex = 1;
701   scaley = 1;
702
703   TopExp_Explorer wexp(W, TopAbs_EDGE);
704   for ( ; wexp.More(); wexp.Next())
705   {
706     const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
707     double f, l;
708     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
709     if ( C2d.IsNull() ) continue;
710     double du = (l - f) / double (nbp);
711     for (int i = 0; i <= nbp; i++)
712     {
713       double param = f + double (i) * du;
714       gp_Pnt2d p = C2d->Value(param);
715       if (p.X() < xmin)
716         xmin = p.X();
717       if (p.X() > xmax)
718         xmax = p.X();
719       if (p.Y() < ymin)
720         ymin = p.Y();
721       if (p.Y() > ymax)
722         ymax = p.Y();
723     }
724   }
725   double xmoy = (xmax + xmin) / 2.;
726   double ymoy = (ymax + ymin) / 2.;
727   double xsize = xmax - xmin;
728   double ysize = ymax - ymin;
729
730   TopLoc_Location L;
731   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L);       // 3D surface
732
733   double length_x = 0;
734   double length_y = 0;
735   gp_Pnt PX0 = S->Value(xmin, ymoy);
736   gp_Pnt PY0 = S->Value(xmoy, ymin);
737   double dx = xsize / double (nbp);
738   double dy = ysize / double (nbp);
739   for (int i = 1; i <= nbp; i++)
740   {
741     double x = xmin + double (i) * dx;
742     gp_Pnt PX = S->Value(x, ymoy);
743     double y = ymin + double (i) * dy;
744     gp_Pnt PY = S->Value(xmoy, y);
745     length_x += PX.Distance(PX0);
746     length_y += PY.Distance(PY0);
747     PX0 = PX;
748     PY0 = PY;
749   }
750   scalex = length_x / xsize;
751   scaley = length_y / ysize;
752   double xyratio = xsize*scalex/(ysize*scaley);
753   const double maxratio = 1.e2;
754   if (xyratio > maxratio) {
755     scaley *= xyratio / maxratio;
756   }
757   else if (xyratio < 1./maxratio) {
758     scalex *= 1 / xyratio / maxratio;
759   }
760 }
761
762 // namespace
763 // {
764 //   bool isDegenTria( const SMDS_MeshNode * nn[3] )
765 //   {
766 //     SMESH_TNodeXYZ p1( nn[0] );
767 //     SMESH_TNodeXYZ p2( nn[1] );
768 //     SMESH_TNodeXYZ p3( nn[2] );
769 //     gp_XYZ vec1 = p2 - p1;
770 //     gp_XYZ vec2 = p3 - p1;
771 //     gp_XYZ cross = vec1 ^ vec2;
772 //     const double eps = 1e-100;
773 //     return ( fabs( cross.X() ) < eps &&
774 //              fabs( cross.Y() ) < eps &&
775 //              fabs( cross.Z() ) < eps );
776 //   }
777 // }
778
779 //=============================================================================
780 /*!
781  *  
782  */
783 //=============================================================================
784
785 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
786                                         vector< const SMDS_MeshNode*>&mefistoToDS,
787                                         double scalex, double scaley)
788 {
789   _helper->SetElementsOnShape( true );
790
791   TopoDS_Face F = TopoDS::Face( _helper->GetSubShape() );
792   Handle(Geom_Surface) S = BRep_Tool::Surface( F );
793
794   //const size_t nbInputNodes = mefistoToDS.size();
795
796   Z n = mefistoToDS.size(); // nb input points
797   mefistoToDS.resize( nbst );
798   for ( ; n < nbst; n++)
799   {
800     if (!mefistoToDS[n])
801     {
802       double u = uvst[n][0] / scalex;
803       double v = uvst[n][1] / scaley;
804       gp_Pnt P = S->Value(u, v);
805
806       mefistoToDS[n] = _helper->AddNode( P.X(), P.Y(), P.Z(), 0, u, v );
807     }
808   }
809
810   Z m = 0;
811
812   // triangle points must be in trigonometric order if face is Forward
813   // else they must be put clockwise
814
815   int i1 = 1, i2 = 2;
816   if ( F.Orientation() != TopAbs_FORWARD )
817     std::swap( i1, i2 );
818
819   const SMDS_MeshNode * nn[3];
820   for (n = 1; n <= nbt; n++)
821   {
822     // const bool allNodesAreOld = ( nust[m + 0] <= nbInputNodes &&
823     //                               nust[m + 1] <= nbInputNodes &&
824     //                               nust[m + 2] <= nbInputNodes );
825     nn[ 0 ] = mefistoToDS[ nust[m++] - 1 ];
826     nn[ 1 ] = mefistoToDS[ nust[m++] - 1 ];
827     nn[ 2 ] = mefistoToDS[ nust[m++] - 1 ];
828     m++;
829
830     // avoid creating degenetrated faces
831     bool isDegen = ( _helper->HasDegeneratedEdges() &&
832                      ( nn[0] == nn[1] || nn[1] == nn[2] || nn[2] == nn[0] ));
833
834     // It was an attemp to fix a problem of a zero area face whose all nodes
835     // are on one staight EDGE. But omitting this face makes a hole in the mesh :(
836     // if ( !isDegen && allNodesAreOld )
837     //   isDegen = isDegenTria( nn );
838
839     if ( !isDegen )
840       _helper->AddFace( nn[0], nn[i1], nn[i2] );
841   }
842
843   // remove bad elements built on vertices shared by wires
844
845   list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
846   for ( ; itN != myNodesOnCommonV.end(); itN++ )
847   {
848     const SMDS_MeshNode* node = *itN;
849     SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
850     while ( invElemIt->more() )
851     {
852       const SMDS_MeshElement* elem = invElemIt->next();
853       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
854       int nbSame = 0;
855       while ( itN->more() )
856         if ( itN->next() == node)
857           nbSame++;
858       if (nbSame > 1) {
859         MESSAGE( "RM bad element " << elem->GetID());
860         _helper->GetMeshDS()->RemoveElement( elem );
861       }
862     }
863   }
864 }