Salome HOME
SMH: Preparation version 3.0.0 - merge (HEAD+POLYWORK)
[modules/smesh.git] / src / Controls / SMESH_Controls.cxx
1 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3 // 
4 //  This library is free software; you can redistribute it and/or 
5 //  modify it under the terms of the GNU Lesser General Public 
6 //  License as published by the Free Software Foundation; either
7 //  version 2.1 of the License. 
8 // 
9 //  This library is distributed in the hope that it will be useful, 
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 //  Lesser General Public License for more details.
13 // 
14 //  You should have received a copy of the GNU Lesser General Public 
15 //  License along with this library; if not, write to the Free Software 
16 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
17 // 
18 //  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
19
20 #include "SMESH_ControlsDef.hxx"
21
22 #include <set>
23
24 #include <BRep_Tool.hxx>
25 #include <gp_Ax3.hxx>
26 #include <gp_Cylinder.hxx>
27 #include <gp_Dir.hxx>
28 #include <gp_Pnt.hxx>
29 #include <gp_Pln.hxx>
30 #include <gp_Vec.hxx>
31 #include <gp_XYZ.hxx>
32 #include <Geom_Plane.hxx>
33 #include <Geom_CylindricalSurface.hxx>
34 #include <Precision.hxx>
35 #include <TColgp_Array1OfXYZ.hxx>
36 #include <TColStd_MapOfInteger.hxx>
37 #include <TColStd_SequenceOfAsciiString.hxx>
38 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
39 #include <TopAbs.hxx>
40 #include <TopoDS.hxx>
41 #include <TopoDS_Face.hxx>
42 #include <TopoDS_Shape.hxx>
43
44 #include "SMDS_Mesh.hxx"
45 #include "SMDS_Iterator.hxx"
46 #include "SMDS_MeshElement.hxx"
47 #include "SMDS_MeshNode.hxx"
48 #include "SMDS_VolumeTool.hxx"
49
50
51 /*
52                             AUXILIARY METHODS 
53 */
54
55 namespace{
56   inline double getAngle( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 )
57   {
58     gp_Vec v1( P1 - P2 ), v2( P3 - P2 );
59     
60     return v1.Magnitude() < gp::Resolution() ||
61       v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 );
62   }
63
64   inline double getArea( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 )
65   {
66     gp_Vec aVec1( P2 - P1 );
67     gp_Vec aVec2( P3 - P1 );
68     return ( aVec1 ^ aVec2 ).Magnitude() * 0.5;
69   }
70
71   inline double getArea( const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3 )
72   {
73     return getArea( P1.XYZ(), P2.XYZ(), P3.XYZ() );
74   }
75
76
77
78   inline double getDistance( const gp_XYZ& P1, const gp_XYZ& P2 )
79   {
80     double aDist = gp_Pnt( P1 ).Distance( gp_Pnt( P2 ) );
81     return aDist;
82   }
83
84   int getNbMultiConnection( const SMDS_Mesh* theMesh, const int theId )
85   {
86     if ( theMesh == 0 )
87       return 0;
88     
89     const SMDS_MeshElement* anEdge = theMesh->FindElement( theId );
90     if ( anEdge == 0 || anEdge->GetType() != SMDSAbs_Edge || anEdge->NbNodes() != 2 )
91       return 0;
92     
93     TColStd_MapOfInteger aMap;
94     
95     int aResult = 0;
96     SMDS_ElemIteratorPtr anIter = anEdge->nodesIterator();
97     if ( anIter != 0 ) {
98       while( anIter->more() ) {
99         const SMDS_MeshNode* aNode = (SMDS_MeshNode*)anIter->next();
100         if ( aNode == 0 )
101           return 0;
102         SMDS_ElemIteratorPtr anElemIter = aNode->GetInverseElementIterator();
103         while( anElemIter->more() ) {
104           const SMDS_MeshElement* anElem = anElemIter->next();
105           if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) {
106             int anId = anElem->GetID();
107             
108             if ( anIter->more() )              // i.e. first node
109               aMap.Add( anId );
110             else if ( aMap.Contains( anId ) )
111               aResult++;
112           }
113         }
114       }
115     }
116     
117     return aResult;
118   }
119
120 }
121
122
123
124 using namespace SMESH::Controls;
125
126 /*
127                                 FUNCTORS
128 */
129
130 /*
131   Class       : NumericalFunctor
132   Description : Base class for numerical functors
133 */
134 NumericalFunctor::NumericalFunctor():
135   myMesh(NULL)
136 {
137   myPrecision = -1;
138 }
139
140 void NumericalFunctor::SetMesh( const SMDS_Mesh* theMesh )
141 {
142   myMesh = theMesh;
143 }
144
145 bool NumericalFunctor::GetPoints(const int theId,
146                                  TSequenceOfXYZ& theRes ) const
147 {
148   theRes.clear();
149
150   if ( myMesh == 0 )
151     return false;
152
153   return GetPoints( myMesh->FindElement( theId ), theRes );
154 }
155
156 bool NumericalFunctor::GetPoints(const SMDS_MeshElement* anElem,
157                                  TSequenceOfXYZ& theRes )
158 {
159   theRes.clear();
160
161   if ( anElem == 0)
162     return false;
163
164   // Get nodes of the element
165   SMDS_ElemIteratorPtr anIter = anElem->nodesIterator();
166   if ( anIter != 0 )
167   {
168     while( anIter->more() )
169     {
170       const SMDS_MeshNode* aNode = (SMDS_MeshNode*)anIter->next();
171       if ( aNode != 0 ){
172         theRes.push_back( gp_XYZ( aNode->X(), aNode->Y(), aNode->Z() ) );
173       }
174     }
175   }
176
177   return true;
178 }
179
180 long  NumericalFunctor::GetPrecision() const
181 {
182   return myPrecision;
183 }
184
185 void  NumericalFunctor::SetPrecision( const long thePrecision )
186 {
187   myPrecision = thePrecision;
188 }
189
190 double NumericalFunctor::GetValue( long theId )
191 {
192   TSequenceOfXYZ P;
193   if ( GetPoints( theId, P ))
194   {
195     double aVal = GetValue( P );
196     if ( myPrecision >= 0 )
197     {
198       double prec = pow( 10., (double)( myPrecision ) );
199       aVal = floor( aVal * prec + 0.5 ) / prec;
200     }
201     return aVal;
202   }
203
204   return 0.;
205 }
206
207 /*
208   Class       : MinimumAngle
209   Description : Functor for calculation of minimum angle
210 */
211
212 double MinimumAngle::GetValue( const TSequenceOfXYZ& P )
213 {
214   double aMin;
215
216   if (P.size() <3)
217     return 0.;
218
219   aMin = getAngle(P( P.size() ), P( 1 ), P( 2 ));
220   aMin = Min(aMin,getAngle(P( P.size()-1 ), P( P.size() ), P( 1 )));
221   
222   for (int i=2; i<P.size();i++){
223       double A0 = getAngle( P( i-1 ), P( i ), P( i+1 ) );
224     aMin = Min(aMin,A0);
225   }
226
227   return aMin * 180 / PI;
228 }
229
230 double MinimumAngle::GetBadRate( double Value, int nbNodes ) const
231 {
232   const double aBestAngle = PI / nbNodes;
233   return ( fabs( aBestAngle - Value ));
234 }
235
236 SMDSAbs_ElementType MinimumAngle::GetType() const
237 {
238   return SMDSAbs_Face;
239 }
240
241
242 /*
243   Class       : AspectRatio
244   Description : Functor for calculating aspect ratio
245 */
246 double AspectRatio::GetValue( const TSequenceOfXYZ& P )
247 {
248   int nbNodes = P.size();
249
250   if ( nbNodes != 3 && nbNodes != 4 )
251     return 0;
252
253   // Compute lengths of the sides
254
255   double aLen[ nbNodes ];
256   for ( int i = 0; i < nbNodes - 1; i++ )
257     aLen[ i ] = getDistance( P( i + 1 ), P( i + 2 ) );
258   aLen[ nbNodes - 1 ] = getDistance( P( 1 ), P( nbNodes ) );
259
260   // Compute aspect ratio
261
262   if ( nbNodes == 3 ) 
263   {
264     double anArea = getArea( P( 1 ), P( 2 ), P( 3 ) );
265     if ( anArea <= Precision::Confusion() )
266       return 0.;
267     double aMaxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) );
268     static double aCoef = sqrt( 3. ) / 4;
269
270     return aCoef * aMaxLen * aMaxLen / anArea;
271   }
272   else
273   {
274     double aMinLen = Min( Min( aLen[ 0 ], aLen[ 1 ] ), Min( aLen[ 2 ], aLen[ 3 ] ) );
275     if ( aMinLen <= Precision::Confusion() )
276       return 0.;
277     double aMaxLen = Max( Max( aLen[ 0 ], aLen[ 1 ] ), Max( aLen[ 2 ], aLen[ 3 ] ) );
278     
279     return aMaxLen / aMinLen;
280   }
281 }
282
283 double AspectRatio::GetBadRate( double Value, int /*nbNodes*/ ) const
284 {
285   // the aspect ratio is in the range [1.0,infinity]
286   // 1.0 = good
287   // infinity = bad
288   return Value / 1000.;
289 }
290
291 SMDSAbs_ElementType AspectRatio::GetType() const
292 {
293   return SMDSAbs_Face;
294 }
295
296
297 /*
298   Class       : AspectRatio3D
299   Description : Functor for calculating aspect ratio
300 */
301 namespace{
302
303   inline double getHalfPerimeter(double theTria[3]){
304     return (theTria[0] + theTria[1] + theTria[2])/2.0;
305   }
306
307   inline double getArea(double theHalfPerim, double theTria[3]){
308     return sqrt(theHalfPerim*
309                 (theHalfPerim-theTria[0])*
310                 (theHalfPerim-theTria[1])*
311                 (theHalfPerim-theTria[2]));
312   }
313
314   inline double getVolume(double theLen[6]){
315     double a2 = theLen[0]*theLen[0];
316     double b2 = theLen[1]*theLen[1];
317     double c2 = theLen[2]*theLen[2];
318     double d2 = theLen[3]*theLen[3];
319     double e2 = theLen[4]*theLen[4];
320     double f2 = theLen[5]*theLen[5];
321     double P = 4.0*a2*b2*d2;
322     double Q = a2*(b2+d2-e2)-b2*(a2+d2-f2)-d2*(a2+b2-c2);
323     double R = (b2+d2-e2)*(a2+d2-f2)*(a2+d2-f2);
324     return sqrt(P-Q+R)/12.0;
325   }
326
327   inline double getVolume2(double theLen[6]){
328     double a2 = theLen[0]*theLen[0];
329     double b2 = theLen[1]*theLen[1];
330     double c2 = theLen[2]*theLen[2];
331     double d2 = theLen[3]*theLen[3];
332     double e2 = theLen[4]*theLen[4];
333     double f2 = theLen[5]*theLen[5];
334
335     double P = a2*e2*(b2+c2+d2+f2-a2-e2);
336     double Q = b2*f2*(a2+c2+d2+e2-b2-f2);
337     double R = c2*d2*(a2+b2+e2+f2-c2-d2);
338     double S = a2*b2*d2+b2*c2*e2+a2*c2*f2+d2*e2*f2;
339     
340     return sqrt(P+Q+R-S)/12.0;
341   }
342
343   inline double getVolume(const TSequenceOfXYZ& P){
344     gp_Vec aVec1( P( 2 ) - P( 1 ) );
345     gp_Vec aVec2( P( 3 ) - P( 1 ) );
346     gp_Vec aVec3( P( 4 ) - P( 1 ) );
347     gp_Vec anAreaVec( aVec1 ^ aVec2 );
348     return fabs(aVec3 * anAreaVec) / 6.0;
349   }
350
351   inline double getMaxHeight(double theLen[6])
352   {
353     double aHeight = max(theLen[0],theLen[1]);
354     aHeight = max(aHeight,theLen[2]);
355     aHeight = max(aHeight,theLen[3]);
356     aHeight = max(aHeight,theLen[4]);
357     aHeight = max(aHeight,theLen[5]);
358     return aHeight;
359   }
360
361 }
362
363 double AspectRatio3D::GetValue( const TSequenceOfXYZ& P )
364 {
365   double aQuality = 0.0;
366   int nbNodes = P.size();
367   switch(nbNodes){
368   case 4:{
369     double aLen[6] = {
370       getDistance(P( 1 ),P( 2 )), // a
371       getDistance(P( 2 ),P( 3 )), // b
372       getDistance(P( 3 ),P( 1 )), // c
373       getDistance(P( 2 ),P( 4 )), // d
374       getDistance(P( 3 ),P( 4 )), // e
375       getDistance(P( 1 ),P( 4 ))  // f
376     };
377     double aTria[4][3] = {
378       {aLen[0],aLen[1],aLen[2]}, // abc
379       {aLen[0],aLen[3],aLen[5]}, // adf
380       {aLen[1],aLen[3],aLen[4]}, // bde
381       {aLen[2],aLen[4],aLen[5]}  // cef
382     };
383     double aSumArea = 0.0;
384     double aHalfPerimeter = getHalfPerimeter(aTria[0]);
385     double anArea = getArea(aHalfPerimeter,aTria[0]);
386     aSumArea += anArea;
387     aHalfPerimeter = getHalfPerimeter(aTria[1]);
388     anArea = getArea(aHalfPerimeter,aTria[1]);
389     aSumArea += anArea;
390     aHalfPerimeter = getHalfPerimeter(aTria[2]);
391     anArea = getArea(aHalfPerimeter,aTria[2]);
392     aSumArea += anArea;
393     aHalfPerimeter = getHalfPerimeter(aTria[3]);
394     anArea = getArea(aHalfPerimeter,aTria[3]);
395     aSumArea += anArea;
396     double aVolume = getVolume(P);
397     //double aVolume = getVolume(aLen);
398     double aHeight = getMaxHeight(aLen);
399     static double aCoeff = sqrt(6.0)/36.0;
400     aQuality = aCoeff*aHeight*aSumArea/aVolume;
401     break;
402   }
403   case 5:{
404     {
405       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 3 ),P( 5 )};
406       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
407     }
408     {
409       gp_XYZ aXYZ[4] = {P( 1 ),P( 3 ),P( 4 ),P( 5 )};
410       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
411     }
412     {
413       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 5 )};
414       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
415     }
416     {
417       gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 4 ),P( 5 )};
418       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
419     }
420     break;
421   }
422   case 6:{
423     {
424       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 6 )};
425       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
426     }
427     {
428       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 3 )};
429       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
430     }
431     {
432       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 6 )};
433       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
434     }
435     {
436       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )};
437       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
438     }
439     {
440       gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 6 )};
441       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
442     }
443     {
444       gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 3 )};
445       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
446     }
447     break;
448   }
449   case 8:{
450     {
451       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )};
452       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
453     }
454     {
455       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 4 )};
456       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
457     }
458     {
459       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 7 )};
460       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
461     }
462     {
463       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 8 )};
464       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
465     }
466     {
467       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 3 )};
468       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
469     }
470     {
471       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 4 )};
472       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
473     }
474     {
475       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 7 )};
476       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
477     }
478     {
479       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 8 )};
480       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
481     }
482     {
483       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 3 )};
484       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
485     }
486     {
487       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 4 )};
488       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
489     }
490     {
491       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 7 )};
492       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
493     }
494     {
495       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 8 )};
496       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
497     }
498     {
499       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 1 )};
500       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
501     }
502     {
503       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 2 )};
504       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
505     }
506     {
507       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 5 )};
508       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
509     }
510     {
511       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 6 )};
512       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
513     }
514     {
515       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 1 )};
516       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
517     }
518     {
519       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 2 )};
520       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
521     }
522     {
523       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 5 )};
524       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
525     }
526     {
527       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 6 )};
528       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
529     }
530     {
531       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 1 )};
532       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
533     }
534     {
535       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )};
536       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
537     }
538     {
539       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 5 )};
540       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
541     }
542     {
543       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 6 )};
544       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
545     }
546     {
547       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )};
548       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
549     }
550     {
551       gp_XYZ aXYZ[4] = {P( 4 ),P( 5 ),P( 8 ),P( 2 )};
552       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
553     }
554     {
555       gp_XYZ aXYZ[4] = {P( 1 ),P( 4 ),P( 5 ),P( 3 )};
556       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
557     }
558     {
559       gp_XYZ aXYZ[4] = {P( 3 ),P( 6 ),P( 7 ),P( 1 )};
560       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
561     }
562     {
563       gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 6 ),P( 4 )};
564       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
565     }
566     {
567       gp_XYZ aXYZ[4] = {P( 5 ),P( 6 ),P( 8 ),P( 3 )};
568       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
569     }
570     {
571       gp_XYZ aXYZ[4] = {P( 7 ),P( 8 ),P( 6 ),P( 1 )};
572       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
573     }
574     {
575       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 7 )};
576       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
577     }
578     {
579       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 2 ),P( 5 )};
580       aQuality = max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
581     }
582     break;
583   }
584   }
585   return aQuality;
586 }
587
588 double AspectRatio3D::GetBadRate( double Value, int /*nbNodes*/ ) const
589 {
590   // the aspect ratio is in the range [1.0,infinity]
591   // 1.0 = good
592   // infinity = bad
593   return Value / 1000.;
594 }
595
596 SMDSAbs_ElementType AspectRatio3D::GetType() const
597 {
598   return SMDSAbs_Volume;
599 }
600
601
602 /*
603   Class       : Warping
604   Description : Functor for calculating warping
605 */
606 double Warping::GetValue( const TSequenceOfXYZ& P )
607 {
608   if ( P.size() != 4 )
609     return 0;
610
611   gp_XYZ G = ( P( 1 ) + P( 2 ) + P( 3 ) + P( 4 ) ) / 4;
612
613   double A1 = ComputeA( P( 1 ), P( 2 ), P( 3 ), G );
614   double A2 = ComputeA( P( 2 ), P( 3 ), P( 4 ), G );
615   double A3 = ComputeA( P( 3 ), P( 4 ), P( 1 ), G );
616   double A4 = ComputeA( P( 4 ), P( 1 ), P( 2 ), G );
617
618   return Max( Max( A1, A2 ), Max( A3, A4 ) );
619 }
620
621 double Warping::ComputeA( const gp_XYZ& thePnt1,
622                           const gp_XYZ& thePnt2,
623                           const gp_XYZ& thePnt3,
624                           const gp_XYZ& theG ) const
625 {
626   double aLen1 = gp_Pnt( thePnt1 ).Distance( gp_Pnt( thePnt2 ) );
627   double aLen2 = gp_Pnt( thePnt2 ).Distance( gp_Pnt( thePnt3 ) );
628   double L = Min( aLen1, aLen2 ) * 0.5;
629   if ( L < Precision::Confusion())
630     return 0.;
631
632   gp_XYZ GI = ( thePnt2 + thePnt1 ) / 2. - theG;
633   gp_XYZ GJ = ( thePnt3 + thePnt2 ) / 2. - theG;
634   gp_XYZ N  = GI.Crossed( GJ );
635
636   if ( N.Modulus() < gp::Resolution() )
637     return PI / 2;
638
639   N.Normalize();
640
641   double H = ( thePnt2 - theG ).Dot( N );
642   return asin( fabs( H / L ) ) * 180 / PI;
643 }
644
645 double Warping::GetBadRate( double Value, int /*nbNodes*/ ) const
646 {
647   // the warp is in the range [0.0,PI/2]
648   // 0.0 = good (no warp)
649   // PI/2 = bad  (face pliee)
650   return Value;
651 }
652
653 SMDSAbs_ElementType Warping::GetType() const
654 {
655   return SMDSAbs_Face;
656 }
657
658
659 /*
660   Class       : Taper
661   Description : Functor for calculating taper
662 */
663 double Taper::GetValue( const TSequenceOfXYZ& P )
664 {
665   if ( P.size() != 4 )
666     return 0;
667
668   // Compute taper
669   double J1 = getArea( P( 4 ), P( 1 ), P( 2 ) ) / 2;
670   double J2 = getArea( P( 3 ), P( 1 ), P( 2 ) ) / 2;
671   double J3 = getArea( P( 2 ), P( 3 ), P( 4 ) ) / 2;
672   double J4 = getArea( P( 3 ), P( 4 ), P( 1 ) ) / 2;
673
674   double JA = 0.25 * ( J1 + J2 + J3 + J4 );
675   if ( JA <= Precision::Confusion() )
676     return 0.;
677
678   double T1 = fabs( ( J1 - JA ) / JA );
679   double T2 = fabs( ( J2 - JA ) / JA );
680   double T3 = fabs( ( J3 - JA ) / JA );
681   double T4 = fabs( ( J4 - JA ) / JA );
682
683   return Max( Max( T1, T2 ), Max( T3, T4 ) );
684 }
685
686 double Taper::GetBadRate( double Value, int /*nbNodes*/ ) const
687 {
688   // the taper is in the range [0.0,1.0]
689   // 0.0  = good (no taper)
690   // 1.0 = bad  (les cotes opposes sont allignes)
691   return Value;
692 }
693
694 SMDSAbs_ElementType Taper::GetType() const
695 {
696   return SMDSAbs_Face;
697 }
698
699
700 /*
701   Class       : Skew
702   Description : Functor for calculating skew in degrees
703 */
704 static inline double skewAngle( const gp_XYZ& p1, const gp_XYZ& p2, const gp_XYZ& p3 )
705 {
706   gp_XYZ p12 = ( p2 + p1 ) / 2;
707   gp_XYZ p23 = ( p3 + p2 ) / 2;
708   gp_XYZ p31 = ( p3 + p1 ) / 2;
709
710   gp_Vec v1( p31 - p2 ), v2( p12 - p23 );
711
712   return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 );
713 }
714
715 double Skew::GetValue( const TSequenceOfXYZ& P )
716 {
717   if ( P.size() != 3 && P.size() != 4 )
718     return 0;
719
720   // Compute skew
721   static double PI2 = PI / 2;
722   if ( P.size() == 3 )
723   {
724     double A0 = fabs( PI2 - skewAngle( P( 3 ), P( 1 ), P( 2 ) ) );
725     double A1 = fabs( PI2 - skewAngle( P( 1 ), P( 2 ), P( 3 ) ) );
726     double A2 = fabs( PI2 - skewAngle( P( 2 ), P( 3 ), P( 1 ) ) );
727
728     return Max( A0, Max( A1, A2 ) ) * 180 / PI;
729   }
730   else 
731   {
732     gp_XYZ p12 = ( P( 1 ) + P( 2 ) ) / 2;
733     gp_XYZ p23 = ( P( 2 ) + P( 3 ) ) / 2;
734     gp_XYZ p34 = ( P( 3 ) + P( 4 ) ) / 2;
735     gp_XYZ p41 = ( P( 4 ) + P( 1 ) ) / 2;
736
737     gp_Vec v1( p34 - p12 ), v2( p23 - p41 );
738     double A = v1.Magnitude() <= gp::Resolution() || v2.Magnitude() <= gp::Resolution()
739       ? 0 : fabs( PI2 - v1.Angle( v2 ) );
740
741     return A * 180 / PI;
742   }
743 }
744
745 double Skew::GetBadRate( double Value, int /*nbNodes*/ ) const
746 {
747   // the skew is in the range [0.0,PI/2].
748   // 0.0 = good
749   // PI/2 = bad
750   return Value;
751 }
752
753 SMDSAbs_ElementType Skew::GetType() const
754 {
755   return SMDSAbs_Face;
756 }
757
758
759 /*
760   Class       : Area
761   Description : Functor for calculating area
762 */
763 double Area::GetValue( const TSequenceOfXYZ& P )
764 {
765   double aArea = 0;
766   if ( P.size() == 3 )
767     return getArea( P( 1 ), P( 2 ), P( 3 ) );
768   else if (P.size() > 3)
769     aArea = getArea( P( 1 ), P( 2 ), P( 3 ) );
770   else
771     return 0;
772
773   for (int i=4; i<=P.size(); i++)
774     aArea += getArea(P(1),P(i-1),P(i));
775   return aArea;
776 }
777
778 double Area::GetBadRate( double Value, int /*nbNodes*/ ) const
779 {
780   return Value;
781 }
782
783 SMDSAbs_ElementType Area::GetType() const
784 {
785   return SMDSAbs_Face;
786 }
787
788
789 /*
790   Class       : Length
791   Description : Functor for calculating length off edge
792 */
793 double Length::GetValue( const TSequenceOfXYZ& P )
794 {
795   return ( P.size() == 2 ? getDistance( P( 1 ), P( 2 ) ) : 0 );
796 }
797
798 double Length::GetBadRate( double Value, int /*nbNodes*/ ) const
799 {
800   return Value;
801 }
802
803 SMDSAbs_ElementType Length::GetType() const
804 {
805   return SMDSAbs_Edge;
806 }
807
808 /*
809   Class       : Length2D
810   Description : Functor for calculating length of edge
811 */
812
813 double Length2D::GetValue( long theElementId)
814 {
815   TSequenceOfXYZ P;
816
817   if (GetPoints(theElementId,P)){
818     
819     double  aVal;// = GetValue( P );
820     const SMDS_MeshElement* aElem = myMesh->FindElement( theElementId );
821     SMDSAbs_ElementType aType = aElem->GetType();
822     
823     int len = P.size();
824     
825     switch (aType){
826     case SMDSAbs_All:
827     case SMDSAbs_Node: 
828     case SMDSAbs_Edge:
829       if (len == 2){
830         aVal = getDistance( P( 1 ), P( 2 ) );
831         break;
832       }
833     case SMDSAbs_Face:
834       if (len == 3){ // triangles
835         double L1 = getDistance(P( 1 ),P( 2 ));
836         double L2 = getDistance(P( 2 ),P( 3 ));
837         double L3 = getDistance(P( 3 ),P( 1 ));
838         aVal = Max(L1,Max(L2,L3));
839         break;
840       }
841       else if (len == 4){ // quadrangles
842         double L1 = getDistance(P( 1 ),P( 2 ));
843         double L2 = getDistance(P( 2 ),P( 3 ));
844         double L3 = getDistance(P( 3 ),P( 4 ));
845         double L4 = getDistance(P( 4 ),P( 1 ));
846         aVal = Max(Max(L1,L2),Max(L3,L4));
847         break;
848       }
849     case SMDSAbs_Volume:
850       if (len == 4){ // tetraidrs
851         double L1 = getDistance(P( 1 ),P( 2 ));
852         double L2 = getDistance(P( 2 ),P( 3 ));
853         double L3 = getDistance(P( 3 ),P( 1 ));
854         double L4 = getDistance(P( 1 ),P( 4 ));
855         double L5 = getDistance(P( 2 ),P( 4 ));
856         double L6 = getDistance(P( 3 ),P( 4 ));
857         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
858         break;
859       } 
860       else if (len == 5){ // piramids
861         double L1 = getDistance(P( 1 ),P( 2 ));
862         double L2 = getDistance(P( 2 ),P( 3 ));
863         double L3 = getDistance(P( 3 ),P( 1 ));
864         double L4 = getDistance(P( 4 ),P( 1 ));
865         double L5 = getDistance(P( 1 ),P( 5 ));
866         double L6 = getDistance(P( 2 ),P( 5 ));
867         double L7 = getDistance(P( 3 ),P( 5 ));
868         double L8 = getDistance(P( 4 ),P( 5 ));
869       
870         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
871         aVal = Max(aVal,Max(L7,L8));
872         break;
873       }
874       else if (len == 6){ // pentaidres
875         double L1 = getDistance(P( 1 ),P( 2 ));
876         double L2 = getDistance(P( 2 ),P( 3 ));
877         double L3 = getDistance(P( 3 ),P( 1 ));
878         double L4 = getDistance(P( 4 ),P( 5 ));
879         double L5 = getDistance(P( 5 ),P( 6 ));
880         double L6 = getDistance(P( 6 ),P( 4 ));
881         double L7 = getDistance(P( 1 ),P( 4 ));
882         double L8 = getDistance(P( 2 ),P( 5 ));
883         double L9 = getDistance(P( 3 ),P( 6 ));
884       
885         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
886         aVal = Max(aVal,Max(Max(L7,L8),L9));
887         break;
888       }
889       else if (len == 8){ // hexaider
890         double L1 = getDistance(P( 1 ),P( 2 ));
891         double L2 = getDistance(P( 2 ),P( 3 ));
892         double L3 = getDistance(P( 3 ),P( 4 ));
893         double L4 = getDistance(P( 4 ),P( 1 ));
894         double L5 = getDistance(P( 5 ),P( 6 ));
895         double L6 = getDistance(P( 6 ),P( 7 ));
896         double L7 = getDistance(P( 7 ),P( 8 ));
897         double L8 = getDistance(P( 8 ),P( 5 ));
898         double L9 = getDistance(P( 1 ),P( 5 ));
899         double L10= getDistance(P( 2 ),P( 6 ));
900         double L11= getDistance(P( 3 ),P( 7 ));
901         double L12= getDistance(P( 4 ),P( 8 ));
902       
903         aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
904         aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10)));
905         aVal = Max(aVal,Max(L11,L12));
906         break;
907         
908       }
909       
910     default: aVal=-1; 
911     }
912     
913     if (aVal <0){
914       return 0.;
915     }
916
917     if ( myPrecision >= 0 )
918     {
919       double prec = pow( 10., (double)( myPrecision ) );
920       aVal = floor( aVal * prec + 0.5 ) / prec;
921     }
922     
923     return aVal;
924
925   }
926   return 0.;
927 }
928
929 double Length2D::GetBadRate( double Value, int /*nbNodes*/ ) const
930 {
931   return Value;
932 }
933
934 SMDSAbs_ElementType Length2D::GetType() const
935 {
936   return SMDSAbs_Face;
937 }
938
939 Length2D::Value::Value(double theLength,long thePntId1, long thePntId2):
940   myLength(theLength)
941 {
942   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
943   if(thePntId1 > thePntId2){
944     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
945   }
946 }
947
948 bool Length2D::Value::operator<(const Length2D::Value& x) const{
949   if(myPntId[0] < x.myPntId[0]) return true;
950   if(myPntId[0] == x.myPntId[0])
951     if(myPntId[1] < x.myPntId[1]) return true;
952   return false;
953 }
954
955 void Length2D::GetValues(TValues& theValues){
956   TValues aValues;
957   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
958   for(; anIter->more(); ){
959     const SMDS_MeshFace* anElem = anIter->next();
960     SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator();
961     long aNodeId[2];
962     gp_Pnt P[3];
963     
964     double aLength;
965     const SMDS_MeshElement* aNode;
966     if(aNodesIter->more()){
967       aNode = aNodesIter->next();
968       const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
969       P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
970       aNodeId[0] = aNodeId[1] = aNode->GetID();
971       aLength = 0;
972     }   
973     for(; aNodesIter->more(); ){
974       aNode = aNodesIter->next();
975       const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
976       long anId = aNode->GetID();
977       
978       P[2] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
979
980       aLength = P[1].Distance(P[2]);
981       
982       Value aValue(aLength,aNodeId[1],anId);
983       aNodeId[1] = anId;
984       P[1] = P[2];
985       theValues.insert(aValue);
986     }
987     
988     aLength = P[0].Distance(P[1]);
989     
990     Value aValue(aLength,aNodeId[0],aNodeId[1]);
991     theValues.insert(aValue);
992   }
993 }
994
995 /*
996   Class       : MultiConnection
997   Description : Functor for calculating number of faces conneted to the edge
998 */
999 double MultiConnection::GetValue( const TSequenceOfXYZ& P )
1000 {
1001   return 0;
1002 }
1003 double MultiConnection::GetValue( long theId )
1004 {
1005   return getNbMultiConnection( myMesh, theId );
1006 }
1007
1008 double MultiConnection::GetBadRate( double Value, int /*nbNodes*/ ) const
1009 {
1010   return Value;
1011 }
1012
1013 SMDSAbs_ElementType MultiConnection::GetType() const
1014 {
1015   return SMDSAbs_Edge;
1016 }
1017
1018 /*
1019   Class       : MultiConnection2D
1020   Description : Functor for calculating number of faces conneted to the edge
1021 */
1022 double MultiConnection2D::GetValue( const TSequenceOfXYZ& P )
1023 {
1024   return 0;
1025 }
1026
1027 double MultiConnection2D::GetValue( long theElementId )
1028 {
1029   TSequenceOfXYZ P;
1030   int aResult = 0;
1031   
1032   if (GetPoints(theElementId,P)){
1033     const SMDS_MeshElement* anFaceElem = myMesh->FindElement( theElementId );
1034     SMDSAbs_ElementType aType = anFaceElem->GetType();
1035     
1036     int len = P.size();
1037     
1038     TColStd_MapOfInteger aMap;
1039     int aResult = 0;
1040     
1041     switch (aType){
1042     case SMDSAbs_All:
1043     case SMDSAbs_Node: 
1044     case SMDSAbs_Edge:
1045     case SMDSAbs_Face:
1046       if (len == 3){ // triangles
1047         int Nb[3] = {0,0,0};
1048
1049         int i=0;
1050         SMDS_ElemIteratorPtr anIter = anFaceElem->nodesIterator();
1051         if ( anIter != 0 ) {
1052           while( anIter->more() ) {
1053             const SMDS_MeshNode* aNode = (SMDS_MeshNode*)anIter->next();
1054             if ( aNode == 0 ){
1055               break;
1056             }
1057             SMDS_ElemIteratorPtr anElemIter = aNode->GetInverseElementIterator();
1058             while( anElemIter->more() ) {
1059               const SMDS_MeshElement* anElem = anElemIter->next();
1060               if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) {
1061                 int anId = anElem->GetID();
1062
1063                 if ( anIter->more() )              // i.e. first node
1064                   aMap.Add( anId );
1065                 else if ( aMap.Contains( anId ) ){
1066                   Nb[i]++;
1067                 }
1068               }
1069               else if ( anElem != 0 && anElem->GetType() == SMDSAbs_Edge ) i++;
1070             }
1071           }
1072         }
1073         
1074         aResult = Max(Max(Nb[0],Nb[1]),Nb[2]);
1075       }
1076       break;
1077     case SMDSAbs_Volume:
1078     default: aResult=0;
1079     }
1080     
1081   }
1082   return aResult;//getNbMultiConnection( myMesh, theId );
1083 }
1084
1085 double MultiConnection2D::GetBadRate( double Value, int /*nbNodes*/ ) const
1086 {
1087   return Value;
1088 }
1089
1090 SMDSAbs_ElementType MultiConnection2D::GetType() const
1091 {
1092   return SMDSAbs_Face;
1093 }
1094
1095 MultiConnection2D::Value::Value(long thePntId1, long thePntId2)
1096 {
1097   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
1098   if(thePntId1 > thePntId2){
1099     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
1100   }
1101 }
1102
1103 bool MultiConnection2D::Value::operator<(const MultiConnection2D::Value& x) const{
1104   if(myPntId[0] < x.myPntId[0]) return true;
1105   if(myPntId[0] == x.myPntId[0])
1106     if(myPntId[1] < x.myPntId[1]) return true;
1107   return false;
1108 }
1109
1110 void MultiConnection2D::GetValues(MValues& theValues){
1111   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
1112   for(; anIter->more(); ){
1113     const SMDS_MeshFace* anElem = anIter->next();
1114     SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator();
1115     long aNodeId[3];
1116
1117     //int aNbConnects=0;
1118     const SMDS_MeshNode* aNode0;
1119     const SMDS_MeshNode* aNode1;
1120     const SMDS_MeshNode* aNode2;
1121     if(aNodesIter->more()){
1122       aNode0 = (SMDS_MeshNode*) aNodesIter->next();
1123       aNode1 = aNode0;
1124       const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode1;
1125       aNodeId[0] = aNodeId[1] = aNodes->GetID();
1126     }
1127     for(; aNodesIter->more(); ){
1128       aNode2 = (SMDS_MeshNode*) aNodesIter->next();
1129       long anId = aNode2->GetID();
1130       aNodeId[2] = anId;
1131       
1132       Value aValue(aNodeId[1],aNodeId[2]);
1133       MValues::iterator aItr = theValues.find(aValue);
1134       if (aItr != theValues.end()){
1135         aItr->second += 1;
1136         //aNbConnects = nb;
1137       } else {
1138         theValues[aValue] = 1;
1139         //aNbConnects = 1;
1140       }
1141       //cout << "NodeIds: "<<aNodeId[1]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl;
1142       aNodeId[1] = aNodeId[2];
1143       aNode1 = aNode2;
1144     }
1145     Value aValue(aNodeId[0],aNodeId[2]);
1146     MValues::iterator aItr = theValues.find(aValue);
1147     if (aItr != theValues.end()){
1148       aItr->second += 1;
1149       //aNbConnects = nb;
1150     } else {
1151       theValues[aValue] = 1;
1152       //aNbConnects = 1;
1153     }
1154     //cout << "NodeIds: "<<aNodeId[0]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl;
1155   }
1156
1157 }
1158
1159 /*
1160                             PREDICATES
1161 */
1162
1163 /*
1164   Class       : BadOrientedVolume
1165   Description : Predicate bad oriented volumes
1166 */
1167
1168 BadOrientedVolume::BadOrientedVolume()
1169 {
1170   myMesh = 0;
1171 }
1172
1173 void BadOrientedVolume::SetMesh( const SMDS_Mesh* theMesh )
1174 {
1175   myMesh = theMesh;
1176 }
1177
1178 bool BadOrientedVolume::IsSatisfy( long theId )
1179 {
1180   if ( myMesh == 0 )
1181     return false;
1182
1183   SMDS_VolumeTool vTool( myMesh->FindElement( theId ));
1184   return !vTool.IsForward();
1185 }
1186
1187 SMDSAbs_ElementType BadOrientedVolume::GetType() const
1188 {
1189   return SMDSAbs_Volume;
1190 }
1191
1192
1193
1194 /*
1195   Class       : FreeBorders
1196   Description : Predicate for free borders
1197 */
1198
1199 FreeBorders::FreeBorders()
1200 {
1201   myMesh = 0;
1202 }
1203
1204 void FreeBorders::SetMesh( const SMDS_Mesh* theMesh )
1205 {
1206   myMesh = theMesh;
1207 }
1208
1209 bool FreeBorders::IsSatisfy( long theId )
1210 {
1211   return getNbMultiConnection( myMesh, theId ) == 1;
1212 }
1213
1214 SMDSAbs_ElementType FreeBorders::GetType() const
1215 {
1216   return SMDSAbs_Edge;
1217 }
1218
1219
1220 /*
1221   Class       : FreeEdges
1222   Description : Predicate for free Edges
1223 */
1224 FreeEdges::FreeEdges()
1225 {
1226   myMesh = 0;
1227 }
1228
1229 void FreeEdges::SetMesh( const SMDS_Mesh* theMesh )
1230 {
1231   myMesh = theMesh;
1232 }
1233
1234 bool FreeEdges::IsFreeEdge( const SMDS_MeshNode** theNodes, const int theFaceId  )
1235 {
1236   TColStd_MapOfInteger aMap;
1237   for ( int i = 0; i < 2; i++ )
1238   {
1239     SMDS_ElemIteratorPtr anElemIter = theNodes[ i ]->GetInverseElementIterator();
1240     while( anElemIter->more() )
1241     {
1242       const SMDS_MeshElement* anElem = anElemIter->next();
1243       if ( anElem != 0 && anElem->GetType() == SMDSAbs_Face )
1244       {
1245         int anId = anElem->GetID();
1246
1247         if ( i == 0 ) 
1248           aMap.Add( anId );
1249         else if ( aMap.Contains( anId ) && anId != theFaceId )
1250           return false;
1251       }
1252     }
1253   }
1254   return true;
1255 }
1256
1257 bool FreeEdges::IsSatisfy( long theId )
1258 {
1259   if ( myMesh == 0 )
1260     return false;
1261
1262   const SMDS_MeshElement* aFace = myMesh->FindElement( theId );
1263   if ( aFace == 0 || aFace->GetType() != SMDSAbs_Face || aFace->NbNodes() < 3 )
1264     return false;
1265
1266   int nbNodes = aFace->NbNodes();
1267   const SMDS_MeshNode* aNodes[ nbNodes ];
1268   int i = 0;
1269   SMDS_ElemIteratorPtr anIter = aFace->nodesIterator();
1270   if ( anIter != 0 )
1271   {
1272     while( anIter->more() )
1273     {
1274       const SMDS_MeshNode* aNode = (SMDS_MeshNode*)anIter->next();
1275       if ( aNode == 0 )
1276         return false;
1277       aNodes[ i++ ] = aNode;
1278     }
1279   }
1280
1281   for ( int i = 0; i < nbNodes - 1; i++ )
1282     if ( IsFreeEdge( &aNodes[ i ], theId ) )
1283       return true;
1284
1285   aNodes[ 1 ] = aNodes[ nbNodes - 1 ];
1286   
1287   return IsFreeEdge( &aNodes[ 0 ], theId );
1288
1289 }
1290
1291 SMDSAbs_ElementType FreeEdges::GetType() const
1292 {
1293   return SMDSAbs_Face;
1294 }
1295
1296 FreeEdges::Border::Border(long theElemId, long thePntId1, long thePntId2):
1297   myElemId(theElemId)
1298 {
1299   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
1300   if(thePntId1 > thePntId2){
1301     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
1302   }
1303 }
1304
1305 bool FreeEdges::Border::operator<(const FreeEdges::Border& x) const{
1306   if(myPntId[0] < x.myPntId[0]) return true;
1307   if(myPntId[0] == x.myPntId[0])
1308     if(myPntId[1] < x.myPntId[1]) return true;
1309   return false;
1310 }
1311
1312 inline void UpdateBorders(const FreeEdges::Border& theBorder,
1313                           FreeEdges::TBorders& theRegistry, 
1314                           FreeEdges::TBorders& theContainer)
1315 {
1316   if(theRegistry.find(theBorder) == theRegistry.end()){
1317     theRegistry.insert(theBorder);
1318     theContainer.insert(theBorder);
1319   }else{
1320     theContainer.erase(theBorder);
1321   }
1322 }
1323
1324 void FreeEdges::GetBoreders(TBorders& theBorders)
1325 {
1326   TBorders aRegistry;
1327   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
1328   for(; anIter->more(); ){
1329     const SMDS_MeshFace* anElem = anIter->next();
1330     long anElemId = anElem->GetID();
1331     SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator();
1332     long aNodeId[2];
1333     const SMDS_MeshElement* aNode;
1334     if(aNodesIter->more()){
1335       aNode = aNodesIter->next();
1336       aNodeId[0] = aNodeId[1] = aNode->GetID();
1337     }   
1338     for(; aNodesIter->more(); ){
1339       aNode = aNodesIter->next();
1340       long anId = aNode->GetID();
1341       Border aBorder(anElemId,aNodeId[1],anId);
1342       aNodeId[1] = anId;
1343       //std::cout<<aBorder.myPntId[0]<<"; "<<aBorder.myPntId[1]<<"; "<<aBorder.myElemId<<endl;
1344       UpdateBorders(aBorder,aRegistry,theBorders);
1345     }
1346     Border aBorder(anElemId,aNodeId[0],aNodeId[1]);
1347     //std::cout<<aBorder.myPntId[0]<<"; "<<aBorder.myPntId[1]<<"; "<<aBorder.myElemId<<endl;
1348     UpdateBorders(aBorder,aRegistry,theBorders);
1349   }
1350   //std::cout<<"theBorders.size() = "<<theBorders.size()<<endl;
1351 }
1352
1353 /*
1354   Class       : RangeOfIds
1355   Description : Predicate for Range of Ids.
1356                 Range may be specified with two ways.
1357                 1. Using AddToRange method
1358                 2. With SetRangeStr method. Parameter of this method is a string
1359                    like as "1,2,3,50-60,63,67,70-"
1360 */
1361
1362 //=======================================================================
1363 // name    : RangeOfIds
1364 // Purpose : Constructor
1365 //=======================================================================
1366 RangeOfIds::RangeOfIds()
1367 {
1368   myMesh = 0;
1369   myType = SMDSAbs_All;
1370 }
1371
1372 //=======================================================================
1373 // name    : SetMesh
1374 // Purpose : Set mesh 
1375 //=======================================================================
1376 void RangeOfIds::SetMesh( const SMDS_Mesh* theMesh )
1377 {
1378   myMesh = theMesh;
1379 }
1380
1381 //=======================================================================
1382 // name    : AddToRange
1383 // Purpose : Add ID to the range
1384 //=======================================================================
1385 bool RangeOfIds::AddToRange( long theEntityId )
1386 {
1387   myIds.Add( theEntityId );
1388   return true;
1389 }
1390
1391 //=======================================================================
1392 // name    : GetRangeStr
1393 // Purpose : Get range as a string.
1394 //           Example: "1,2,3,50-60,63,67,70-"
1395 //=======================================================================
1396 void RangeOfIds::GetRangeStr( TCollection_AsciiString& theResStr )
1397 {
1398   theResStr.Clear();
1399
1400   TColStd_SequenceOfInteger     anIntSeq;
1401   TColStd_SequenceOfAsciiString aStrSeq;
1402
1403   TColStd_MapIteratorOfMapOfInteger anIter( myIds );
1404   for ( ; anIter.More(); anIter.Next() )
1405   {
1406     int anId = anIter.Key();
1407     TCollection_AsciiString aStr( anId );
1408     anIntSeq.Append( anId );
1409     aStrSeq.Append( aStr );
1410   }
1411
1412   for ( int i = 1, n = myMin.Length(); i <= n; i++ )
1413   {
1414     int aMinId = myMin( i );
1415     int aMaxId = myMax( i );
1416
1417     TCollection_AsciiString aStr;
1418     if ( aMinId != IntegerFirst() )
1419       aStr += aMinId;
1420       
1421     aStr += "-";
1422       
1423     if ( aMaxId != IntegerLast() )
1424       aStr += aMaxId;
1425
1426     // find position of the string in result sequence and insert string in it
1427     if ( anIntSeq.Length() == 0 )
1428     {
1429       anIntSeq.Append( aMinId );
1430       aStrSeq.Append( aStr );
1431     }
1432     else
1433     {
1434       if ( aMinId < anIntSeq.First() )
1435       {
1436         anIntSeq.Prepend( aMinId );
1437         aStrSeq.Prepend( aStr );
1438       }
1439       else if ( aMinId > anIntSeq.Last() )
1440       {
1441         anIntSeq.Append( aMinId );
1442         aStrSeq.Append( aStr );
1443       }
1444       else
1445         for ( int j = 1, k = anIntSeq.Length(); j <= k; j++ )
1446           if ( aMinId < anIntSeq( j ) )
1447           {
1448             anIntSeq.InsertBefore( j, aMinId );
1449             aStrSeq.InsertBefore( j, aStr );
1450             break;
1451           }
1452     }
1453   }
1454
1455   if ( aStrSeq.Length() == 0 )
1456     return;
1457
1458   theResStr = aStrSeq( 1 );
1459   for ( int j = 2, k = aStrSeq.Length(); j <= k; j++  )
1460   {
1461     theResStr += ",";
1462     theResStr += aStrSeq( j );
1463   }
1464 }
1465
1466 //=======================================================================
1467 // name    : SetRangeStr
1468 // Purpose : Define range with string
1469 //           Example of entry string: "1,2,3,50-60,63,67,70-"
1470 //=======================================================================
1471 bool RangeOfIds::SetRangeStr( const TCollection_AsciiString& theStr )
1472 {
1473   myMin.Clear();
1474   myMax.Clear();
1475   myIds.Clear();
1476
1477   TCollection_AsciiString aStr = theStr;
1478   aStr.RemoveAll( ' ' );
1479   aStr.RemoveAll( '\t' );
1480
1481   for ( int aPos = aStr.Search( ",," ); aPos != -1; aPos = aStr.Search( ",," ) )
1482     aStr.Remove( aPos, 2 );
1483
1484   TCollection_AsciiString tmpStr = aStr.Token( ",", 1 );
1485   int i = 1;
1486   while ( tmpStr != "" )
1487   {
1488     tmpStr = aStr.Token( ",", i++ );
1489     int aPos = tmpStr.Search( '-' );
1490     
1491     if ( aPos == -1 )
1492     {
1493       if ( tmpStr.IsIntegerValue() )
1494         myIds.Add( tmpStr.IntegerValue() );
1495       else
1496         return false;
1497     }
1498     else
1499     {
1500       TCollection_AsciiString aMaxStr = tmpStr.Split( aPos );
1501       TCollection_AsciiString aMinStr = tmpStr;
1502       
1503       while ( aMinStr.Search( "-" ) != -1 ) aMinStr.RemoveAll( '-' );
1504       while ( aMaxStr.Search( "-" ) != -1 ) aMaxStr.RemoveAll( '-' );
1505
1506       if ( !aMinStr.IsEmpty() && !aMinStr.IsIntegerValue() ||
1507            !aMaxStr.IsEmpty() && !aMaxStr.IsIntegerValue() )
1508         return false;
1509            
1510       myMin.Append( aMinStr.IsEmpty() ? IntegerFirst() : aMinStr.IntegerValue() );
1511       myMax.Append( aMaxStr.IsEmpty() ? IntegerLast()  : aMaxStr.IntegerValue() );
1512     }
1513   }
1514
1515   return true;
1516 }
1517
1518 //=======================================================================
1519 // name    : GetType
1520 // Purpose : Get type of supported entities
1521 //=======================================================================
1522 SMDSAbs_ElementType RangeOfIds::GetType() const
1523 {
1524   return myType;
1525 }
1526
1527 //=======================================================================
1528 // name    : SetType
1529 // Purpose : Set type of supported entities
1530 //=======================================================================
1531 void RangeOfIds::SetType( SMDSAbs_ElementType theType )
1532 {
1533   myType = theType;
1534 }
1535
1536 //=======================================================================
1537 // name    : IsSatisfy
1538 // Purpose : Verify whether entity satisfies to this rpedicate
1539 //=======================================================================
1540 bool RangeOfIds::IsSatisfy( long theId )
1541 {
1542   if ( !myMesh )
1543     return false;
1544
1545   if ( myType == SMDSAbs_Node )
1546   {
1547     if ( myMesh->FindNode( theId ) == 0 )
1548       return false;
1549   }
1550   else
1551   {
1552     const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
1553     if ( anElem == 0 || myType != anElem->GetType() && myType != SMDSAbs_All )
1554       return false;
1555   }
1556     
1557   if ( myIds.Contains( theId ) )
1558     return true;
1559
1560   for ( int i = 1, n = myMin.Length(); i <= n; i++ )
1561     if ( theId >= myMin( i ) && theId <= myMax( i ) )
1562       return true;
1563
1564   return false;
1565 }
1566
1567 /*
1568   Class       : Comparator
1569   Description : Base class for comparators
1570 */
1571 Comparator::Comparator():
1572   myMargin(0)
1573 {}
1574
1575 Comparator::~Comparator()
1576 {}
1577
1578 void Comparator::SetMesh( const SMDS_Mesh* theMesh )
1579 {
1580   if ( myFunctor )
1581     myFunctor->SetMesh( theMesh );
1582 }
1583
1584 void Comparator::SetMargin( double theValue )
1585 {
1586   myMargin = theValue;
1587 }
1588
1589 void Comparator::SetNumFunctor( NumericalFunctorPtr theFunct )
1590 {
1591   myFunctor = theFunct;
1592 }
1593
1594 SMDSAbs_ElementType Comparator::GetType() const
1595 {
1596   return myFunctor ? myFunctor->GetType() : SMDSAbs_All;
1597 }
1598
1599 double Comparator::GetMargin()
1600 {
1601   return myMargin;
1602 }
1603
1604
1605 /*
1606   Class       : LessThan
1607   Description : Comparator "<"
1608 */
1609 bool LessThan::IsSatisfy( long theId )
1610 {
1611   return myFunctor && myFunctor->GetValue( theId ) < myMargin;
1612 }
1613
1614
1615 /*
1616   Class       : MoreThan
1617   Description : Comparator ">"
1618 */
1619 bool MoreThan::IsSatisfy( long theId )
1620 {
1621   return myFunctor && myFunctor->GetValue( theId ) > myMargin;
1622 }
1623
1624
1625 /*
1626   Class       : EqualTo
1627   Description : Comparator "="
1628 */
1629 EqualTo::EqualTo():
1630   myToler(Precision::Confusion())
1631 {}
1632
1633 bool EqualTo::IsSatisfy( long theId )
1634 {
1635   return myFunctor && fabs( myFunctor->GetValue( theId ) - myMargin ) < myToler;
1636 }
1637
1638 void EqualTo::SetTolerance( double theToler )
1639 {
1640   myToler = theToler;
1641 }
1642
1643 double EqualTo::GetTolerance()
1644 {
1645   return myToler;
1646 }
1647
1648 /*
1649   Class       : LogicalNOT
1650   Description : Logical NOT predicate
1651 */
1652 LogicalNOT::LogicalNOT()
1653 {}
1654
1655 LogicalNOT::~LogicalNOT()
1656 {}
1657
1658 bool LogicalNOT::IsSatisfy( long theId )
1659 {
1660   return myPredicate && !myPredicate->IsSatisfy( theId );
1661 }
1662
1663 void LogicalNOT::SetMesh( const SMDS_Mesh* theMesh )
1664 {
1665   if ( myPredicate )
1666     myPredicate->SetMesh( theMesh );
1667 }
1668
1669 void LogicalNOT::SetPredicate( PredicatePtr thePred )
1670 {
1671   myPredicate = thePred;
1672 }
1673
1674 SMDSAbs_ElementType LogicalNOT::GetType() const
1675 {
1676   return myPredicate ? myPredicate->GetType() : SMDSAbs_All;
1677 }
1678
1679
1680 /*
1681   Class       : LogicalBinary
1682   Description : Base class for binary logical predicate
1683 */
1684 LogicalBinary::LogicalBinary()
1685 {}
1686
1687 LogicalBinary::~LogicalBinary()
1688 {}
1689
1690 void LogicalBinary::SetMesh( const SMDS_Mesh* theMesh )
1691 {
1692   if ( myPredicate1 )
1693     myPredicate1->SetMesh( theMesh );
1694
1695   if ( myPredicate2 )
1696     myPredicate2->SetMesh( theMesh );
1697 }
1698
1699 void LogicalBinary::SetPredicate1( PredicatePtr thePredicate )
1700 {
1701   myPredicate1 = thePredicate;
1702 }
1703
1704 void LogicalBinary::SetPredicate2( PredicatePtr thePredicate )
1705 {
1706   myPredicate2 = thePredicate;
1707 }
1708
1709 SMDSAbs_ElementType LogicalBinary::GetType() const
1710 {
1711   if ( !myPredicate1 || !myPredicate2 )
1712     return SMDSAbs_All;
1713
1714   SMDSAbs_ElementType aType1 = myPredicate1->GetType();
1715   SMDSAbs_ElementType aType2 = myPredicate2->GetType();
1716
1717   return aType1 == aType2 ? aType1 : SMDSAbs_All;
1718 }
1719
1720
1721 /*
1722   Class       : LogicalAND
1723   Description : Logical AND
1724 */
1725 bool LogicalAND::IsSatisfy( long theId )
1726 {
1727   return 
1728     myPredicate1 && 
1729     myPredicate2 && 
1730     myPredicate1->IsSatisfy( theId ) && 
1731     myPredicate2->IsSatisfy( theId );
1732 }
1733
1734
1735 /*
1736   Class       : LogicalOR
1737   Description : Logical OR
1738 */
1739 bool LogicalOR::IsSatisfy( long theId )
1740 {
1741   return 
1742     myPredicate1 && 
1743     myPredicate2 && 
1744     myPredicate1->IsSatisfy( theId ) || 
1745     myPredicate2->IsSatisfy( theId );
1746 }
1747
1748
1749 /*
1750                               FILTER
1751 */
1752
1753 Filter::Filter()
1754 {}
1755
1756 Filter::~Filter()
1757 {}
1758
1759 void Filter::SetPredicate( PredicatePtr thePredicate )
1760 {
1761   myPredicate = thePredicate;
1762 }
1763
1764 template<class TElement, class TIterator, class TPredicate> 
1765 inline void FillSequence(const TIterator& theIterator,
1766                          TPredicate& thePredicate,
1767                          Filter::TIdSequence& theSequence)
1768 {
1769   if ( theIterator ) {
1770     while( theIterator->more() ) {
1771       TElement anElem = theIterator->next();
1772       long anId = anElem->GetID();
1773       if ( thePredicate->IsSatisfy( anId ) )
1774         theSequence.push_back( anId );
1775     }
1776   }
1777 }
1778
1779 void
1780 Filter::
1781 GetElementsId( const SMDS_Mesh* theMesh, 
1782                PredicatePtr thePredicate, 
1783                TIdSequence& theSequence )
1784 {
1785   theSequence.clear();
1786
1787   if ( !theMesh || !thePredicate ) 
1788     return;
1789
1790   thePredicate->SetMesh( theMesh );
1791
1792   SMDSAbs_ElementType aType = thePredicate->GetType();
1793   switch(aType){
1794   case SMDSAbs_Node:
1795     FillSequence<const SMDS_MeshNode*>(theMesh->nodesIterator(),thePredicate,theSequence);
1796     break;
1797   case SMDSAbs_Edge:
1798     FillSequence<const SMDS_MeshElement*>(theMesh->edgesIterator(),thePredicate,theSequence);
1799     break;
1800   case SMDSAbs_Face:
1801     FillSequence<const SMDS_MeshElement*>(theMesh->facesIterator(),thePredicate,theSequence);
1802     break;
1803   case SMDSAbs_Volume:
1804     FillSequence<const SMDS_MeshElement*>(theMesh->volumesIterator(),thePredicate,theSequence);
1805     break;
1806   case SMDSAbs_All:
1807     FillSequence<const SMDS_MeshElement*>(theMesh->edgesIterator(),thePredicate,theSequence);
1808     FillSequence<const SMDS_MeshElement*>(theMesh->facesIterator(),thePredicate,theSequence);
1809     FillSequence<const SMDS_MeshElement*>(theMesh->volumesIterator(),thePredicate,theSequence);
1810     break;
1811   }
1812 }
1813
1814 void
1815 Filter::GetElementsId( const SMDS_Mesh* theMesh,
1816                        Filter::TIdSequence& theSequence )
1817 {
1818   GetElementsId(theMesh,myPredicate,theSequence);
1819 }
1820
1821 /*
1822                               ManifoldPart
1823 */
1824
1825 typedef std::set<SMDS_MeshFace*>                    TMapOfFacePtr;
1826
1827 /*  
1828    Internal class Link
1829 */ 
1830
1831 ManifoldPart::Link::Link( SMDS_MeshNode* theNode1,
1832                           SMDS_MeshNode* theNode2 )
1833 {
1834   myNode1 = theNode1;
1835   myNode2 = theNode2;
1836 }
1837
1838 ManifoldPart::Link::~Link()
1839 {
1840   myNode1 = 0;
1841   myNode2 = 0;
1842 }
1843
1844 bool ManifoldPart::Link::IsEqual( const ManifoldPart::Link& theLink ) const
1845 {
1846   if ( myNode1 == theLink.myNode1 &&
1847        myNode2 == theLink.myNode2 )
1848     return true;
1849   else if ( myNode1 == theLink.myNode2 &&
1850             myNode2 == theLink.myNode1 )
1851     return true;
1852   else
1853     return false;
1854 }
1855
1856 bool ManifoldPart::Link::operator<( const ManifoldPart::Link& x ) const
1857 {
1858   if(myNode1 < x.myNode1) return true;
1859   if(myNode1 == x.myNode1)
1860     if(myNode2 < x.myNode2) return true;
1861   return false;
1862 }
1863
1864 bool ManifoldPart::IsEqual( const ManifoldPart::Link& theLink1,
1865                             const ManifoldPart::Link& theLink2 )
1866
1867   return theLink1.IsEqual( theLink2 );
1868 }
1869
1870 ManifoldPart::ManifoldPart()
1871 {
1872   myMesh = 0;
1873   myAngToler = Precision::Angular();
1874   myIsOnlyManifold = true;
1875 }
1876
1877 ManifoldPart::~ManifoldPart()
1878 {
1879   myMesh = 0;
1880 }
1881
1882 void ManifoldPart::SetMesh( const SMDS_Mesh* theMesh )
1883 {
1884   myMesh = theMesh;
1885   process();
1886 }
1887
1888 SMDSAbs_ElementType ManifoldPart::GetType() const
1889 { return SMDSAbs_Face; }
1890
1891 bool ManifoldPart::IsSatisfy( long theElementId )
1892 {
1893   return myMapIds.Contains( theElementId );
1894 }
1895
1896 void ManifoldPart::SetAngleTolerance( const double theAngToler )
1897 { myAngToler = theAngToler; }
1898
1899 double ManifoldPart::GetAngleTolerance() const
1900 { return myAngToler; }
1901
1902 void ManifoldPart::SetIsOnlyManifold( const bool theIsOnly )
1903 { myIsOnlyManifold = theIsOnly; }
1904
1905 void ManifoldPart::SetStartElem( const long  theStartId )
1906 { myStartElemId = theStartId; }
1907
1908 bool ManifoldPart::process()
1909 {
1910   myMapIds.Clear();
1911   myMapBadGeomIds.Clear();
1912   
1913   myAllFacePtr.clear();
1914   myAllFacePtrIntDMap.clear();
1915   if ( !myMesh )
1916     return false;
1917
1918   // collect all faces into own map
1919   SMDS_FaceIteratorPtr anFaceItr = myMesh->facesIterator();
1920   for (; anFaceItr->more(); )
1921   {
1922     SMDS_MeshFace* aFacePtr = (SMDS_MeshFace*)anFaceItr->next();
1923     myAllFacePtr.push_back( aFacePtr );
1924     myAllFacePtrIntDMap[aFacePtr] = myAllFacePtr.size()-1;
1925   }
1926
1927   SMDS_MeshFace* aStartFace = (SMDS_MeshFace*)myMesh->FindElement( myStartElemId );
1928   if ( !aStartFace )
1929     return false;
1930
1931   // the map of non manifold links and bad geometry
1932   TMapOfLink aMapOfNonManifold;
1933   TColStd_MapOfInteger aMapOfTreated;
1934
1935   // begin cycle on faces from start index and run on vector till the end
1936   //  and from begin to start index to cover whole vector
1937   const int aStartIndx = myAllFacePtrIntDMap[aStartFace];
1938   bool isStartTreat = false;
1939   for ( int fi = aStartIndx; !isStartTreat || fi != aStartIndx ; fi++ )
1940   {
1941     if ( fi == aStartIndx )
1942       isStartTreat = true;
1943     // as result next time when fi will be equal to aStartIndx
1944     
1945     SMDS_MeshFace* aFacePtr = myAllFacePtr[ fi ];
1946     if ( aMapOfTreated.Contains( aFacePtr->GetID() ) )
1947       continue;
1948
1949     aMapOfTreated.Add( aFacePtr->GetID() );
1950     TColStd_MapOfInteger aResFaces;
1951     if ( !findConnected( myAllFacePtrIntDMap, aFacePtr,
1952                          aMapOfNonManifold, aResFaces ) )
1953       continue;
1954     TColStd_MapIteratorOfMapOfInteger anItr( aResFaces );
1955     for ( ; anItr.More(); anItr.Next() )
1956     {
1957       int aFaceId = anItr.Key();
1958       aMapOfTreated.Add( aFaceId );
1959       myMapIds.Add( aFaceId );
1960     }
1961
1962     if ( fi == ( myAllFacePtr.size() - 1 ) )
1963       fi = 0;
1964   } // end run on vector of faces
1965   return !myMapIds.IsEmpty();
1966 }
1967
1968 static void getLinks( const SMDS_MeshFace* theFace,
1969                       ManifoldPart::TVectorOfLink& theLinks )
1970 {
1971   int aNbNode = theFace->NbNodes();
1972   SMDS_ElemIteratorPtr aNodeItr = theFace->nodesIterator();
1973   int i = 1;
1974   SMDS_MeshNode* aNode = 0;
1975   for ( ; aNodeItr->more() && i <= aNbNode; )
1976   {
1977     
1978     SMDS_MeshNode* aN1 = (SMDS_MeshNode*)aNodeItr->next();
1979     if ( i == 1 )
1980       aNode = aN1;
1981     i++;
1982     SMDS_MeshNode* aN2 = ( i >= aNbNode ) ? aNode : (SMDS_MeshNode*)aNodeItr->next();
1983     i++;
1984     ManifoldPart::Link aLink( aN1, aN2 );
1985     theLinks.push_back( aLink );
1986   }
1987 }
1988
1989 static gp_XYZ getNormale( const SMDS_MeshFace* theFace )
1990 {
1991   gp_XYZ n;
1992   int aNbNode = theFace->NbNodes();
1993   TColgp_Array1OfXYZ anArrOfXYZ(1,4);
1994   SMDS_ElemIteratorPtr aNodeItr = theFace->nodesIterator();
1995   int i = 1;
1996   for ( ; aNodeItr->more() && i <= 4; i++ )
1997   {
1998     SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next();
1999     anArrOfXYZ.SetValue(i, gp_XYZ( aNode->X(), aNode->Y(), aNode->Z() ) );
2000   }
2001   
2002   gp_XYZ q1 = anArrOfXYZ.Value(2) - anArrOfXYZ.Value(1);
2003   gp_XYZ q2 = anArrOfXYZ.Value(3) - anArrOfXYZ.Value(1);
2004   n  = q1 ^ q2;
2005   if ( aNbNode > 3 )
2006   {
2007     gp_XYZ q3 = anArrOfXYZ.Value(4) - anArrOfXYZ.Value(1);
2008     n += q2 ^ q3;
2009   }
2010   double len = n.Modulus();
2011   if ( len > 0 )
2012     n /= len;
2013
2014   return n;
2015 }
2016
2017 bool ManifoldPart::findConnected
2018                  ( const ManifoldPart::TDataMapFacePtrInt& theAllFacePtrInt,
2019                   SMDS_MeshFace*                           theStartFace,
2020                   ManifoldPart::TMapOfLink&                theNonManifold,
2021                   TColStd_MapOfInteger&                    theResFaces )
2022 {
2023   theResFaces.Clear();
2024   if ( !theAllFacePtrInt.size() )
2025     return false;
2026   
2027   if ( getNormale( theStartFace ).SquareModulus() <= gp::Resolution() )
2028   {
2029     myMapBadGeomIds.Add( theStartFace->GetID() );
2030     return false;
2031   }
2032
2033   ManifoldPart::TMapOfLink aMapOfBoundary, aMapToSkip;
2034   ManifoldPart::TVectorOfLink aSeqOfBoundary;
2035   theResFaces.Add( theStartFace->GetID() );
2036   ManifoldPart::TDataMapOfLinkFacePtr aDMapLinkFace;
2037
2038   expandBoundary( aMapOfBoundary, aSeqOfBoundary, 
2039                  aDMapLinkFace, theNonManifold, theStartFace );
2040
2041   bool isDone = false;
2042   while ( !isDone && aMapOfBoundary.size() != 0 )
2043   {
2044     bool isToReset = false;
2045     ManifoldPart::TVectorOfLink::iterator pLink = aSeqOfBoundary.begin();
2046     for ( ; !isToReset && pLink != aSeqOfBoundary.end(); ++pLink )
2047     {
2048       ManifoldPart::Link aLink = *pLink;
2049       if ( aMapToSkip.find( aLink ) != aMapToSkip.end() )
2050         continue;
2051       // each link could be treated only once
2052       aMapToSkip.insert( aLink );
2053
2054       ManifoldPart::TVectorOfFacePtr aFaces;
2055       // find next
2056       if ( myIsOnlyManifold && 
2057            (theNonManifold.find( aLink ) != theNonManifold.end()) )
2058         continue;
2059       else
2060       {
2061         getFacesByLink( aLink, aFaces );
2062         // filter the element to keep only indicated elements
2063         ManifoldPart::TVectorOfFacePtr aFiltered;
2064         ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin();
2065         for ( ; pFace != aFaces.end(); ++pFace )
2066         {
2067           SMDS_MeshFace* aFace = *pFace;
2068           if ( myAllFacePtrIntDMap.find( aFace ) != myAllFacePtrIntDMap.end() )
2069             aFiltered.push_back( aFace );
2070         }
2071         aFaces = aFiltered;
2072         if ( aFaces.size() < 2 )  // no neihgbour faces
2073           continue;
2074         else if ( myIsOnlyManifold && aFaces.size() > 2 ) // non manifold case
2075         {
2076           theNonManifold.insert( aLink );
2077           continue;
2078         }
2079       }
2080       
2081       // compare normal with normals of neighbor element
2082       SMDS_MeshFace* aPrevFace = aDMapLinkFace[ aLink ];
2083       ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin();
2084       for ( ; pFace != aFaces.end(); ++pFace )
2085       {
2086         SMDS_MeshFace* aNextFace = *pFace;
2087         if ( aPrevFace == aNextFace )
2088           continue;
2089         int anNextFaceID = aNextFace->GetID();
2090         if ( myIsOnlyManifold && theResFaces.Contains( anNextFaceID ) )
2091          // should not be with non manifold restriction. probably bad topology
2092           continue;
2093         // check if face was treated and skipped
2094         if ( myMapBadGeomIds.Contains( anNextFaceID ) ||
2095              !isInPlane( aPrevFace, aNextFace ) )
2096           continue;
2097         // add new element to connected and extend the boundaries.
2098         theResFaces.Add( anNextFaceID );
2099         expandBoundary( aMapOfBoundary, aSeqOfBoundary, 
2100                         aDMapLinkFace, theNonManifold, aNextFace );
2101         isToReset = true;
2102       }
2103     }
2104     isDone = !isToReset;
2105   }
2106
2107   return !theResFaces.IsEmpty();
2108 }
2109
2110 bool ManifoldPart::isInPlane( const SMDS_MeshFace* theFace1,
2111                               const SMDS_MeshFace* theFace2 )
2112 {
2113   gp_Dir aNorm1 = gp_Dir( getNormale( theFace1 ) );
2114   gp_XYZ aNorm2XYZ = getNormale( theFace2 );
2115   if ( aNorm2XYZ.SquareModulus() <= gp::Resolution() )
2116   {
2117     myMapBadGeomIds.Add( theFace2->GetID() );
2118     return false;
2119   }
2120   if ( aNorm1.IsParallel( gp_Dir( aNorm2XYZ ), myAngToler ) )
2121     return true;
2122
2123   return false;
2124 }
2125
2126 void ManifoldPart::expandBoundary
2127                    ( ManifoldPart::TMapOfLink&            theMapOfBoundary,
2128                      ManifoldPart::TVectorOfLink&         theSeqOfBoundary,
2129                      ManifoldPart::TDataMapOfLinkFacePtr& theDMapLinkFacePtr,
2130                      ManifoldPart::TMapOfLink&            theNonManifold,
2131                      SMDS_MeshFace*                       theNextFace ) const
2132 {
2133   ManifoldPart::TVectorOfLink aLinks;
2134   getLinks( theNextFace, aLinks );
2135   int aNbLink = aLinks.size();
2136   for ( int i = 0; i < aNbLink; i++ )
2137   {
2138     ManifoldPart::Link aLink = aLinks[ i ];
2139     if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) )
2140       continue;
2141     if ( theMapOfBoundary.find( aLink ) != theMapOfBoundary.end() )
2142     {
2143       if ( myIsOnlyManifold )
2144       {
2145         // remove from boundary
2146         theMapOfBoundary.erase( aLink );
2147         ManifoldPart::TVectorOfLink::iterator pLink = theSeqOfBoundary.begin();
2148         for ( ; pLink != theSeqOfBoundary.end(); ++pLink )
2149         {
2150           ManifoldPart::Link aBoundLink = *pLink;
2151           if ( aBoundLink.IsEqual( aLink ) )
2152           {
2153             theSeqOfBoundary.erase( pLink );
2154             break;
2155           }
2156         }
2157       }
2158     }
2159     else
2160     {
2161       theMapOfBoundary.insert( aLink );
2162       theSeqOfBoundary.push_back( aLink );
2163       theDMapLinkFacePtr[ aLink ] = theNextFace;
2164     }
2165   }
2166 }
2167
2168 void ManifoldPart::getFacesByLink( const ManifoldPart::Link& theLink,
2169                                    ManifoldPart::TVectorOfFacePtr& theFaces ) const
2170 {
2171   SMDS_Mesh::SetOfFaces aSetOfFaces;
2172   // take all faces that shared first node
2173   SMDS_ElemIteratorPtr anItr = theLink.myNode1->facesIterator();
2174   for ( ; anItr->more(); )
2175   {
2176     SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next();
2177     if ( !aFace )
2178       continue;
2179     aSetOfFaces.Add( aFace );
2180   }
2181   // take all faces that shared second node
2182   anItr = theLink.myNode2->facesIterator();
2183   // find the common part of two sets
2184   for ( ; anItr->more(); )
2185   {
2186     SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next();
2187     if ( aSetOfFaces.Contains( aFace ) )
2188       theFaces.push_back( aFace );
2189   }
2190 }
2191
2192
2193 /*
2194    ElementsOnSurface
2195 */
2196
2197 ElementsOnSurface::ElementsOnSurface()
2198 {
2199   myMesh = 0;
2200   myIds.Clear();
2201   myType = SMDSAbs_All;
2202   mySurf.Nullify();
2203   myToler = Precision::Confusion();
2204 }
2205
2206 ElementsOnSurface::~ElementsOnSurface()
2207 {
2208   myMesh = 0;
2209 }
2210
2211 void ElementsOnSurface::SetMesh( const SMDS_Mesh* theMesh )
2212
2213   if ( myMesh == theMesh )
2214     return;
2215   myMesh = theMesh;
2216   myIds.Clear();
2217   process();
2218 }
2219
2220 bool ElementsOnSurface::IsSatisfy( long theElementId )
2221 {
2222   return myIds.Contains( theElementId );
2223 }
2224
2225 SMDSAbs_ElementType ElementsOnSurface::GetType() const
2226 { return myType; }
2227
2228 void ElementsOnSurface::SetTolerance( const double theToler )
2229 { myToler = theToler; }
2230
2231 double ElementsOnSurface::GetTolerance() const
2232 {
2233   return myToler;
2234 }
2235
2236 void ElementsOnSurface::SetSurface( const TopoDS_Shape& theShape,
2237                                     const SMDSAbs_ElementType theType )
2238 {
2239   myType = theType;
2240   mySurf.Nullify();
2241   if ( theShape.IsNull() || theShape.ShapeType() != TopAbs_FACE )
2242   {
2243     mySurf.Nullify();
2244     return;
2245   }
2246   TopoDS_Face aFace = TopoDS::Face( theShape );
2247   mySurf = BRep_Tool::Surface( aFace );
2248 }
2249
2250 void ElementsOnSurface::process()
2251 {
2252   myIds.Clear();
2253   if ( mySurf.IsNull() )
2254     return;
2255
2256   if ( myMesh == 0 )
2257     return;
2258
2259   if ( myType == SMDSAbs_Face || myType == SMDSAbs_All )
2260   {
2261     SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
2262     for(; anIter->more(); )
2263       process( anIter->next() );
2264   }
2265
2266   if ( myType == SMDSAbs_Edge || myType == SMDSAbs_All )
2267   {
2268     SMDS_EdgeIteratorPtr anIter = myMesh->edgesIterator();
2269     for(; anIter->more(); )
2270       process( anIter->next() );
2271   }
2272
2273   if ( myType == SMDSAbs_Node )
2274   {
2275     SMDS_NodeIteratorPtr anIter = myMesh->nodesIterator();
2276     for(; anIter->more(); )
2277       process( anIter->next() );
2278   }
2279 }
2280
2281 void ElementsOnSurface::process( const SMDS_MeshElement* theElemPtr )
2282 {
2283   SMDS_ElemIteratorPtr aNodeItr = theElemPtr->nodesIterator();
2284   bool isSatisfy = true;
2285   for ( ; aNodeItr->more(); )
2286   {
2287     SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next();
2288     if ( !isOnSurface( aNode ) )
2289     {
2290       isSatisfy = false;
2291       break;
2292     }
2293   }
2294   if ( isSatisfy )
2295     myIds.Add( theElemPtr->GetID() );
2296 }
2297
2298 bool ElementsOnSurface::isOnSurface( const SMDS_MeshNode* theNode ) const
2299 {
2300   if ( mySurf.IsNull() )
2301     return false;
2302
2303   gp_Pnt aPnt( theNode->X(), theNode->Y(), theNode->Z() );
2304   double aToler2 = myToler * myToler;
2305   if ( mySurf->IsKind(STANDARD_TYPE(Geom_Plane)))
2306   {
2307     gp_Pln aPln = Handle(Geom_Plane)::DownCast(mySurf)->Pln();
2308     if ( aPln.SquareDistance( aPnt ) > aToler2 )
2309       return false;
2310   }
2311   else if ( mySurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)))
2312   {
2313     gp_Cylinder aCyl = Handle(Geom_CylindricalSurface)::DownCast(mySurf)->Cylinder();
2314     double aRad = aCyl.Radius();
2315     gp_Ax3 anAxis = aCyl.Position();
2316     gp_XYZ aLoc = aCyl.Location().XYZ();
2317     double aXDist = anAxis.XDirection().XYZ() * ( aPnt.XYZ() - aLoc );
2318     double aYDist = anAxis.YDirection().XYZ() * ( aPnt.XYZ() - aLoc );
2319     if ( fabs(aXDist*aXDist + aYDist*aYDist - aRad*aRad) > aToler2 )
2320       return false;
2321   }
2322   else
2323     return false;
2324
2325   return true;
2326 }