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