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