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