Salome HOME
Update copyright information
[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 //  $Header$
28 //
29 #include "StdMeshers_MEFISTO_2D.hxx"
30
31 #include "SMESH_Gen.hxx"
32 #include "SMESH_Mesh.hxx"
33 #include "SMESH_subMesh.hxx"
34 #include "SMESH_Block.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_Comment.hxx"
37
38 #include "StdMeshers_FaceSide.hxx"
39 #include "StdMeshers_MaxElementArea.hxx"
40 #include "StdMeshers_LengthFromEdges.hxx"
41
42 #include "Rn.h"
43 #include "aptrte.h"
44
45 #include "SMDS_MeshElement.hxx"
46 #include "SMDS_MeshNode.hxx"
47 #include "SMDS_EdgePosition.hxx"
48 #include "SMDS_FacePosition.hxx"
49
50 #include "utilities.h"
51
52 #include <BRepTools.hxx>
53 #include <BRep_Tool.hxx>
54 #include <Geom2d_Curve.hxx>
55 #include <Geom_Surface.hxx>
56 #include <TopExp.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopTools_ListOfShape.hxx>
60 #include <TopTools_MapOfShape.hxx>
61 #include <TopoDS.hxx>
62 #include <TopoDS_Edge.hxx>
63 #include <TopoDS_Face.hxx>
64 #include <TopoDS_Iterator.hxx>
65 #include <gp_Pnt2d.hxx>
66
67 using namespace std;
68
69 //=============================================================================
70 /*!
71  *  
72  */
73 //=============================================================================
74
75 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
76   SMESH_2D_Algo(hypId, studyId, gen)
77 {
78   MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
79   _name = "MEFISTO_2D";
80   _shapeType = (1 << TopAbs_FACE);
81   _compatibleHypothesis.push_back("MaxElementArea");
82   _compatibleHypothesis.push_back("LengthFromEdges");
83
84   _edgeLength = 0;
85   _maxElementArea = 0;
86   _hypMaxElementArea = NULL;
87   _hypLengthFromEdges = NULL;
88   myTool = 0;
89 }
90
91 //=============================================================================
92 /*!
93  *  
94  */
95 //=============================================================================
96
97 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
98 {
99   MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
100 }
101
102 //=============================================================================
103 /*!
104  *  
105  */
106 //=============================================================================
107
108 bool StdMeshers_MEFISTO_2D::CheckHypothesis
109                          (SMESH_Mesh&                          aMesh,
110                           const TopoDS_Shape&                  aShape,
111                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
112 {
113   _hypMaxElementArea = NULL;
114   _hypLengthFromEdges = NULL;
115   _edgeLength = 0;
116   _maxElementArea = 0;
117
118   list <const SMESHDS_Hypothesis * >::const_iterator itl;
119   const SMESHDS_Hypothesis *theHyp;
120
121   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
122   int nbHyp = hyps.size();
123   if (!nbHyp)
124   {
125     aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
126     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
127   }
128
129   itl = hyps.begin();
130   theHyp = (*itl); // use only the first hypothesis
131
132   string hypName = theHyp->GetName();
133
134   bool isOk = false;
135
136   if (hypName == "MaxElementArea")
137   {
138     _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
139     ASSERT(_hypMaxElementArea);
140     _maxElementArea = _hypMaxElementArea->GetMaxArea();
141     isOk = true;
142     aStatus = SMESH_Hypothesis::HYP_OK;
143   }
144
145   else if (hypName == "LengthFromEdges")
146   {
147     _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
148     ASSERT(_hypLengthFromEdges);
149     isOk = true;
150     aStatus = SMESH_Hypothesis::HYP_OK;
151   }
152   else
153     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
154
155   if (isOk)
156   {
157     isOk = false;
158     if (_maxElementArea > 0)
159     {
160       //_edgeLength = 2 * sqrt(_maxElementArea);        // triangles : minorant
161       _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
162       isOk = true;
163     }
164     else
165       isOk = (_hypLengthFromEdges != NULL);     // **** check mode
166     if (!isOk)
167       aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
168   }
169
170   return isOk;
171 }
172
173 //=============================================================================
174 /*!
175  *  
176  */
177 //=============================================================================
178
179 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
180 {
181   MESSAGE("StdMeshers_MEFISTO_2D::Compute");
182
183   TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
184
185   // helper builds quadratic mesh if necessary
186   SMESH_MesherHelper helper(aMesh);
187   myTool = &helper;
188   _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
189   const bool ignoreMediumNodes = _quadraticMesh;
190
191   // get all edges of a face
192   TError problem;
193   TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
194   int nbWires = wires.size();
195   if ( problem && !problem->IsOK() ) return error( problem );
196   if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
197   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
198     return error(COMPERR_BAD_INPUT_MESH,
199                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
200
201   // compute average edge length
202   if (!_hypMaxElementArea)
203   {
204     _edgeLength = 0;
205     int nbSegments = 0;
206     for ( int iW = 0; iW < nbWires; ++iW )
207     {
208       StdMeshers_FaceSidePtr wire = wires[ iW ];
209       _edgeLength += wire->Length();
210       nbSegments  += wire->NbSegments();
211     }
212     if ( nbSegments )
213       _edgeLength /= nbSegments;
214   }
215
216   if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
217     _edgeLength = 100;
218
219   Z nblf;                 //nombre de lignes fermees (enveloppe en tete)
220   Z *nudslf = NULL;       //numero du dernier sommet de chaque ligne fermee
221   R2 *uvslf = NULL;       
222   Z nbpti = 0;            //nombre points internes futurs sommets de la triangulation
223   R2 *uvpti = NULL;
224   
225   Z nbst;
226   R2 *uvst = NULL;
227   Z nbt;
228   Z *nust = NULL;
229   Z ierr = 0;
230
231   Z nutysu = 1;           // 1: il existe un fonction areteideale_()
232   // Z  nutysu=0;         // 0: on utilise aretmx
233   R aretmx = _edgeLength; // longueur max aretes future triangulation
234   
235   nblf = nbWires;
236   
237   nudslf = new Z[1 + nblf];
238   nudslf[0] = 0;
239   int iw = 1;
240   int nbpnt = 0;
241
242   // count nb of input points
243   for ( int iW = 0; iW < nbWires; ++iW )
244   {
245     nbpnt += wires[iW]->NbPoints() - 1;
246     nudslf[iw++] = nbpnt;
247   }
248
249   uvslf = new R2[nudslf[nblf]];
250
251   double scalex, scaley;
252   ComputeScaleOnFace(aMesh, F, scalex, scaley);
253
254   // correspondence mefisto index --> Nodes
255   vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
256
257   bool isOk = false;
258
259   // fill input points UV
260   if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
261   {
262     // Compute
263     aptrte(nutysu, aretmx,
264            nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
265
266     if (ierr == 0)
267     {
268       MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
269       MESSAGE("                                    Node Number " << nbst);
270       StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
271       isOk = true;
272     }
273     else
274     {
275       error(ierr,"Error in Triangulation (aptrte())");
276     }
277   }
278   if (nudslf != NULL) delete[]nudslf;
279   if (uvslf != NULL)  delete[]uvslf;
280   if (uvst != NULL)   delete[]uvst;
281   if (nust != NULL)   delete[]nust;
282
283   return isOk;
284 }
285
286 //=======================================================================
287 //function : fixOverlappedLinkUV
288 //purpose  : prevent failure due to overlapped adjacent links
289 //=======================================================================
290
291 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
292 {
293   gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
294   gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
295
296   double tol2 = DBL_MIN * DBL_MIN;
297   double sqMod1 = v1.SquareModulus();
298   if ( sqMod1 <= tol2 ) return false;
299   double sqMod2 = v2.SquareModulus();
300   if ( sqMod2 <= tol2 ) return false;
301
302   double dot = v1*v2;
303
304   // check sinus >= 1.e-3
305   const double minSin = 1.e-3;
306   if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
307     MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
308     v1.SetCoord( -v1.Y(), v1.X() );
309     double delta = sqrt( sqMod1 ) * minSin;
310     if ( v1.X() < 0 )
311       uv0.x -= delta;
312     else
313       uv0.x += delta;
314     if ( v1.Y() < 0 )
315       uv0.y -= delta;
316     else
317       uv0.y += delta;
318 // #ifdef _DEBUG_
319 //     MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
320 //     MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
321 //       "v2( " << v2.X() << " " << v2.Y() << " ) ");
322 //    MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
323 //     v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
324 //     v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
325 //     gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
326 //     sqMod1 = v1.SquareModulus();
327 //     sqMod2 = v2.SquareModulus();
328 //     dot = v1*v2;
329 //     double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
330 //     MESSAGE("NEW SIN: " << sin);
331 // #endif
332     return true;
333   }
334   return false;
335 }
336
337 //=======================================================================
338 //function : fixCommonVertexUV
339 //purpose  : 
340 //=======================================================================
341
342 static bool fixCommonVertexUV (R2 &                 theUV,
343                                const TopoDS_Vertex& theV,
344                                const TopoDS_Face&   theF,
345                                const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
346                                SMESH_Mesh &         theMesh,
347                                const double         theScaleX,
348                                const double         theScaleY,
349                                const bool           theCreateQuadratic)
350 {
351   if( !theVWMap.Contains( theV )) return false;
352
353   // check if there is another wire sharing theV
354   const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
355   TopTools_ListIteratorOfListOfShape aWIt;
356   TopTools_MapOfShape aWires;
357   for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
358     aWires.Add( aWIt.Value() );
359   if ( aWires.Extent() < 2 ) return false;
360
361   TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
362   TopoDS_Shape anInnerWire;
363   for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
364     if ( !anOuterWire.IsSame( aWIt.Value() ))
365       anInnerWire = aWIt.Value();
366
367   TopTools_ListOfShape EList;
368   list< double >       UList;
369
370   // find edges of theW sharing theV
371   // and find 2d normal to them at theV
372   gp_Vec2d N(0.,0.);
373   TopoDS_Iterator itE( anInnerWire );
374   for (  ; itE.More(); itE.Next() )
375   {
376     const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
377     TopoDS_Iterator itV( E );
378     for ( ; itV.More(); itV.Next() )
379     {
380       const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
381       if ( !V.IsSame( theV ))
382         continue;
383       EList.Append( E );
384       Standard_Real u = BRep_Tool::Parameter( V, E );
385       UList.push_back( u );
386       double f, l;
387       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
388       gp_Vec2d d1;
389       gp_Pnt2d p;
390       C2d->D1( u, p, d1 );
391       gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
392       if ( E.Orientation() == TopAbs_REVERSED )
393         n.Reverse();
394       N += n.Normalized();
395     }
396   }
397
398   // define step size by which to move theUV
399
400   gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
401   gp_Pnt2d thisUV( theUV.x, theUV.y );
402   double maxDist = -DBL_MAX;
403   TopTools_ListIteratorOfListOfShape aEIt (EList);
404   list< double >::iterator aUIt = UList.begin();
405   for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
406   {
407     const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
408     double f, l;
409     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
410
411     double umin = DBL_MAX, umax = -DBL_MAX;
412     SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
413     if ( !nIt->more() ) // no nodes on edge, only on vertices
414     {
415       umin = l;
416       umax = f;
417     }
418     else {
419       while ( nIt->more() ) {
420         const SMDS_MeshNode* node = nIt->next();
421         // check if node is medium
422         if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
423           continue;
424         const SMDS_EdgePosition* epos =
425           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
426         double u = epos->GetUParameter();
427         if ( u < umin )
428           umin = u;
429         if ( u > umax )
430           umax = u;
431       }
432     }
433     bool isFirstCommon = ( *aUIt == f );
434     gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
435     double dist = thisUV.SquareDistance( uv );
436     if ( dist > maxDist ) {
437       maxDist = dist;
438       nextUV  = uv;
439     }
440   }
441   R2 uv0, uv1, uv2;
442   uv0.x = thisUV.X();   uv0.y = thisUV.Y();
443   uv1.x = nextUV.X();   uv1.y = nextUV.Y(); 
444   uv2.x = thisUV.X();   uv2.y = thisUV.Y();
445
446   uv1.x *= theScaleX;   uv1.y *= theScaleY; 
447
448   if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
449   {
450     double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
451
452     // move theUV along the normal by the step
453
454     N *= step;
455
456     MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
457             << ") by (" << N.X() << " " << N.Y() << ")" 
458             << endl << "--- MAX DIST " << maxDist);
459
460     theUV.x += N.X();
461     theUV.y += N.Y();
462
463     return true;
464   }
465   return false;
466 }
467
468 //=============================================================================
469 /*!
470  *  
471  */
472 //=============================================================================
473
474 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector &                 wires,
475                                        R2 *                          uvslf,
476                                        vector<const SMDS_MeshNode*>& mefistoToDS,
477                                        double                        scalex,
478                                        double                        scaley)
479 {
480   // to avoid passing same uv points for a vertex common to 2 wires
481   TopoDS_Face F;
482   TopTools_IndexedDataMapOfShapeListOfShape VWMap;
483   if ( wires.size() > 1 )
484   {
485     F = TopoDS::Face( myTool->GetSubShape() );
486     TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
487     int nbVertices = 0;
488     for ( int iW = 0; iW < wires.size(); ++iW )
489       nbVertices += wires[ iW ]->NbEdges();
490     if ( nbVertices == VWMap.Extent() )
491       VWMap.Clear(); // wires have no common vertices
492   }
493
494   int m = 0;
495   list< int > mOnVertex;
496
497   for ( int iW = 0; iW < wires.size(); ++iW )
498   {
499     const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
500     if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
501       return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
502                    << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
503                    << ", probably because of invalid node parameters on geom edges");
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 }