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