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