Salome HOME
Merge from BR_V5_DEV 16Feb09
[modules/smesh.git] / src / StdMeshers / StdMeshers_MEFISTO_2D.cxx
1 //  Copyright (C) 2007-2008  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.
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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 //  File   : StdMeshers_MEFISTO_2D.cxx
24 //           Moved here from SMESH_MEFISTO_2D.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28 #include "StdMeshers_MEFISTO_2D.hxx"
29
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_Mesh.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_Block.hxx"
34 #include "SMESH_MesherHelper.hxx"
35 #include "SMESH_Comment.hxx"
36
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_MaxElementArea.hxx"
39 #include "StdMeshers_LengthFromEdges.hxx"
40
41 #include "Rn.h"
42 #include "aptrte.h"
43
44 #include "SMDS_MeshElement.hxx"
45 #include "SMDS_MeshNode.hxx"
46 #include "SMDS_EdgePosition.hxx"
47 #include "SMDS_FacePosition.hxx"
48
49 #include "utilities.h"
50
51 #include <BRepTools.hxx>
52 #include <BRep_Tool.hxx>
53 #include <Geom2d_Curve.hxx>
54 #include <Geom_Surface.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_ListIteratorOfListOfShape.hxx>
58 #include <TopTools_ListOfShape.hxx>
59 #include <TopTools_MapOfShape.hxx>
60 #include <TopoDS.hxx>
61 #include <TopoDS_Edge.hxx>
62 #include <TopoDS_Face.hxx>
63 #include <TopoDS_Iterator.hxx>
64 #include <gp_Pnt2d.hxx>
65
66 using namespace std;
67
68 //=============================================================================
69 /*!
70  *  
71  */
72 //=============================================================================
73
74 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
75   SMESH_2D_Algo(hypId, studyId, gen)
76 {
77   MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
78   _name = "MEFISTO_2D";
79   _shapeType = (1 << TopAbs_FACE);
80   _compatibleHypothesis.push_back("MaxElementArea");
81   _compatibleHypothesis.push_back("LengthFromEdges");
82
83   _edgeLength = 0;
84   _maxElementArea = 0;
85   _hypMaxElementArea = NULL;
86   _hypLengthFromEdges = NULL;
87   myTool = 0;
88 }
89
90 //=============================================================================
91 /*!
92  *  
93  */
94 //=============================================================================
95
96 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
97 {
98   MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
99 }
100
101 //=============================================================================
102 /*!
103  *  
104  */
105 //=============================================================================
106
107 bool StdMeshers_MEFISTO_2D::CheckHypothesis
108                          (SMESH_Mesh&                          aMesh,
109                           const TopoDS_Shape&                  aShape,
110                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
111 {
112   _hypMaxElementArea = NULL;
113   _hypLengthFromEdges = NULL;
114   _edgeLength = 0;
115   _maxElementArea = 0;
116
117   list <const SMESHDS_Hypothesis * >::const_iterator itl;
118   const SMESHDS_Hypothesis *theHyp;
119
120   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
121   int nbHyp = hyps.size();
122   if (!nbHyp)
123   {
124     aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
125     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
126   }
127
128   itl = hyps.begin();
129   theHyp = (*itl); // use only the first hypothesis
130
131   string hypName = theHyp->GetName();
132
133   bool isOk = false;
134
135   if (hypName == "MaxElementArea")
136   {
137     _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
138     ASSERT(_hypMaxElementArea);
139     _maxElementArea = _hypMaxElementArea->GetMaxArea();
140     isOk = true;
141     aStatus = SMESH_Hypothesis::HYP_OK;
142   }
143
144   else if (hypName == "LengthFromEdges")
145   {
146     _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
147     ASSERT(_hypLengthFromEdges);
148     isOk = true;
149     aStatus = SMESH_Hypothesis::HYP_OK;
150   }
151   else
152     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
153
154   if (isOk)
155   {
156     isOk = false;
157     if (_maxElementArea > 0)
158     {
159       //_edgeLength = 2 * sqrt(_maxElementArea);        // triangles : minorant
160       _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
161       isOk = true;
162     }
163     else
164       isOk = (_hypLengthFromEdges != NULL);     // **** check mode
165     if (!isOk)
166       aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
167   }
168
169   return isOk;
170 }
171
172 //=============================================================================
173 /*!
174  *  
175  */
176 //=============================================================================
177
178 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
179 {
180   MESSAGE("StdMeshers_MEFISTO_2D::Compute");
181
182   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
183
184   // helper builds quadratic mesh if necessary
185   SMESH_MesherHelper helper(aMesh);
186   myTool = &helper;
187   _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
188   const bool ignoreMediumNodes = _quadraticMesh;
189
190   // get all edges of a face
191   TError problem;
192   TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
193   int nbWires = wires.size();
194   if ( problem && !problem->IsOK() ) return error( problem );
195   if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
196   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
197     return error(COMPERR_BAD_INPUT_MESH,
198                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
199
200   // compute average edge length
201   if (!_hypMaxElementArea)
202   {
203     _edgeLength = 0;
204     int nbSegments = 0;
205     for ( int iW = 0; iW < nbWires; ++iW )
206     {
207       StdMeshers_FaceSidePtr wire = wires[ iW ];
208       _edgeLength += wire->Length();
209       nbSegments  += wire->NbSegments();
210     }
211     if ( nbSegments )
212       _edgeLength /= nbSegments;
213   }
214
215   if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
216     _edgeLength = 100;
217
218   Z nblf;                 //nombre de lignes fermees (enveloppe en tete)
219   Z *nudslf = NULL;       //numero du dernier sommet de chaque ligne fermee
220   R2 *uvslf = NULL;       
221   Z nbpti = 0;            //nombre points internes futurs sommets de la triangulation
222   R2 *uvpti = NULL;
223   
224   Z nbst;
225   R2 *uvst = NULL;
226   Z nbt;
227   Z *nust = NULL;
228   Z ierr = 0;
229
230   Z nutysu = 1;           // 1: il existe un fonction areteideale_()
231   // Z  nutysu=0;         // 0: on utilise aretmx
232   R aretmx = _edgeLength; // longueur max aretes future triangulation
233   
234   nblf = nbWires;
235   
236   nudslf = new Z[1 + nblf];
237   nudslf[0] = 0;
238   int iw = 1;
239   int nbpnt = 0;
240
241   // count nb of input points
242   for ( int iW = 0; iW < nbWires; ++iW )
243   {
244     nbpnt += wires[iW]->NbPoints() - 1;
245     nudslf[iw++] = nbpnt;
246   }
247
248   uvslf = new R2[nudslf[nblf]];
249
250   double scalex, scaley;
251   ComputeScaleOnFace(aMesh, F, scalex, scaley);
252
253   // correspondence mefisto index --> Nodes
254   vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
255
256   bool isOk = false;
257
258   // fill input points UV
259   if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
260   {
261     // Compute
262     aptrte(nutysu, aretmx,
263            nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
264
265     if (ierr == 0)
266     {
267       MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
268       MESSAGE("                                    Node Number " << nbst);
269       StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
270       isOk = true;
271     }
272     else
273     {
274       error(ierr,"Error in Triangulation (aptrte())");
275     }
276   }
277   if (nudslf != NULL) delete[]nudslf;
278   if (uvslf != NULL)  delete[]uvslf;
279   if (uvst != NULL)   delete[]uvst;
280   if (nust != NULL)   delete[]nust;
281
282   return isOk;
283 }
284
285 //=======================================================================
286 //function : fixOverlappedLinkUV
287 //purpose  : prevent failure due to overlapped adjacent links
288 //=======================================================================
289
290 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
291 {
292   gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
293   gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
294
295   double tol2 = DBL_MIN * DBL_MIN;
296   double sqMod1 = v1.SquareModulus();
297   if ( sqMod1 <= tol2 ) return false;
298   double sqMod2 = v2.SquareModulus();
299   if ( sqMod2 <= tol2 ) return false;
300
301   double dot = v1*v2;
302
303   // check sinus >= 1.e-3
304   const double minSin = 1.e-3;
305   if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
306     MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
307     v1.SetCoord( -v1.Y(), v1.X() );
308     double delta = sqrt( sqMod1 ) * minSin;
309     if ( v1.X() < 0 )
310       uv0.x -= delta;
311     else
312       uv0.x += delta;
313     if ( v1.Y() < 0 )
314       uv0.y -= delta;
315     else
316       uv0.y += delta;
317 // #ifdef _DEBUG_
318 //     MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
319 //     MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
320 //       "v2( " << v2.X() << " " << v2.Y() << " ) ");
321 //    MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
322 //     v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
323 //     v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
324 //     gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
325 //     sqMod1 = v1.SquareModulus();
326 //     sqMod2 = v2.SquareModulus();
327 //     dot = v1*v2;
328 //     double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
329 //     MESSAGE("NEW SIN: " << sin);
330 // #endif
331     return true;
332   }
333   return false;
334 }
335
336 //=======================================================================
337 //function : fixCommonVertexUV
338 //purpose  : 
339 //=======================================================================
340
341 static bool fixCommonVertexUV (R2 &                 theUV,
342                                const TopoDS_Vertex& theV,
343                                const TopoDS_Face&   theF,
344                                const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
345                                SMESH_Mesh &         theMesh,
346                                const double         theScaleX,
347                                const double         theScaleY,
348                                const bool           theCreateQuadratic)
349 {
350   if( !theVWMap.Contains( theV )) return false;
351
352   // check if there is another wire sharing theV
353   const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
354   TopTools_ListIteratorOfListOfShape aWIt;
355   TopTools_MapOfShape aWires;
356   for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
357     aWires.Add( aWIt.Value() );
358   if ( aWires.Extent() < 2 ) return false;
359
360   TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
361   TopoDS_Shape anInnerWire;
362   for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
363     if ( !anOuterWire.IsSame( aWIt.Value() ))
364       anInnerWire = aWIt.Value();
365
366   TopTools_ListOfShape EList;
367   list< double >       UList;
368
369   // find edges of theW sharing theV
370   // and find 2d normal to them at theV
371   gp_Vec2d N(0.,0.);
372   TopoDS_Iterator itE( anInnerWire );
373   for (  ; itE.More(); itE.Next() )
374   {
375     const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
376     TopoDS_Iterator itV( E );
377     for ( ; itV.More(); itV.Next() )
378     {
379       const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
380       if ( !V.IsSame( theV ))
381         continue;
382       EList.Append( E );
383       Standard_Real u = BRep_Tool::Parameter( V, E );
384       UList.push_back( u );
385       double f, l;
386       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
387       gp_Vec2d d1;
388       gp_Pnt2d p;
389       C2d->D1( u, p, d1 );
390       gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
391       if ( E.Orientation() == TopAbs_REVERSED )
392         n.Reverse();
393       N += n.Normalized();
394     }
395   }
396
397   // define step size by which to move theUV
398
399   gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
400   gp_Pnt2d thisUV( theUV.x, theUV.y );
401   double maxDist = -DBL_MAX;
402   TopTools_ListIteratorOfListOfShape aEIt (EList);
403   list< double >::iterator aUIt = UList.begin();
404   for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
405   {
406     const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
407     double f, l;
408     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
409
410     double umin = DBL_MAX, umax = -DBL_MAX;
411     SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
412     if ( !nIt->more() ) // no nodes on edge, only on vertices
413     {
414       umin = l;
415       umax = f;
416     }
417     else {
418       while ( nIt->more() ) {
419         const SMDS_MeshNode* node = nIt->next();
420         // check if node is medium
421         if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
422           continue;
423         const SMDS_EdgePosition* epos =
424           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
425         double u = epos->GetUParameter();
426         if ( u < umin )
427           umin = u;
428         if ( u > umax )
429           umax = u;
430       }
431     }
432     bool isFirstCommon = ( *aUIt == f );
433     gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
434     double dist = thisUV.SquareDistance( uv );
435     if ( dist > maxDist ) {
436       maxDist = dist;
437       nextUV  = uv;
438     }
439   }
440   R2 uv0, uv1, uv2;
441   uv0.x = thisUV.X();   uv0.y = thisUV.Y();
442   uv1.x = nextUV.X();   uv1.y = nextUV.Y(); 
443   uv2.x = thisUV.X();   uv2.y = thisUV.Y();
444
445   uv1.x *= theScaleX;   uv1.y *= theScaleY; 
446
447   if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
448   {
449     double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
450
451     // move theUV along the normal by the step
452
453     N *= step;
454
455     MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
456             << ") by (" << N.X() << " " << N.Y() << ")" 
457             << endl << "--- MAX DIST " << maxDist);
458
459     theUV.x += N.X();
460     theUV.y += N.Y();
461
462     return true;
463   }
464   return false;
465 }
466
467 //=============================================================================
468 /*!
469  *  
470  */
471 //=============================================================================
472
473 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector &                 wires,
474                                        R2 *                          uvslf,
475                                        vector<const SMDS_MeshNode*>& mefistoToDS,
476                                        double                        scalex,
477                                        double                        scaley)
478 {
479   // to avoid passing same uv points for a vertex common to 2 wires
480   TopoDS_Face F;
481   TopTools_IndexedDataMapOfShapeListOfShape VWMap;
482   if ( wires.size() > 1 )
483   {
484     F = TopoDS::Face( myTool->GetSubShape() );
485     TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
486     int nbVertices = 0;
487     for ( int iW = 0; iW < wires.size(); ++iW )
488       nbVertices += wires[ iW ]->NbEdges();
489     if ( nbVertices == VWMap.Extent() )
490       VWMap.Clear(); // wires have no common vertices
491   }
492
493   int m = 0;
494
495   for ( int iW = 0; iW < wires.size(); ++iW )
496   {
497     const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
498     if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
499       return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
500                    << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
501                    << ", probably because of invalid node parameters on geom edges");
502     }
503     if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
504       MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
505       return error("Internal error");
506     }
507
508     list< int > mOnVertex;
509     vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
510     for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
511     {
512       // bind mefisto ID to node
513       mefistoToDS[m] = uvPt->node;
514       // set UV
515       uvslf[m].x = uvPt->u * scalex;
516       uvslf[m].y = uvPt->v * scaley;
517       if ( uvPt->node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
518         mOnVertex.push_back( m );
519       m++;
520     }
521
522     int mFirst = mOnVertex.front(), mLast = m - 1;
523     list< int >::iterator mIt = mOnVertex.begin();
524     for ( ; mIt != mOnVertex.end(); ++mIt)
525     {
526       int m = *mIt;
527       if ( iW && !VWMap.IsEmpty()) { // except outer wire
528         // avoid passing same uv point for a vertex common to 2 wires
529         int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
530         TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
531         if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
532                                 scalex, scaley, _quadraticMesh )) {
533           myNodesOnCommonV.push_back( mefistoToDS[m] );
534           continue;
535         }
536       }
537       // prevent failure on overlapped adjacent links,
538       // check only links ending in vertex nodes
539       int mB = m - 1, mA = m + 1; // indices Before and After
540       if ( mB < mFirst ) mB = mLast;
541       if ( mA > mLast )  mA = mFirst;
542       fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
543     }
544   }
545
546   return true;
547 }
548
549 //=============================================================================
550 /*!
551  *  
552  */
553 //=============================================================================
554
555 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh &        aMesh,
556                                                const TopoDS_Face & aFace,
557                                                double &            scalex,
558                                                double &            scaley)
559 {
560   TopoDS_Wire W = BRepTools::OuterWire(aFace);
561
562   double xmin = 1.e300;         // min & max of face 2D parametric coord.
563   double xmax = -1.e300;
564   double ymin = 1.e300;
565   double ymax = -1.e300;
566   int nbp = 23;
567   scalex = 1;
568   scaley = 1;
569
570   TopExp_Explorer wexp(W, TopAbs_EDGE);
571   for ( ; wexp.More(); wexp.Next())
572   {
573     const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
574     double f, l;
575     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
576     if ( C2d.IsNull() ) continue;
577     double du = (l - f) / double (nbp);
578     for (int i = 0; i <= nbp; i++)
579     {
580       double param = f + double (i) * du;
581       gp_Pnt2d p = C2d->Value(param);
582       if (p.X() < xmin)
583         xmin = p.X();
584       if (p.X() > xmax)
585         xmax = p.X();
586       if (p.Y() < ymin)
587         ymin = p.Y();
588       if (p.Y() > ymax)
589         ymax = p.Y();
590       //    MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
591     }
592   }
593   //   SCRUTE(xmin);
594   //   SCRUTE(xmax);
595   //   SCRUTE(ymin);
596   //   SCRUTE(ymax);
597   double xmoy = (xmax + xmin) / 2.;
598   double ymoy = (ymax + ymin) / 2.;
599   double xsize = xmax - xmin;
600   double ysize = ymax - ymin;
601
602   TopLoc_Location L;
603   Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L);       // 3D surface
604
605   double length_x = 0;
606   double length_y = 0;
607   gp_Pnt PX0 = S->Value(xmin, ymoy);
608   gp_Pnt PY0 = S->Value(xmoy, ymin);
609   double dx = xsize / double (nbp);
610   double dy = ysize / double (nbp);
611   for (int i = 1; i <= nbp; i++)
612   {
613     double x = xmin + double (i) * dx;
614     gp_Pnt PX = S->Value(x, ymoy);
615     double y = ymin + double (i) * dy;
616     gp_Pnt PY = S->Value(xmoy, y);
617     length_x += PX.Distance(PX0);
618     length_y += PY.Distance(PY0);
619     PX0 = PX;
620     PY0 = PY;
621   }
622   scalex = length_x / xsize;
623   scaley = length_y / ysize;
624 //   SCRUTE(xsize);
625 //   SCRUTE(ysize);
626   double xyratio = xsize*scalex/(ysize*scaley);
627   const double maxratio = 1.e2;
628   //SCRUTE(xyratio);
629   if (xyratio > maxratio) {
630     SCRUTE( scaley );
631     scaley *= xyratio / maxratio;
632     SCRUTE( scaley );
633   }
634   else if (xyratio < 1./maxratio) {
635     SCRUTE( scalex );
636     scalex *= 1 / xyratio / maxratio;
637     SCRUTE( scalex );
638   }
639   ASSERT(scalex);
640   ASSERT(scaley);
641 }
642
643 //=============================================================================
644 /*!
645  *  
646  */
647 //=============================================================================
648
649 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
650                                         vector< const SMDS_MeshNode*>&mefistoToDS,
651                                         double scalex, double scaley)
652 {
653   SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
654   int faceID = myTool->GetSubShapeID();
655
656   TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
657   Handle(Geom_Surface) S = BRep_Tool::Surface( F );
658
659   Z n = mefistoToDS.size(); // nb input points
660   mefistoToDS.resize( nbst );
661   for ( ; n < nbst; n++)
662   {
663     if (!mefistoToDS[n])
664     {
665       double u = uvst[n][0] / scalex;
666       double v = uvst[n][1] / scaley;
667       gp_Pnt P = S->Value(u, v);
668
669       SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
670       meshDS->SetNodeOnFace(node, faceID, u, v);
671
672       //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
673       mefistoToDS[n] = node;
674       //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
675     }
676   }
677
678   Z m = 0;
679
680   // triangle points must be in trigonometric order if face is Forward
681   // else they must be put clockwise
682
683   bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );
684
685   for (n = 1; n <= nbt; n++)
686   {
687     const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
688     const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
689     const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];
690
691     SMDS_MeshElement * elt;
692     if (triangleIsWellOriented)
693       elt = myTool->AddFace(n1, n2, n3);
694     else
695       elt = myTool->AddFace(n1, n3, n2);
696
697     meshDS->SetMeshElementOnShape(elt, faceID);
698     m++;
699   }
700
701   // remove bad elements built on vertices shared by wires
702
703   list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
704   for ( ; itN != myNodesOnCommonV.end(); itN++ )
705   {
706     const SMDS_MeshNode* node = *itN;
707     SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
708     while ( invElemIt->more() )
709     {
710       const SMDS_MeshElement* elem = invElemIt->next();
711       SMDS_ElemIteratorPtr itN = elem->nodesIterator();
712       int nbSame = 0;
713       while ( itN->more() )
714         if ( itN->next() == node)
715           nbSame++;
716       if (nbSame > 1) {
717         MESSAGE( "RM bad element " << elem->GetID());
718         meshDS->RemoveElement( elem );
719       }
720     }
721   }
722 }