Salome HOME
Add "Deflection 2D" quality control
[modules/smesh.git] / src / Controls / SMESH_Controls.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include "SMESH_ControlsDef.hxx"
24
25 #include "SMDS_BallElement.hxx"
26 #include "SMDS_FacePosition.hxx"
27 #include "SMDS_Iterator.hxx"
28 #include "SMDS_Mesh.hxx"
29 #include "SMDS_MeshElement.hxx"
30 #include "SMDS_MeshNode.hxx"
31 #include "SMDS_QuadraticEdge.hxx"
32 #include "SMDS_QuadraticFaceOfNodes.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESHDS_GroupBase.hxx"
35 #include "SMESHDS_GroupOnFilter.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESH_MeshAlgos.hxx"
38 #include "SMESH_OctreeNode.hxx"
39
40 #include <Basics_Utils.hxx>
41
42 #include <BRepAdaptor_Surface.hxx>
43 #include <BRepBndLib.hxx>
44 #include <BRepBuilderAPI_Copy.hxx>
45 #include <BRepClass3d_SolidClassifier.hxx>
46 #include <BRepClass_FaceClassifier.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Geom_CylindricalSurface.hxx>
49 #include <Geom_Plane.hxx>
50 #include <Geom_Surface.hxx>
51 #include <NCollection_Map.hxx>
52 #include <Precision.hxx>
53 #include <ShapeAnalysis_Surface.hxx>
54 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
55 #include <TColStd_MapOfInteger.hxx>
56 #include <TColStd_SequenceOfAsciiString.hxx>
57 #include <TColgp_Array1OfXYZ.hxx>
58 #include <TopAbs.hxx>
59 #include <TopExp.hxx>
60 #include <TopoDS.hxx>
61 #include <TopoDS_Edge.hxx>
62 #include <TopoDS_Face.hxx>
63 #include <TopoDS_Iterator.hxx>
64 #include <TopoDS_Shape.hxx>
65 #include <TopoDS_Vertex.hxx>
66 #include <gp_Ax3.hxx>
67 #include <gp_Cylinder.hxx>
68 #include <gp_Dir.hxx>
69 #include <gp_Pln.hxx>
70 #include <gp_Pnt.hxx>
71 #include <gp_Vec.hxx>
72 #include <gp_XYZ.hxx>
73
74 #include <vtkMeshQuality.h>
75
76 #include <set>
77 #include <limits>
78
79 /*
80                             AUXILIARY METHODS
81 */
82
83 namespace {
84
85   const double theEps = 1e-100;
86   const double theInf = 1e+100;
87
88   inline gp_XYZ gpXYZ(const SMDS_MeshNode* aNode )
89   {
90     return gp_XYZ(aNode->X(), aNode->Y(), aNode->Z() );
91   }
92
93   inline double getAngle( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 )
94   {
95     gp_Vec v1( P1 - P2 ), v2( P3 - P2 );
96
97     return v1.Magnitude() < gp::Resolution() ||
98       v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 );
99   }
100
101   inline double getArea( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 )
102   {
103     gp_Vec aVec1( P2 - P1 );
104     gp_Vec aVec2( P3 - P1 );
105     return ( aVec1 ^ aVec2 ).Magnitude() * 0.5;
106   }
107
108   inline double getArea( const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3 )
109   {
110     return getArea( P1.XYZ(), P2.XYZ(), P3.XYZ() );
111   }
112
113
114
115   inline double getDistance( const gp_XYZ& P1, const gp_XYZ& P2 )
116   {
117     double aDist = gp_Pnt( P1 ).Distance( gp_Pnt( P2 ) );
118     return aDist;
119   }
120
121   int getNbMultiConnection( const SMDS_Mesh* theMesh, const int theId )
122   {
123     if ( theMesh == 0 )
124       return 0;
125
126     const SMDS_MeshElement* anEdge = theMesh->FindElement( theId );
127     if ( anEdge == 0 || anEdge->GetType() != SMDSAbs_Edge/* || anEdge->NbNodes() != 2 */)
128       return 0;
129
130     // for each pair of nodes in anEdge (there are 2 pairs in a quadratic edge)
131     // count elements containing both nodes of the pair.
132     // Note that there may be such cases for a quadratic edge (a horizontal line):
133     //
134     //  Case 1          Case 2
135     //  |     |      |        |      |
136     //  |     |      |        |      |
137     //  +-----+------+  +-----+------+ 
138     //  |            |  |            |
139     //  |            |  |            |
140     // result should be 2 in both cases
141     //
142     int aResult0 = 0, aResult1 = 0;
143      // last node, it is a medium one in a quadratic edge
144     const SMDS_MeshNode* aLastNode = anEdge->GetNode( anEdge->NbNodes() - 1 );
145     const SMDS_MeshNode*    aNode0 = anEdge->GetNode( 0 );
146     const SMDS_MeshNode*    aNode1 = anEdge->GetNode( 1 );
147     if ( aNode1 == aLastNode ) aNode1 = 0;
148
149     SMDS_ElemIteratorPtr anElemIter = aLastNode->GetInverseElementIterator();
150     while( anElemIter->more() ) {
151       const SMDS_MeshElement* anElem = anElemIter->next();
152       if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) {
153         SMDS_ElemIteratorPtr anIter = anElem->nodesIterator();
154         while ( anIter->more() ) {
155           if ( const SMDS_MeshElement* anElemNode = anIter->next() ) {
156             if ( anElemNode == aNode0 ) {
157               aResult0++;
158               if ( !aNode1 ) break; // not a quadratic edge
159             }
160             else if ( anElemNode == aNode1 )
161               aResult1++;
162           }
163         }
164       }
165     }
166     int aResult = std::max ( aResult0, aResult1 );
167
168     return aResult;
169   }
170
171   gp_XYZ getNormale( const SMDS_MeshFace* theFace, bool* ok=0 )
172   {
173     int aNbNode = theFace->NbNodes();
174
175     gp_XYZ q1 = gpXYZ( theFace->GetNode(1)) - gpXYZ( theFace->GetNode(0));
176     gp_XYZ q2 = gpXYZ( theFace->GetNode(2)) - gpXYZ( theFace->GetNode(0));
177     gp_XYZ n  = q1 ^ q2;
178     if ( aNbNode > 3 ) {
179       gp_XYZ q3 = gpXYZ( theFace->GetNode(3)) - gpXYZ( theFace->GetNode(0));
180       n += q2 ^ q3;
181     }
182     double len = n.Modulus();
183     bool zeroLen = ( len <= std::numeric_limits<double>::min());
184     if ( !zeroLen )
185       n /= len;
186
187     if (ok) *ok = !zeroLen;
188
189     return n;
190   }
191 }
192
193
194
195 using namespace SMESH::Controls;
196
197 /*
198  *                               FUNCTORS
199  */
200
201 //================================================================================
202 /*
203   Class       : NumericalFunctor
204   Description : Base class for numerical functors
205 */
206 //================================================================================
207
208 NumericalFunctor::NumericalFunctor():
209   myMesh(NULL)
210 {
211   myPrecision = -1;
212 }
213
214 void NumericalFunctor::SetMesh( const SMDS_Mesh* theMesh )
215 {
216   myMesh = theMesh;
217 }
218
219 bool NumericalFunctor::GetPoints(const int       theId,
220                                  TSequenceOfXYZ& theRes ) const
221 {
222   theRes.clear();
223
224   if ( myMesh == 0 )
225     return false;
226
227   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
228   if ( !anElem || anElem->GetType() != this->GetType() )
229     return false;
230
231   return GetPoints( anElem, theRes );
232 }
233
234 bool NumericalFunctor::GetPoints(const SMDS_MeshElement* anElem,
235                                  TSequenceOfXYZ&         theRes )
236 {
237   theRes.clear();
238
239   if ( anElem == 0 )
240     return false;
241
242   theRes.reserve( anElem->NbNodes() );
243   theRes.setElement( anElem );
244
245   // Get nodes of the element
246   SMDS_ElemIteratorPtr anIter;
247
248   if ( anElem->IsQuadratic() ) {
249     switch ( anElem->GetType() ) {
250     case SMDSAbs_Edge:
251       anIter = dynamic_cast<const SMDS_VtkEdge*>
252         (anElem)->interlacedNodesElemIterator();
253       break;
254     case SMDSAbs_Face:
255       anIter = dynamic_cast<const SMDS_VtkFace*>
256         (anElem)->interlacedNodesElemIterator();
257       break;
258     default:
259       anIter = anElem->nodesIterator();
260     }
261   }
262   else {
263     anIter = anElem->nodesIterator();
264   }
265
266   if ( anIter ) {
267     SMESH_NodeXYZ p;
268     while( anIter->more() ) {
269       if ( p.Set( anIter->next() ))
270         theRes.push_back( p );
271     }
272   }
273
274   return true;
275 }
276
277 long  NumericalFunctor::GetPrecision() const
278 {
279   return myPrecision;
280 }
281
282 void  NumericalFunctor::SetPrecision( const long thePrecision )
283 {
284   myPrecision = thePrecision;
285   myPrecisionValue = pow( 10., (double)( myPrecision ) );
286 }
287
288 double NumericalFunctor::GetValue( long theId )
289 {
290   double aVal = 0;
291
292   myCurrElement = myMesh->FindElement( theId );
293
294   TSequenceOfXYZ P;
295   if ( GetPoints( theId, P )) // elem type is checked here
296     aVal = Round( GetValue( P ));
297
298   return aVal;
299 }
300
301 double NumericalFunctor::Round( const double & aVal )
302 {
303   return ( myPrecision >= 0 ) ? floor( aVal * myPrecisionValue + 0.5 ) / myPrecisionValue : aVal;
304 }
305
306 //================================================================================
307 /*!
308  * \brief Return histogram of functor values
309  *  \param nbIntervals - number of intervals
310  *  \param nbEvents - number of mesh elements having values within i-th interval
311  *  \param funValues - boundaries of intervals
312  *  \param elements - elements to check vulue of; empty list means "of all"
313  *  \param minmax - boundaries of diapason of values to divide into intervals
314  */
315 //================================================================================
316
317 void NumericalFunctor::GetHistogram(int                     nbIntervals,
318                                     std::vector<int>&       nbEvents,
319                                     std::vector<double>&    funValues,
320                                     const std::vector<int>& elements,
321                                     const double*           minmax,
322                                     const bool              isLogarithmic)
323 {
324   if ( nbIntervals < 1 ||
325        !myMesh ||
326        !myMesh->GetMeshInfo().NbElements( GetType() ))
327     return;
328   nbEvents.resize( nbIntervals, 0 );
329   funValues.resize( nbIntervals+1 );
330
331   // get all values sorted
332   std::multiset< double > values;
333   if ( elements.empty() )
334   {
335     SMDS_ElemIteratorPtr elemIt = myMesh->elementsIterator( GetType() );
336     while ( elemIt->more() )
337       values.insert( GetValue( elemIt->next()->GetID() ));
338   }
339   else
340   {
341     std::vector<int>::const_iterator id = elements.begin();
342     for ( ; id != elements.end(); ++id )
343       values.insert( GetValue( *id ));
344   }
345
346   if ( minmax )
347   {
348     funValues[0] = minmax[0];
349     funValues[nbIntervals] = minmax[1];
350   }
351   else
352   {
353     funValues[0] = *values.begin();
354     funValues[nbIntervals] = *values.rbegin();
355   }
356   // case nbIntervals == 1
357   if ( nbIntervals == 1 )
358   {
359     nbEvents[0] = values.size();
360     return;
361   }
362   // case of 1 value
363   if (funValues.front() == funValues.back())
364   {
365     nbEvents.resize( 1 );
366     nbEvents[0] = values.size();
367     funValues[1] = funValues.back();
368     funValues.resize( 2 );
369   }
370   // generic case
371   std::multiset< double >::iterator min = values.begin(), max;
372   for ( int i = 0; i < nbIntervals; ++i )
373   {
374     // find end value of i-th interval
375     double r = (i+1) / double(nbIntervals);
376     if (isLogarithmic && funValues.front() > 1e-07 && funValues.back() > 1e-07) {
377       double logmin = log10(funValues.front());
378       double lval = logmin + r * (log10(funValues.back()) - logmin);
379       funValues[i+1] = pow(10.0, lval);
380     }
381     else {
382       funValues[i+1] = funValues.front() * (1-r) + funValues.back() * r;
383     }
384
385     // count values in the i-th interval if there are any
386     if ( min != values.end() && *min <= funValues[i+1] )
387     {
388       // find the first value out of the interval
389       max = values.upper_bound( funValues[i+1] ); // max is greater than funValues[i+1], or end()
390       nbEvents[i] = std::distance( min, max );
391       min = max;
392     }
393   }
394   // add values larger than minmax[1]
395   nbEvents.back() += std::distance( min, values.end() );
396 }
397
398 //=======================================================================
399 /*
400   Class       : Volume
401   Description : Functor calculating volume of a 3D element
402 */
403 //================================================================================
404
405 double Volume::GetValue( long theElementId )
406 {
407   if ( theElementId && myMesh ) {
408     SMDS_VolumeTool aVolumeTool;
409     if ( aVolumeTool.Set( myMesh->FindElement( theElementId )))
410       return aVolumeTool.GetSize();
411   }
412   return 0;
413 }
414
415 double Volume::GetBadRate( double Value, int /*nbNodes*/ ) const
416 {
417   return Value;
418 }
419
420 SMDSAbs_ElementType Volume::GetType() const
421 {
422   return SMDSAbs_Volume;
423 }
424
425 //=======================================================================
426 /*
427   Class       : MaxElementLength2D
428   Description : Functor calculating maximum length of 2D element
429 */
430 //================================================================================
431
432 double MaxElementLength2D::GetValue( const TSequenceOfXYZ& P )
433 {
434   if(P.size() == 0)
435     return 0.;
436   double aVal = 0;
437   int len = P.size();
438   if( len == 3 ) { // triangles
439     double L1 = getDistance(P( 1 ),P( 2 ));
440     double L2 = getDistance(P( 2 ),P( 3 ));
441     double L3 = getDistance(P( 3 ),P( 1 ));
442     aVal = Max(L1,Max(L2,L3));
443   }
444   else if( len == 4 ) { // quadrangles
445     double L1 = getDistance(P( 1 ),P( 2 ));
446     double L2 = getDistance(P( 2 ),P( 3 ));
447     double L3 = getDistance(P( 3 ),P( 4 ));
448     double L4 = getDistance(P( 4 ),P( 1 ));
449     double D1 = getDistance(P( 1 ),P( 3 ));
450     double D2 = getDistance(P( 2 ),P( 4 ));
451     aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2));
452   }
453   else if( len == 6 ) { // quadratic triangles
454     double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
455     double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
456     double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 ));
457     aVal = Max(L1,Max(L2,L3));
458   }
459   else if( len == 8 || len == 9 ) { // quadratic quadrangles
460     double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
461     double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
462     double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 ));
463     double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 ));
464     double D1 = getDistance(P( 1 ),P( 5 ));
465     double D2 = getDistance(P( 3 ),P( 7 ));
466     aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2));
467   }
468   // Diagonals are undefined for concave polygons
469   // else if ( P.getElementEntity() == SMDSEntity_Quad_Polygon && P.size() > 2 ) // quad polygon
470   // {
471   //   // sides
472   //   aVal = getDistance( P( 1 ), P( P.size() )) + getDistance( P( P.size() ), P( P.size()-1 ));
473   //   for ( size_t i = 1; i < P.size()-1; i += 2 )
474   //   {
475   //     double L = getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 ));
476   //     aVal = Max( aVal, L );
477   //   }
478   //   // diagonals
479   //   for ( int i = P.size()-5; i > 0; i -= 2 )
480   //     for ( int j = i + 4; j < P.size() + i - 2; i += 2 )
481   //     {
482   //       double D = getDistance( P( i ), P( j ));
483   //       aVal = Max( aVal, D );
484   //     }
485   // }
486   // { // polygons
487     
488   // }
489
490   if( myPrecision >= 0 )
491   {
492     double prec = pow( 10., (double)myPrecision );
493     aVal = floor( aVal * prec + 0.5 ) / prec;
494   }
495   return aVal;
496 }
497
498 double MaxElementLength2D::GetValue( long theElementId )
499 {
500   TSequenceOfXYZ P;
501   return GetPoints( theElementId, P ) ? GetValue(P) : 0.0;
502 }
503
504 double MaxElementLength2D::GetBadRate( double Value, int /*nbNodes*/ ) const
505 {
506   return Value;
507 }
508
509 SMDSAbs_ElementType MaxElementLength2D::GetType() const
510 {
511   return SMDSAbs_Face;
512 }
513
514 //=======================================================================
515 /*
516   Class       : MaxElementLength3D
517   Description : Functor calculating maximum length of 3D element
518 */
519 //================================================================================
520
521 double MaxElementLength3D::GetValue( long theElementId )
522 {
523   TSequenceOfXYZ P;
524   if( GetPoints( theElementId, P ) ) {
525     double aVal = 0;
526     const SMDS_MeshElement* aElem = myMesh->FindElement( theElementId );
527     SMDSAbs_EntityType      aType = aElem->GetEntityType();
528     int len = P.size();
529     switch ( aType ) {
530     case SMDSEntity_Tetra: { // tetras
531       double L1 = getDistance(P( 1 ),P( 2 ));
532       double L2 = getDistance(P( 2 ),P( 3 ));
533       double L3 = getDistance(P( 3 ),P( 1 ));
534       double L4 = getDistance(P( 1 ),P( 4 ));
535       double L5 = getDistance(P( 2 ),P( 4 ));
536       double L6 = getDistance(P( 3 ),P( 4 ));
537       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
538       break;
539     }
540     case SMDSEntity_Pyramid: { // pyramids
541       double L1 = getDistance(P( 1 ),P( 2 ));
542       double L2 = getDistance(P( 2 ),P( 3 ));
543       double L3 = getDistance(P( 3 ),P( 4 ));
544       double L4 = getDistance(P( 4 ),P( 1 ));
545       double L5 = getDistance(P( 1 ),P( 5 ));
546       double L6 = getDistance(P( 2 ),P( 5 ));
547       double L7 = getDistance(P( 3 ),P( 5 ));
548       double L8 = getDistance(P( 4 ),P( 5 ));
549       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
550       aVal = Max(aVal,Max(L7,L8));
551       break;
552     }
553     case SMDSEntity_Penta: { // pentas
554       double L1 = getDistance(P( 1 ),P( 2 ));
555       double L2 = getDistance(P( 2 ),P( 3 ));
556       double L3 = getDistance(P( 3 ),P( 1 ));
557       double L4 = getDistance(P( 4 ),P( 5 ));
558       double L5 = getDistance(P( 5 ),P( 6 ));
559       double L6 = getDistance(P( 6 ),P( 4 ));
560       double L7 = getDistance(P( 1 ),P( 4 ));
561       double L8 = getDistance(P( 2 ),P( 5 ));
562       double L9 = getDistance(P( 3 ),P( 6 ));
563       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
564       aVal = Max(aVal,Max(Max(L7,L8),L9));
565       break;
566     }
567     case SMDSEntity_Hexa: { // hexas
568       double L1 = getDistance(P( 1 ),P( 2 ));
569       double L2 = getDistance(P( 2 ),P( 3 ));
570       double L3 = getDistance(P( 3 ),P( 4 ));
571       double L4 = getDistance(P( 4 ),P( 1 ));
572       double L5 = getDistance(P( 5 ),P( 6 ));
573       double L6 = getDistance(P( 6 ),P( 7 ));
574       double L7 = getDistance(P( 7 ),P( 8 ));
575       double L8 = getDistance(P( 8 ),P( 5 ));
576       double L9 = getDistance(P( 1 ),P( 5 ));
577       double L10= getDistance(P( 2 ),P( 6 ));
578       double L11= getDistance(P( 3 ),P( 7 ));
579       double L12= getDistance(P( 4 ),P( 8 ));
580       double D1 = getDistance(P( 1 ),P( 7 ));
581       double D2 = getDistance(P( 2 ),P( 8 ));
582       double D3 = getDistance(P( 3 ),P( 5 ));
583       double D4 = getDistance(P( 4 ),P( 6 ));
584       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
585       aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10)));
586       aVal = Max(aVal,Max(L11,L12));
587       aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4)));
588       break;
589     }
590     case SMDSEntity_Hexagonal_Prism: { // hexagonal prism
591       for ( int i1 = 1; i1 < 12; ++i1 )
592         for ( int i2 = i1+1; i1 <= 12; ++i1 )
593           aVal = Max( aVal, getDistance(P( i1 ),P( i2 )));
594       break;
595     }
596     case SMDSEntity_Quad_Tetra: { // quadratic tetras
597       double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 ));
598       double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 ));
599       double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 ));
600       double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
601       double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 ));
602       double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 ));
603       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
604       break;
605     }
606     case SMDSEntity_Quad_Pyramid: { // quadratic pyramids
607       double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 ));
608       double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 ));
609       double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
610       double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
611       double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
612       double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 ));
613       double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 ));
614       double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 ));
615       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
616       aVal = Max(aVal,Max(L7,L8));
617       break;
618     }
619     case SMDSEntity_Quad_Penta:
620     case SMDSEntity_BiQuad_Penta: { // quadratic pentas
621       double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 ));
622       double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 ));
623       double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
624       double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
625       double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 ));
626       double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 ));
627       double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 ));
628       double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 ));
629       double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 ));
630       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
631       aVal = Max(aVal,Max(Max(L7,L8),L9));
632       break;
633     }
634     case SMDSEntity_Quad_Hexa:
635     case SMDSEntity_TriQuad_Hexa: { // quadratic hexas
636       double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 ));
637       double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 ));
638       double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 ));
639       double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 ));
640       double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 ));
641       double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 ));
642       double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 ));
643       double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 ));
644       double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 ));
645       double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 ));
646       double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 ));
647       double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 ));
648       double D1 = getDistance(P( 1 ),P( 7 ));
649       double D2 = getDistance(P( 2 ),P( 8 ));
650       double D3 = getDistance(P( 3 ),P( 5 ));
651       double D4 = getDistance(P( 4 ),P( 6 ));
652       aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6));
653       aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10)));
654       aVal = Max(aVal,Max(L11,L12));
655       aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4)));
656       break;
657     }
658     case SMDSEntity_Quad_Polyhedra:
659     case SMDSEntity_Polyhedra: { // polys
660       // get the maximum distance between all pairs of nodes
661       for( int i = 1; i <= len; i++ ) {
662         for( int j = 1; j <= len; j++ ) {
663           if( j > i ) { // optimization of the loop
664             double D = getDistance( P(i), P(j) );
665             aVal = Max( aVal, D );
666           }
667         }
668       }
669       break;
670     }
671     case SMDSEntity_Node:
672     case SMDSEntity_0D:
673     case SMDSEntity_Edge:
674     case SMDSEntity_Quad_Edge:
675     case SMDSEntity_Triangle:
676     case SMDSEntity_Quad_Triangle:
677     case SMDSEntity_BiQuad_Triangle:
678     case SMDSEntity_Quadrangle:
679     case SMDSEntity_Quad_Quadrangle:
680     case SMDSEntity_BiQuad_Quadrangle:
681     case SMDSEntity_Polygon:
682     case SMDSEntity_Quad_Polygon:
683     case SMDSEntity_Ball:
684     case SMDSEntity_Last: return 0;
685     } // switch ( aType )
686
687     if( myPrecision >= 0 )
688     {
689       double prec = pow( 10., (double)myPrecision );
690       aVal = floor( aVal * prec + 0.5 ) / prec;
691     }
692     return aVal;
693   }
694   return 0.;
695 }
696
697 double MaxElementLength3D::GetBadRate( double Value, int /*nbNodes*/ ) const
698 {
699   return Value;
700 }
701
702 SMDSAbs_ElementType MaxElementLength3D::GetType() const
703 {
704   return SMDSAbs_Volume;
705 }
706
707 //=======================================================================
708 /*
709   Class       : MinimumAngle
710   Description : Functor for calculation of minimum angle
711 */
712 //================================================================================
713
714 double MinimumAngle::GetValue( const TSequenceOfXYZ& P )
715 {
716   double aMin;
717
718   if (P.size() <3)
719     return 0.;
720
721   aMin = getAngle(P( P.size() ), P( 1 ), P( 2 ));
722   aMin = Min(aMin,getAngle(P( P.size()-1 ), P( P.size() ), P( 1 )));
723
724   for ( size_t i = 2; i < P.size(); i++ )
725   {
726     double A0 = getAngle( P( i-1 ), P( i ), P( i+1 ) );
727     aMin = Min(aMin,A0);
728   }
729
730   return aMin * 180.0 / M_PI;
731 }
732
733 double MinimumAngle::GetBadRate( double Value, int nbNodes ) const
734 {
735   //const double aBestAngle = PI / nbNodes;
736   const double aBestAngle = 180.0 - ( 360.0 / double(nbNodes) );
737   return ( fabs( aBestAngle - Value ));
738 }
739
740 SMDSAbs_ElementType MinimumAngle::GetType() const
741 {
742   return SMDSAbs_Face;
743 }
744
745
746 //================================================================================
747 /*
748   Class       : AspectRatio
749   Description : Functor for calculating aspect ratio
750 */
751 //================================================================================
752
753 double AspectRatio::GetValue( long theId )
754 {
755   double aVal = 0;
756   myCurrElement = myMesh->FindElement( theId );
757   if ( myCurrElement && myCurrElement->GetVtkType() == VTK_QUAD )
758   {
759     // issue 21723
760     vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid();
761     if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() ))
762       aVal = Round( vtkMeshQuality::QuadAspectRatio( avtkCell ));
763   }
764   else
765   {
766     TSequenceOfXYZ P;
767     if ( GetPoints( myCurrElement, P ))
768       aVal = Round( GetValue( P ));
769   }
770   return aVal;
771 }
772
773 double AspectRatio::GetValue( const TSequenceOfXYZ& P )
774 {
775   // According to "Mesh quality control" by Nadir Bouhamau referring to
776   // Pascal Jean Frey and Paul-Louis George. Maillages, applications aux elements finis.
777   // Hermes Science publications, Paris 1999 ISBN 2-7462-0024-4
778   // PAL10872
779
780   int nbNodes = P.size();
781
782   if ( nbNodes < 3 )
783     return 0;
784
785   // Compute aspect ratio
786
787   if ( nbNodes == 3 ) {
788     // Compute lengths of the sides
789     std::vector< double > aLen (nbNodes);
790     for ( int i = 0; i < nbNodes - 1; i++ )
791       aLen[ i ] = getDistance( P( i + 1 ), P( i + 2 ) );
792     aLen[ nbNodes - 1 ] = getDistance( P( 1 ), P( nbNodes ) );
793     // Q = alfa * h * p / S, where
794     //
795     // alfa = sqrt( 3 ) / 6
796     // h - length of the longest edge
797     // p - half perimeter
798     // S - triangle surface
799     const double alfa = sqrt( 3. ) / 6.;
800     double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) );
801     double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.;
802     double anArea = getArea( P( 1 ), P( 2 ), P( 3 ) );
803     if ( anArea <= theEps  )
804       return theInf;
805     return alfa * maxLen * half_perimeter / anArea;
806   }
807   else if ( nbNodes == 6 ) { // quadratic triangles
808     // Compute lengths of the sides
809     std::vector< double > aLen (3);
810     aLen[0] = getDistance( P(1), P(3) );
811     aLen[1] = getDistance( P(3), P(5) );
812     aLen[2] = getDistance( P(5), P(1) );
813     // Q = alfa * h * p / S, where
814     //
815     // alfa = sqrt( 3 ) / 6
816     // h - length of the longest edge
817     // p - half perimeter
818     // S - triangle surface
819     const double alfa = sqrt( 3. ) / 6.;
820     double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) );
821     double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.;
822     double anArea = getArea( P(1), P(3), P(5) );
823     if ( anArea <= theEps )
824       return theInf;
825     return alfa * maxLen * half_perimeter / anArea;
826   }
827   else if( nbNodes == 4 ) { // quadrangle
828     // Compute lengths of the sides
829     std::vector< double > aLen (4);
830     aLen[0] = getDistance( P(1), P(2) );
831     aLen[1] = getDistance( P(2), P(3) );
832     aLen[2] = getDistance( P(3), P(4) );
833     aLen[3] = getDistance( P(4), P(1) );
834     // Compute lengths of the diagonals
835     std::vector< double > aDia (2);
836     aDia[0] = getDistance( P(1), P(3) );
837     aDia[1] = getDistance( P(2), P(4) );
838     // Compute areas of all triangles which can be built
839     // taking three nodes of the quadrangle
840     std::vector< double > anArea (4);
841     anArea[0] = getArea( P(1), P(2), P(3) );
842     anArea[1] = getArea( P(1), P(2), P(4) );
843     anArea[2] = getArea( P(1), P(3), P(4) );
844     anArea[3] = getArea( P(2), P(3), P(4) );
845     // Q = alpha * L * C1 / C2, where
846     //
847     // alpha = sqrt( 1/32 )
848     // L = max( L1, L2, L3, L4, D1, D2 )
849     // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 )
850     // C2 = min( S1, S2, S3, S4 )
851     // Li - lengths of the edges
852     // Di - lengths of the diagonals
853     // Si - areas of the triangles
854     const double alpha = sqrt( 1 / 32. );
855     double L = Max( aLen[ 0 ],
856                  Max( aLen[ 1 ],
857                    Max( aLen[ 2 ],
858                      Max( aLen[ 3 ],
859                        Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) );
860     double C1 = sqrt( ( aLen[0] * aLen[0] +
861                         aLen[1] * aLen[1] +
862                         aLen[2] * aLen[2] +
863                         aLen[3] * aLen[3] ) / 4. );
864     double C2 = Min( anArea[ 0 ],
865                   Min( anArea[ 1 ],
866                     Min( anArea[ 2 ], anArea[ 3 ] ) ) );
867     if ( C2 <= theEps )
868       return theInf;
869     return alpha * L * C1 / C2;
870   }
871   else if( nbNodes == 8 || nbNodes == 9 ) { // nbNodes==8 - quadratic quadrangle
872     // Compute lengths of the sides
873     std::vector< double > aLen (4);
874     aLen[0] = getDistance( P(1), P(3) );
875     aLen[1] = getDistance( P(3), P(5) );
876     aLen[2] = getDistance( P(5), P(7) );
877     aLen[3] = getDistance( P(7), P(1) );
878     // Compute lengths of the diagonals
879     std::vector< double > aDia (2);
880     aDia[0] = getDistance( P(1), P(5) );
881     aDia[1] = getDistance( P(3), P(7) );
882     // Compute areas of all triangles which can be built
883     // taking three nodes of the quadrangle
884     std::vector< double > anArea (4);
885     anArea[0] = getArea( P(1), P(3), P(5) );
886     anArea[1] = getArea( P(1), P(3), P(7) );
887     anArea[2] = getArea( P(1), P(5), P(7) );
888     anArea[3] = getArea( P(3), P(5), P(7) );
889     // Q = alpha * L * C1 / C2, where
890     //
891     // alpha = sqrt( 1/32 )
892     // L = max( L1, L2, L3, L4, D1, D2 )
893     // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 )
894     // C2 = min( S1, S2, S3, S4 )
895     // Li - lengths of the edges
896     // Di - lengths of the diagonals
897     // Si - areas of the triangles
898     const double alpha = sqrt( 1 / 32. );
899     double L = Max( aLen[ 0 ],
900                  Max( aLen[ 1 ],
901                    Max( aLen[ 2 ],
902                      Max( aLen[ 3 ],
903                        Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) );
904     double C1 = sqrt( ( aLen[0] * aLen[0] +
905                         aLen[1] * aLen[1] +
906                         aLen[2] * aLen[2] +
907                         aLen[3] * aLen[3] ) / 4. );
908     double C2 = Min( anArea[ 0 ],
909                   Min( anArea[ 1 ],
910                     Min( anArea[ 2 ], anArea[ 3 ] ) ) );
911     if ( C2 <= theEps )
912       return theInf;
913     return alpha * L * C1 / C2;
914   }
915   return 0;
916 }
917
918 double AspectRatio::GetBadRate( double Value, int /*nbNodes*/ ) const
919 {
920   // the aspect ratio is in the range [1.0,infinity]
921   // < 1.0 = very bad, zero area
922   // 1.0 = good
923   // infinity = bad
924   return ( Value < 0.9 ) ? 1000 : Value / 1000.;
925 }
926
927 SMDSAbs_ElementType AspectRatio::GetType() const
928 {
929   return SMDSAbs_Face;
930 }
931
932
933 //================================================================================
934 /*
935   Class       : AspectRatio3D
936   Description : Functor for calculating aspect ratio
937 */
938 //================================================================================
939
940 namespace{
941
942   inline double getHalfPerimeter(double theTria[3]){
943     return (theTria[0] + theTria[1] + theTria[2])/2.0;
944   }
945
946   inline double getArea(double theHalfPerim, double theTria[3]){
947     return sqrt(theHalfPerim*
948                 (theHalfPerim-theTria[0])*
949                 (theHalfPerim-theTria[1])*
950                 (theHalfPerim-theTria[2]));
951   }
952
953   inline double getVolume(double theLen[6]){
954     double a2 = theLen[0]*theLen[0];
955     double b2 = theLen[1]*theLen[1];
956     double c2 = theLen[2]*theLen[2];
957     double d2 = theLen[3]*theLen[3];
958     double e2 = theLen[4]*theLen[4];
959     double f2 = theLen[5]*theLen[5];
960     double P = 4.0*a2*b2*d2;
961     double Q = a2*(b2+d2-e2)-b2*(a2+d2-f2)-d2*(a2+b2-c2);
962     double R = (b2+d2-e2)*(a2+d2-f2)*(a2+d2-f2);
963     return sqrt(P-Q+R)/12.0;
964   }
965
966   inline double getVolume2(double theLen[6]){
967     double a2 = theLen[0]*theLen[0];
968     double b2 = theLen[1]*theLen[1];
969     double c2 = theLen[2]*theLen[2];
970     double d2 = theLen[3]*theLen[3];
971     double e2 = theLen[4]*theLen[4];
972     double f2 = theLen[5]*theLen[5];
973
974     double P = a2*e2*(b2+c2+d2+f2-a2-e2);
975     double Q = b2*f2*(a2+c2+d2+e2-b2-f2);
976     double R = c2*d2*(a2+b2+e2+f2-c2-d2);
977     double S = a2*b2*d2+b2*c2*e2+a2*c2*f2+d2*e2*f2;
978
979     return sqrt(P+Q+R-S)/12.0;
980   }
981
982   inline double getVolume(const TSequenceOfXYZ& P){
983     gp_Vec aVec1( P( 2 ) - P( 1 ) );
984     gp_Vec aVec2( P( 3 ) - P( 1 ) );
985     gp_Vec aVec3( P( 4 ) - P( 1 ) );
986     gp_Vec anAreaVec( aVec1 ^ aVec2 );
987     return fabs(aVec3 * anAreaVec) / 6.0;
988   }
989
990   inline double getMaxHeight(double theLen[6])
991   {
992     double aHeight = std::max(theLen[0],theLen[1]);
993     aHeight = std::max(aHeight,theLen[2]);
994     aHeight = std::max(aHeight,theLen[3]);
995     aHeight = std::max(aHeight,theLen[4]);
996     aHeight = std::max(aHeight,theLen[5]);
997     return aHeight;
998   }
999
1000 }
1001
1002 double AspectRatio3D::GetValue( long theId )
1003 {
1004   double aVal = 0;
1005   myCurrElement = myMesh->FindElement( theId );
1006   if ( myCurrElement && myCurrElement->GetVtkType() == VTK_TETRA )
1007   {
1008     // Action from CoTech | ACTION 31.3:
1009     // EURIWARE BO: Homogenize the formulas used to calculate the Controls in SMESH to fit with
1010     // those of ParaView. The library used by ParaView for those calculations can be reused in SMESH.
1011     vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid();
1012     if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() ))
1013       aVal = Round( vtkMeshQuality::TetAspectRatio( avtkCell ));
1014   }
1015   else
1016   {
1017     TSequenceOfXYZ P;
1018     if ( GetPoints( myCurrElement, P ))
1019       aVal = Round( GetValue( P ));
1020   }
1021   return aVal;
1022 }
1023
1024 double AspectRatio3D::GetValue( const TSequenceOfXYZ& P )
1025 {
1026   double aQuality = 0.0;
1027   if(myCurrElement->IsPoly()) return aQuality;
1028
1029   int nbNodes = P.size();
1030
1031   if(myCurrElement->IsQuadratic()) {
1032     if(nbNodes==10) nbNodes=4; // quadratic tetrahedron
1033     else if(nbNodes==13) nbNodes=5; // quadratic pyramid
1034     else if(nbNodes==15) nbNodes=6; // quadratic pentahedron
1035     else if(nbNodes==20) nbNodes=8; // quadratic hexahedron
1036     else if(nbNodes==27) nbNodes=8; // quadratic hexahedron
1037     else return aQuality;
1038   }
1039
1040   switch(nbNodes) {
1041   case 4:{
1042     double aLen[6] = {
1043       getDistance(P( 1 ),P( 2 )), // a
1044       getDistance(P( 2 ),P( 3 )), // b
1045       getDistance(P( 3 ),P( 1 )), // c
1046       getDistance(P( 2 ),P( 4 )), // d
1047       getDistance(P( 3 ),P( 4 )), // e
1048       getDistance(P( 1 ),P( 4 ))  // f
1049     };
1050     double aTria[4][3] = {
1051       {aLen[0],aLen[1],aLen[2]}, // abc
1052       {aLen[0],aLen[3],aLen[5]}, // adf
1053       {aLen[1],aLen[3],aLen[4]}, // bde
1054       {aLen[2],aLen[4],aLen[5]}  // cef
1055     };
1056     double aSumArea = 0.0;
1057     double aHalfPerimeter = getHalfPerimeter(aTria[0]);
1058     double anArea = getArea(aHalfPerimeter,aTria[0]);
1059     aSumArea += anArea;
1060     aHalfPerimeter = getHalfPerimeter(aTria[1]);
1061     anArea = getArea(aHalfPerimeter,aTria[1]);
1062     aSumArea += anArea;
1063     aHalfPerimeter = getHalfPerimeter(aTria[2]);
1064     anArea = getArea(aHalfPerimeter,aTria[2]);
1065     aSumArea += anArea;
1066     aHalfPerimeter = getHalfPerimeter(aTria[3]);
1067     anArea = getArea(aHalfPerimeter,aTria[3]);
1068     aSumArea += anArea;
1069     double aVolume = getVolume(P);
1070     //double aVolume = getVolume(aLen);
1071     double aHeight = getMaxHeight(aLen);
1072     static double aCoeff = sqrt(2.0)/12.0;
1073     if ( aVolume > DBL_MIN )
1074       aQuality = aCoeff*aHeight*aSumArea/aVolume;
1075     break;
1076   }
1077   case 5:{
1078     {
1079       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 3 ),P( 5 )};
1080       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1081     }
1082     {
1083       gp_XYZ aXYZ[4] = {P( 1 ),P( 3 ),P( 4 ),P( 5 )};
1084       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1085     }
1086     {
1087       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 5 )};
1088       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1089     }
1090     {
1091       gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 4 ),P( 5 )};
1092       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1093     }
1094     break;
1095   }
1096   case 6:{
1097     {
1098       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 6 )};
1099       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1100     }
1101     {
1102       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 3 )};
1103       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1104     }
1105     {
1106       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 6 )};
1107       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1108     }
1109     {
1110       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )};
1111       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1112     }
1113     {
1114       gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 6 )};
1115       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1116     }
1117     {
1118       gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 3 )};
1119       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1120     }
1121     break;
1122   }
1123   case 8:{
1124     {
1125       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )};
1126       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1127     }
1128     {
1129       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 4 )};
1130       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1131     }
1132     {
1133       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 7 )};
1134       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1135     }
1136     {
1137       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 8 )};
1138       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1139     }
1140     {
1141       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 3 )};
1142       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1143     }
1144     {
1145       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 4 )};
1146       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1147     }
1148     {
1149       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 7 )};
1150       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1151     }
1152     {
1153       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 8 )};
1154       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1155     }
1156     {
1157       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 3 )};
1158       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1159     }
1160     {
1161       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 4 )};
1162       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1163     }
1164     {
1165       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 7 )};
1166       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1167     }
1168     {
1169       gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 8 )};
1170       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1171     }
1172     {
1173       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 1 )};
1174       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1175     }
1176     {
1177       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 2 )};
1178       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1179     }
1180     {
1181       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 5 )};
1182       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1183     }
1184     {
1185       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 6 )};
1186       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1187     }
1188     {
1189       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 1 )};
1190       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1191     }
1192     {
1193       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 2 )};
1194       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1195     }
1196     {
1197       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 5 )};
1198       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1199     }
1200     {
1201       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 6 )};
1202       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1203     }
1204     {
1205       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 1 )};
1206       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1207     }
1208     {
1209       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )};
1210       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1211     }
1212     {
1213       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 5 )};
1214       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1215     }
1216     {
1217       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 6 )};
1218       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1219     }
1220     {
1221       gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )};
1222       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1223     }
1224     {
1225       gp_XYZ aXYZ[4] = {P( 4 ),P( 5 ),P( 8 ),P( 2 )};
1226       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1227     }
1228     {
1229       gp_XYZ aXYZ[4] = {P( 1 ),P( 4 ),P( 5 ),P( 3 )};
1230       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1231     }
1232     {
1233       gp_XYZ aXYZ[4] = {P( 3 ),P( 6 ),P( 7 ),P( 1 )};
1234       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1235     }
1236     {
1237       gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 6 ),P( 4 )};
1238       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1239     }
1240     {
1241       gp_XYZ aXYZ[4] = {P( 5 ),P( 6 ),P( 8 ),P( 3 )};
1242       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1243     }
1244     {
1245       gp_XYZ aXYZ[4] = {P( 7 ),P( 8 ),P( 6 ),P( 1 )};
1246       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1247     }
1248     {
1249       gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 7 )};
1250       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1251     }
1252     {
1253       gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 2 ),P( 5 )};
1254       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality);
1255     }
1256     break;
1257   }
1258   case 12:
1259     {
1260       gp_XYZ aXYZ[8] = {P( 1 ),P( 2 ),P( 4 ),P( 5 ),P( 7 ),P( 8 ),P( 10 ),P( 11 )};
1261       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality);
1262     }
1263     {
1264       gp_XYZ aXYZ[8] = {P( 2 ),P( 3 ),P( 5 ),P( 6 ),P( 8 ),P( 9 ),P( 11 ),P( 12 )};
1265       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality);
1266     }
1267     {
1268       gp_XYZ aXYZ[8] = {P( 3 ),P( 4 ),P( 6 ),P( 1 ),P( 9 ),P( 10 ),P( 12 ),P( 7 )};
1269       aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality);
1270     }
1271     break;
1272   } // switch(nbNodes)
1273
1274   if ( nbNodes > 4 ) {
1275     // avaluate aspect ratio of quadranle faces
1276     AspectRatio aspect2D;
1277     SMDS_VolumeTool::VolumeType type = SMDS_VolumeTool::GetType( nbNodes );
1278     int nbFaces = SMDS_VolumeTool::NbFaces( type );
1279     TSequenceOfXYZ points(4);
1280     for ( int i = 0; i < nbFaces; ++i ) { // loop on faces of a volume
1281       if ( SMDS_VolumeTool::NbFaceNodes( type, i ) != 4 )
1282         continue;
1283       const int* pInd = SMDS_VolumeTool::GetFaceNodesIndices( type, i, true );
1284       for ( int p = 0; p < 4; ++p ) // loop on nodes of a quadranle face
1285         points( p + 1 ) = P( pInd[ p ] + 1 );
1286       aQuality = std::max( aQuality, aspect2D.GetValue( points ));
1287     }
1288   }
1289   return aQuality;
1290 }
1291
1292 double AspectRatio3D::GetBadRate( double Value, int /*nbNodes*/ ) const
1293 {
1294   // the aspect ratio is in the range [1.0,infinity]
1295   // 1.0 = good
1296   // infinity = bad
1297   return Value / 1000.;
1298 }
1299
1300 SMDSAbs_ElementType AspectRatio3D::GetType() const
1301 {
1302   return SMDSAbs_Volume;
1303 }
1304
1305
1306 //================================================================================
1307 /*
1308   Class       : Warping
1309   Description : Functor for calculating warping
1310 */
1311 //================================================================================
1312
1313 double Warping::GetValue( const TSequenceOfXYZ& P )
1314 {
1315   if ( P.size() != 4 )
1316     return 0;
1317
1318   gp_XYZ G = ( P( 1 ) + P( 2 ) + P( 3 ) + P( 4 ) ) / 4.;
1319
1320   double A1 = ComputeA( P( 1 ), P( 2 ), P( 3 ), G );
1321   double A2 = ComputeA( P( 2 ), P( 3 ), P( 4 ), G );
1322   double A3 = ComputeA( P( 3 ), P( 4 ), P( 1 ), G );
1323   double A4 = ComputeA( P( 4 ), P( 1 ), P( 2 ), G );
1324
1325   double val = Max( Max( A1, A2 ), Max( A3, A4 ) );
1326
1327   const double eps = 0.1; // val is in degrees
1328
1329   return val < eps ? 0. : val;
1330 }
1331
1332 double Warping::ComputeA( const gp_XYZ& thePnt1,
1333                           const gp_XYZ& thePnt2,
1334                           const gp_XYZ& thePnt3,
1335                           const gp_XYZ& theG ) const
1336 {
1337   double aLen1 = gp_Pnt( thePnt1 ).Distance( gp_Pnt( thePnt2 ) );
1338   double aLen2 = gp_Pnt( thePnt2 ).Distance( gp_Pnt( thePnt3 ) );
1339   double L = Min( aLen1, aLen2 ) * 0.5;
1340   if ( L < theEps )
1341     return theInf;
1342
1343   gp_XYZ GI = ( thePnt2 + thePnt1 ) / 2. - theG;
1344   gp_XYZ GJ = ( thePnt3 + thePnt2 ) / 2. - theG;
1345   gp_XYZ N  = GI.Crossed( GJ );
1346
1347   if ( N.Modulus() < gp::Resolution() )
1348     return M_PI / 2;
1349
1350   N.Normalize();
1351
1352   double H = ( thePnt2 - theG ).Dot( N );
1353   return asin( fabs( H / L ) ) * 180. / M_PI;
1354 }
1355
1356 double Warping::GetBadRate( double Value, int /*nbNodes*/ ) const
1357 {
1358   // the warp is in the range [0.0,PI/2]
1359   // 0.0 = good (no warp)
1360   // PI/2 = bad  (face pliee)
1361   return Value;
1362 }
1363
1364 SMDSAbs_ElementType Warping::GetType() const
1365 {
1366   return SMDSAbs_Face;
1367 }
1368
1369
1370 //================================================================================
1371 /*
1372   Class       : Taper
1373   Description : Functor for calculating taper
1374 */
1375 //================================================================================
1376
1377 double Taper::GetValue( const TSequenceOfXYZ& P )
1378 {
1379   if ( P.size() != 4 )
1380     return 0.;
1381
1382   // Compute taper
1383   double J1 = getArea( P( 4 ), P( 1 ), P( 2 ) );
1384   double J2 = getArea( P( 3 ), P( 1 ), P( 2 ) );
1385   double J3 = getArea( P( 2 ), P( 3 ), P( 4 ) );
1386   double J4 = getArea( P( 3 ), P( 4 ), P( 1 ) );
1387
1388   double JA = 0.25 * ( J1 + J2 + J3 + J4 );
1389   if ( JA <= theEps )
1390     return theInf;
1391
1392   double T1 = fabs( ( J1 - JA ) / JA );
1393   double T2 = fabs( ( J2 - JA ) / JA );
1394   double T3 = fabs( ( J3 - JA ) / JA );
1395   double T4 = fabs( ( J4 - JA ) / JA );
1396
1397   double val = Max( Max( T1, T2 ), Max( T3, T4 ) );
1398
1399   const double eps = 0.01;
1400
1401   return val < eps ? 0. : val;
1402 }
1403
1404 double Taper::GetBadRate( double Value, int /*nbNodes*/ ) const
1405 {
1406   // the taper is in the range [0.0,1.0]
1407   // 0.0 = good (no taper)
1408   // 1.0 = bad  (les cotes opposes sont allignes)
1409   return Value;
1410 }
1411
1412 SMDSAbs_ElementType Taper::GetType() const
1413 {
1414   return SMDSAbs_Face;
1415 }
1416
1417 //================================================================================
1418 /*
1419   Class       : Skew
1420   Description : Functor for calculating skew in degrees
1421 */
1422 //================================================================================
1423
1424 static inline double skewAngle( const gp_XYZ& p1, const gp_XYZ& p2, const gp_XYZ& p3 )
1425 {
1426   gp_XYZ p12 = ( p2 + p1 ) / 2.;
1427   gp_XYZ p23 = ( p3 + p2 ) / 2.;
1428   gp_XYZ p31 = ( p3 + p1 ) / 2.;
1429
1430   gp_Vec v1( p31 - p2 ), v2( p12 - p23 );
1431
1432   return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0. : v1.Angle( v2 );
1433 }
1434
1435 double Skew::GetValue( const TSequenceOfXYZ& P )
1436 {
1437   if ( P.size() != 3 && P.size() != 4 )
1438     return 0.;
1439
1440   // Compute skew
1441   const double PI2 = M_PI / 2.;
1442   if ( P.size() == 3 )
1443   {
1444     double A0 = fabs( PI2 - skewAngle( P( 3 ), P( 1 ), P( 2 ) ) );
1445     double A1 = fabs( PI2 - skewAngle( P( 1 ), P( 2 ), P( 3 ) ) );
1446     double A2 = fabs( PI2 - skewAngle( P( 2 ), P( 3 ), P( 1 ) ) );
1447
1448     return Max( A0, Max( A1, A2 ) ) * 180. / M_PI;
1449   }
1450   else
1451   {
1452     gp_XYZ p12 = ( P( 1 ) + P( 2 ) ) / 2.;
1453     gp_XYZ p23 = ( P( 2 ) + P( 3 ) ) / 2.;
1454     gp_XYZ p34 = ( P( 3 ) + P( 4 ) ) / 2.;
1455     gp_XYZ p41 = ( P( 4 ) + P( 1 ) ) / 2.;
1456
1457     gp_Vec v1( p34 - p12 ), v2( p23 - p41 );
1458     double A = v1.Magnitude() <= gp::Resolution() || v2.Magnitude() <= gp::Resolution()
1459       ? 0. : fabs( PI2 - v1.Angle( v2 ) );
1460
1461     double val = A * 180. / M_PI;
1462
1463     const double eps = 0.1; // val is in degrees
1464
1465     return val < eps ? 0. : val;
1466   }
1467 }
1468
1469 double Skew::GetBadRate( double Value, int /*nbNodes*/ ) const
1470 {
1471   // the skew is in the range [0.0,PI/2].
1472   // 0.0 = good
1473   // PI/2 = bad
1474   return Value;
1475 }
1476
1477 SMDSAbs_ElementType Skew::GetType() const
1478 {
1479   return SMDSAbs_Face;
1480 }
1481
1482
1483 //================================================================================
1484 /*
1485   Class       : Area
1486   Description : Functor for calculating area
1487 */
1488 //================================================================================
1489
1490 double Area::GetValue( const TSequenceOfXYZ& P )
1491 {
1492   double val = 0.0;
1493   if ( P.size() > 2 )
1494   {
1495     gp_Vec aVec1( P(2) - P(1) );
1496     gp_Vec aVec2( P(3) - P(1) );
1497     gp_Vec SumVec = aVec1 ^ aVec2;
1498
1499     for (size_t i=4; i<=P.size(); i++)
1500     {
1501       gp_Vec aVec1( P(i-1) - P(1) );
1502       gp_Vec aVec2( P(i  ) - P(1) );
1503       gp_Vec tmp = aVec1 ^ aVec2;
1504       SumVec.Add(tmp);
1505     }
1506     val = SumVec.Magnitude() * 0.5;
1507   }
1508   return val;
1509 }
1510
1511 double Area::GetBadRate( double Value, int /*nbNodes*/ ) const
1512 {
1513   // meaningless as it is not a quality control functor
1514   return Value;
1515 }
1516
1517 SMDSAbs_ElementType Area::GetType() const
1518 {
1519   return SMDSAbs_Face;
1520 }
1521
1522 //================================================================================
1523 /*
1524   Class       : Length
1525   Description : Functor for calculating length of edge
1526 */
1527 //================================================================================
1528
1529 double Length::GetValue( const TSequenceOfXYZ& P )
1530 {
1531   switch ( P.size() ) {
1532   case 2:  return getDistance( P( 1 ), P( 2 ) );
1533   case 3:  return getDistance( P( 1 ), P( 2 ) ) + getDistance( P( 2 ), P( 3 ) );
1534   default: return 0.;
1535   }
1536 }
1537
1538 double Length::GetBadRate( double Value, int /*nbNodes*/ ) const
1539 {
1540   // meaningless as it is not quality control functor
1541   return Value;
1542 }
1543
1544 SMDSAbs_ElementType Length::GetType() const
1545 {
1546   return SMDSAbs_Edge;
1547 }
1548
1549 //================================================================================
1550 /*
1551   Class       : Length2D
1552   Description : Functor for calculating minimal length of edge
1553 */
1554 //================================================================================
1555
1556 double Length2D::GetValue( const TSequenceOfXYZ& P )
1557 {
1558   double aVal = 0;
1559   int len = P.size();
1560   SMDSAbs_EntityType aType = P.getElementEntity();
1561
1562   switch (aType) {
1563   case SMDSEntity_Edge:
1564     if (len == 2)
1565       aVal = getDistance( P( 1 ), P( 2 ) );
1566     break;
1567   case SMDSEntity_Quad_Edge:
1568     if (len == 3) // quadratic edge
1569       aVal = getDistance(P( 1 ),P( 3 )) + getDistance(P( 3 ),P( 2 ));
1570     break;
1571   case SMDSEntity_Triangle:
1572     if (len == 3){ // triangles
1573       double L1 = getDistance(P( 1 ),P( 2 ));
1574       double L2 = getDistance(P( 2 ),P( 3 ));
1575       double L3 = getDistance(P( 3 ),P( 1 ));
1576       aVal = Min(L1,Min(L2,L3));
1577     }
1578     break;
1579   case SMDSEntity_Quadrangle:
1580     if (len == 4){ // quadrangles
1581       double L1 = getDistance(P( 1 ),P( 2 ));
1582       double L2 = getDistance(P( 2 ),P( 3 ));
1583       double L3 = getDistance(P( 3 ),P( 4 ));
1584       double L4 = getDistance(P( 4 ),P( 1 ));
1585       aVal = Min(Min(L1,L2),Min(L3,L4));
1586     }
1587     break;
1588   case SMDSEntity_Quad_Triangle:
1589   case SMDSEntity_BiQuad_Triangle:
1590     if (len >= 6){ // quadratic triangles
1591       double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
1592       double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
1593       double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 ));
1594       aVal = Min(L1,Min(L2,L3));
1595     }
1596     break;
1597   case SMDSEntity_Quad_Quadrangle:
1598   case SMDSEntity_BiQuad_Quadrangle:
1599     if (len >= 8){ // quadratic quadrangles
1600       double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 ));
1601       double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 ));
1602       double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 ));
1603       double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 ));
1604       aVal = Min(Min(L1,L2),Min(L3,L4));
1605     }
1606     break;
1607   case SMDSEntity_Tetra:
1608     if (len == 4){ // tetrahedra
1609       double L1 = getDistance(P( 1 ),P( 2 ));
1610       double L2 = getDistance(P( 2 ),P( 3 ));
1611       double L3 = getDistance(P( 3 ),P( 1 ));
1612       double L4 = getDistance(P( 1 ),P( 4 ));
1613       double L5 = getDistance(P( 2 ),P( 4 ));
1614       double L6 = getDistance(P( 3 ),P( 4 ));
1615       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1616     }
1617     break;
1618   case SMDSEntity_Pyramid:
1619     if (len == 5){ // pyramid
1620       double L1 = getDistance(P( 1 ),P( 2 ));
1621       double L2 = getDistance(P( 2 ),P( 3 ));
1622       double L3 = getDistance(P( 3 ),P( 4 ));
1623       double L4 = getDistance(P( 4 ),P( 1 ));
1624       double L5 = getDistance(P( 1 ),P( 5 ));
1625       double L6 = getDistance(P( 2 ),P( 5 ));
1626       double L7 = getDistance(P( 3 ),P( 5 ));
1627       double L8 = getDistance(P( 4 ),P( 5 ));
1628
1629       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1630       aVal = Min(aVal,Min(L7,L8));
1631     }
1632     break;
1633   case SMDSEntity_Penta:
1634     if (len == 6) { // pentahedron
1635       double L1 = getDistance(P( 1 ),P( 2 ));
1636       double L2 = getDistance(P( 2 ),P( 3 ));
1637       double L3 = getDistance(P( 3 ),P( 1 ));
1638       double L4 = getDistance(P( 4 ),P( 5 ));
1639       double L5 = getDistance(P( 5 ),P( 6 ));
1640       double L6 = getDistance(P( 6 ),P( 4 ));
1641       double L7 = getDistance(P( 1 ),P( 4 ));
1642       double L8 = getDistance(P( 2 ),P( 5 ));
1643       double L9 = getDistance(P( 3 ),P( 6 ));
1644
1645       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1646       aVal = Min(aVal,Min(Min(L7,L8),L9));
1647     }
1648     break;
1649   case SMDSEntity_Hexa:
1650     if (len == 8){ // hexahedron
1651       double L1 = getDistance(P( 1 ),P( 2 ));
1652       double L2 = getDistance(P( 2 ),P( 3 ));
1653       double L3 = getDistance(P( 3 ),P( 4 ));
1654       double L4 = getDistance(P( 4 ),P( 1 ));
1655       double L5 = getDistance(P( 5 ),P( 6 ));
1656       double L6 = getDistance(P( 6 ),P( 7 ));
1657       double L7 = getDistance(P( 7 ),P( 8 ));
1658       double L8 = getDistance(P( 8 ),P( 5 ));
1659       double L9 = getDistance(P( 1 ),P( 5 ));
1660       double L10= getDistance(P( 2 ),P( 6 ));
1661       double L11= getDistance(P( 3 ),P( 7 ));
1662       double L12= getDistance(P( 4 ),P( 8 ));
1663
1664       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1665       aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10)));
1666       aVal = Min(aVal,Min(L11,L12));
1667     }
1668     break;
1669   case SMDSEntity_Quad_Tetra:
1670     if (len == 10){ // quadratic tetrahedron
1671       double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 ));
1672       double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 ));
1673       double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 ));
1674       double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
1675       double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 ));
1676       double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 ));
1677       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1678     }
1679     break;
1680   case SMDSEntity_Quad_Pyramid:
1681     if (len == 13){ // quadratic pyramid
1682       double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 ));
1683       double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 ));
1684       double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 ));
1685       double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
1686       double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
1687       double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 ));
1688       double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 ));
1689       double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 ));
1690       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1691       aVal = Min(aVal,Min(L7,L8));
1692     }
1693     break;
1694   case SMDSEntity_Quad_Penta:
1695   case SMDSEntity_BiQuad_Penta:
1696     if (len >= 15){ // quadratic pentahedron
1697       double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 ));
1698       double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 ));
1699       double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 ));
1700       double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 ));
1701       double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 ));
1702       double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 ));
1703       double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 ));
1704       double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 ));
1705       double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 ));
1706       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1707       aVal = Min(aVal,Min(Min(L7,L8),L9));
1708     }
1709     break;
1710   case SMDSEntity_Quad_Hexa:
1711   case SMDSEntity_TriQuad_Hexa:
1712     if (len >= 20) { // quadratic hexahedron
1713       double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 ));
1714       double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 ));
1715       double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 ));
1716       double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 ));
1717       double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 ));
1718       double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 ));
1719       double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 ));
1720       double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 ));
1721       double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 ));
1722       double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 ));
1723       double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 ));
1724       double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 ));
1725       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1726       aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10)));
1727       aVal = Min(aVal,Min(L11,L12));
1728     }
1729     break;
1730   case SMDSEntity_Polygon:
1731     if ( len > 1 ) {
1732       aVal = getDistance( P(1), P( P.size() ));
1733       for ( size_t i = 1; i < P.size(); ++i )
1734         aVal = Min( aVal, getDistance( P( i ), P( i+1 )));
1735     }
1736     break;
1737   case SMDSEntity_Quad_Polygon:
1738     if ( len > 2 ) {
1739       aVal = getDistance( P(1), P( P.size() )) + getDistance( P(P.size()), P( P.size()-1 ));
1740       for ( size_t i = 1; i < P.size()-1; i += 2 )
1741         aVal = Min( aVal, getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 )));
1742     }
1743     break;
1744   case SMDSEntity_Hexagonal_Prism:
1745     if (len == 12) { // hexagonal prism
1746       double L1 = getDistance(P( 1 ),P( 2 ));
1747       double L2 = getDistance(P( 2 ),P( 3 ));
1748       double L3 = getDistance(P( 3 ),P( 4 ));
1749       double L4 = getDistance(P( 4 ),P( 5 ));
1750       double L5 = getDistance(P( 5 ),P( 6 ));
1751       double L6 = getDistance(P( 6 ),P( 1 ));
1752
1753       double L7 = getDistance(P( 7 ), P( 8 ));
1754       double L8 = getDistance(P( 8 ), P( 9 ));
1755       double L9 = getDistance(P( 9 ), P( 10 ));
1756       double L10= getDistance(P( 10 ),P( 11 ));
1757       double L11= getDistance(P( 11 ),P( 12 ));
1758       double L12= getDistance(P( 12 ),P( 7 ));
1759
1760       double L13 = getDistance(P( 1 ),P( 7 ));
1761       double L14 = getDistance(P( 2 ),P( 8 ));
1762       double L15 = getDistance(P( 3 ),P( 9 ));
1763       double L16 = getDistance(P( 4 ),P( 10 ));
1764       double L17 = getDistance(P( 5 ),P( 11 ));
1765       double L18 = getDistance(P( 6 ),P( 12 ));
1766       aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6));
1767       aVal = Min(aVal, Min(Min(Min(L7,L8),Min(L9,L10)),Min(L11,L12)));
1768       aVal = Min(aVal, Min(Min(Min(L13,L14),Min(L15,L16)),Min(L17,L18)));
1769     }
1770     break;
1771   case SMDSEntity_Polyhedra:
1772   {
1773   }
1774   break;
1775   default:
1776     return 0;
1777   }
1778
1779   if (aVal < 0 ) {
1780     return 0.;
1781   }
1782
1783   if ( myPrecision >= 0 )
1784   {
1785     double prec = pow( 10., (double)( myPrecision ) );
1786     aVal = floor( aVal * prec + 0.5 ) / prec;
1787   }
1788
1789   return aVal;
1790 }
1791
1792 double Length2D::GetBadRate( double Value, int /*nbNodes*/ ) const
1793 {
1794   // meaningless as it is not a quality control functor
1795   return Value;
1796 }
1797
1798 SMDSAbs_ElementType Length2D::GetType() const
1799 {
1800   return SMDSAbs_Face;
1801 }
1802
1803 Length2D::Value::Value(double theLength,long thePntId1, long thePntId2):
1804   myLength(theLength)
1805 {
1806   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
1807   if(thePntId1 > thePntId2){
1808     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
1809   }
1810 }
1811
1812 bool Length2D::Value::operator<(const Length2D::Value& x) const
1813 {
1814   if(myPntId[0] < x.myPntId[0]) return true;
1815   if(myPntId[0] == x.myPntId[0])
1816     if(myPntId[1] < x.myPntId[1]) return true;
1817   return false;
1818 }
1819
1820 void Length2D::GetValues(TValues& theValues)
1821 {
1822   TValues aValues;
1823   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
1824   for(; anIter->more(); ){
1825     const SMDS_MeshFace* anElem = anIter->next();
1826
1827     if(anElem->IsQuadratic()) {
1828       const SMDS_VtkFace* F =
1829         dynamic_cast<const SMDS_VtkFace*>(anElem);
1830       // use special nodes iterator
1831       SMDS_ElemIteratorPtr anIter = F->interlacedNodesElemIterator();
1832       long aNodeId[4] = { 0,0,0,0 };
1833       gp_Pnt P[4];
1834
1835       double aLength = 0;
1836       const SMDS_MeshElement* aNode;
1837       if(anIter->more()){
1838         aNode = anIter->next();
1839         const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
1840         P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
1841         aNodeId[0] = aNodeId[1] = aNode->GetID();
1842         aLength = 0;
1843       }
1844       for(; anIter->more(); ){
1845         const SMDS_MeshNode* N1 = static_cast<const SMDS_MeshNode*> (anIter->next());
1846         P[2] = gp_Pnt(N1->X(),N1->Y(),N1->Z());
1847         aNodeId[2] = N1->GetID();
1848         aLength = P[1].Distance(P[2]);
1849         if(!anIter->more()) break;
1850         const SMDS_MeshNode* N2 = static_cast<const SMDS_MeshNode*> (anIter->next());
1851         P[3] = gp_Pnt(N2->X(),N2->Y(),N2->Z());
1852         aNodeId[3] = N2->GetID();
1853         aLength += P[2].Distance(P[3]);
1854         Value aValue1(aLength,aNodeId[1],aNodeId[2]);
1855         Value aValue2(aLength,aNodeId[2],aNodeId[3]);
1856         P[1] = P[3];
1857         aNodeId[1] = aNodeId[3];
1858         theValues.insert(aValue1);
1859         theValues.insert(aValue2);
1860       }
1861       aLength += P[2].Distance(P[0]);
1862       Value aValue1(aLength,aNodeId[1],aNodeId[2]);
1863       Value aValue2(aLength,aNodeId[2],aNodeId[0]);
1864       theValues.insert(aValue1);
1865       theValues.insert(aValue2);
1866     }
1867     else {
1868       SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator();
1869       long aNodeId[2] = {0,0};
1870       gp_Pnt P[3];
1871
1872       double aLength;
1873       const SMDS_MeshElement* aNode;
1874       if(aNodesIter->more()){
1875         aNode = aNodesIter->next();
1876         const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
1877         P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
1878         aNodeId[0] = aNodeId[1] = aNode->GetID();
1879         aLength = 0;
1880       }
1881       for(; aNodesIter->more(); ){
1882         aNode = aNodesIter->next();
1883         const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode;
1884         long anId = aNode->GetID();
1885         
1886         P[2] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z());
1887         
1888         aLength = P[1].Distance(P[2]);
1889         
1890         Value aValue(aLength,aNodeId[1],anId);
1891         aNodeId[1] = anId;
1892         P[1] = P[2];
1893         theValues.insert(aValue);
1894       }
1895
1896       aLength = P[0].Distance(P[1]);
1897
1898       Value aValue(aLength,aNodeId[0],aNodeId[1]);
1899       theValues.insert(aValue);
1900     }
1901   }
1902 }
1903
1904 //================================================================================
1905 /*
1906   Class       : Deflection2D
1907   Description : Functor for calculating number of faces conneted to the edge
1908 */
1909 //================================================================================
1910
1911 double Deflection2D::GetValue( const TSequenceOfXYZ& P )
1912 {
1913   if ( myMesh && P.getElement() )
1914   {
1915     // get underlying surface
1916     if ( myShapeIndex != P.getElement()->getshapeId() )
1917     {
1918       mySurface.Nullify();
1919       myShapeIndex = P.getElement()->getshapeId();
1920       const TopoDS_Shape& S =
1921         static_cast< const SMESHDS_Mesh* >( myMesh )->IndexToShape( myShapeIndex );
1922       if ( !S.IsNull() && S.ShapeType() == TopAbs_FACE )
1923       {
1924         mySurface = new ShapeAnalysis_Surface( BRep_Tool::Surface( TopoDS::Face( S )));
1925       }
1926     }
1927     // project gravity center to the surface
1928     if ( !mySurface.IsNull() )
1929     {
1930       gp_XYZ gc(0,0,0);
1931       gp_XY  uv(0,0);
1932       int nbUV = 0;
1933       for ( size_t i = 0; i < P.size(); ++i )
1934       {
1935         gc += P(i+1);
1936
1937         if ( const SMDS_FacePosition* fPos = dynamic_cast<const SMDS_FacePosition*>
1938              ( P.getElement()->GetNode( i )->GetPosition() ))
1939         {
1940           uv.ChangeCoord(1) += fPos->GetUParameter();
1941           uv.ChangeCoord(2) += fPos->GetVParameter();
1942           ++nbUV;
1943         }
1944       }
1945       gc /= P.size();
1946       if ( nbUV ) uv /= nbUV;
1947
1948       double maxLen = MaxElementLength2D().GetValue( P );
1949       double    tol = 1e-3 * maxLen;
1950       if ( uv.X() != 0 && uv.Y() != 0 ) // faster way
1951         mySurface->NextValueOfUV( uv, gc, tol, 0.5 * maxLen );
1952       else
1953         mySurface->ValueOfUV( gc, tol );
1954
1955       return Round( mySurface->Gap() );
1956     }
1957   }
1958   return 0;
1959 }
1960
1961 void Deflection2D::SetMesh( const SMDS_Mesh* theMesh )
1962 {
1963   NumericalFunctor::SetMesh( dynamic_cast<const SMESHDS_Mesh* >( theMesh ));
1964   myShapeIndex = -100;
1965 }
1966
1967 SMDSAbs_ElementType Deflection2D::GetType() const
1968 {
1969   return SMDSAbs_Face;
1970 }
1971
1972 double Deflection2D::GetBadRate( double Value, int /*nbNodes*/ ) const
1973 {
1974   // meaningless as it is not quality control functor
1975   return Value;
1976 }
1977
1978 //================================================================================
1979 /*
1980   Class       : MultiConnection
1981   Description : Functor for calculating number of faces conneted to the edge
1982 */
1983 //================================================================================
1984
1985 double MultiConnection::GetValue( const TSequenceOfXYZ& P )
1986 {
1987   return 0;
1988 }
1989 double MultiConnection::GetValue( long theId )
1990 {
1991   return getNbMultiConnection( myMesh, theId );
1992 }
1993
1994 double MultiConnection::GetBadRate( double Value, int /*nbNodes*/ ) const
1995 {
1996   // meaningless as it is not quality control functor
1997   return Value;
1998 }
1999
2000 SMDSAbs_ElementType MultiConnection::GetType() const
2001 {
2002   return SMDSAbs_Edge;
2003 }
2004
2005 //================================================================================
2006 /*
2007   Class       : MultiConnection2D
2008   Description : Functor for calculating number of faces conneted to the edge
2009 */
2010 //================================================================================
2011
2012 double MultiConnection2D::GetValue( const TSequenceOfXYZ& P )
2013 {
2014   return 0;
2015 }
2016
2017 double MultiConnection2D::GetValue( long theElementId )
2018 {
2019   int aResult = 0;
2020
2021   const SMDS_MeshElement* aFaceElem = myMesh->FindElement(theElementId);
2022   SMDSAbs_ElementType aType = aFaceElem->GetType();
2023
2024   switch (aType) {
2025   case SMDSAbs_Face:
2026     {
2027       int i = 0, len = aFaceElem->NbNodes();
2028       SMDS_ElemIteratorPtr anIter = aFaceElem->nodesIterator();
2029       if (!anIter) break;
2030
2031       const SMDS_MeshNode *aNode, *aNode0 = 0;
2032       TColStd_MapOfInteger aMap, aMapPrev;
2033
2034       for (i = 0; i <= len; i++) {
2035         aMapPrev = aMap;
2036         aMap.Clear();
2037
2038         int aNb = 0;
2039         if (anIter->more()) {
2040           aNode = (SMDS_MeshNode*)anIter->next();
2041         } else {
2042           if (i == len)
2043             aNode = aNode0;
2044           else
2045             break;
2046         }
2047         if (!aNode) break;
2048         if (i == 0) aNode0 = aNode;
2049
2050         SMDS_ElemIteratorPtr anElemIter = aNode->GetInverseElementIterator();
2051         while (anElemIter->more()) {
2052           const SMDS_MeshElement* anElem = anElemIter->next();
2053           if (anElem != 0 && anElem->GetType() == SMDSAbs_Face) {
2054             int anId = anElem->GetID();
2055
2056             aMap.Add(anId);
2057             if (aMapPrev.Contains(anId)) {
2058               aNb++;
2059             }
2060           }
2061         }
2062         aResult = Max(aResult, aNb);
2063       }
2064     }
2065     break;
2066   default:
2067     aResult = 0;
2068   }
2069
2070   return aResult;
2071 }
2072
2073 double MultiConnection2D::GetBadRate( double Value, int /*nbNodes*/ ) const
2074 {
2075   // meaningless as it is not quality control functor
2076   return Value;
2077 }
2078
2079 SMDSAbs_ElementType MultiConnection2D::GetType() const
2080 {
2081   return SMDSAbs_Face;
2082 }
2083
2084 MultiConnection2D::Value::Value(long thePntId1, long thePntId2)
2085 {
2086   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
2087   if(thePntId1 > thePntId2){
2088     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
2089   }
2090 }
2091
2092 bool MultiConnection2D::Value::operator<(const MultiConnection2D::Value& x) const
2093 {
2094   if(myPntId[0] < x.myPntId[0]) return true;
2095   if(myPntId[0] == x.myPntId[0])
2096     if(myPntId[1] < x.myPntId[1]) return true;
2097   return false;
2098 }
2099
2100 void MultiConnection2D::GetValues(MValues& theValues)
2101 {
2102   if ( !myMesh ) return;
2103   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
2104   for(; anIter->more(); ){
2105     const SMDS_MeshFace* anElem = anIter->next();
2106     SMDS_ElemIteratorPtr aNodesIter;
2107     if ( anElem->IsQuadratic() )
2108       aNodesIter = dynamic_cast<const SMDS_VtkFace*>
2109         (anElem)->interlacedNodesElemIterator();
2110     else
2111       aNodesIter = anElem->nodesIterator();
2112     long aNodeId[3] = {0,0,0};
2113
2114     //int aNbConnects=0;
2115     const SMDS_MeshNode* aNode0;
2116     const SMDS_MeshNode* aNode1;
2117     const SMDS_MeshNode* aNode2;
2118     if(aNodesIter->more()){
2119       aNode0 = (SMDS_MeshNode*) aNodesIter->next();
2120       aNode1 = aNode0;
2121       const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode1;
2122       aNodeId[0] = aNodeId[1] = aNodes->GetID();
2123     }
2124     for(; aNodesIter->more(); ) {
2125       aNode2 = (SMDS_MeshNode*) aNodesIter->next();
2126       long anId = aNode2->GetID();
2127       aNodeId[2] = anId;
2128
2129       Value aValue(aNodeId[1],aNodeId[2]);
2130       MValues::iterator aItr = theValues.find(aValue);
2131       if (aItr != theValues.end()){
2132         aItr->second += 1;
2133         //aNbConnects = nb;
2134       }
2135       else {
2136         theValues[aValue] = 1;
2137         //aNbConnects = 1;
2138       }
2139       //cout << "NodeIds: "<<aNodeId[1]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl;
2140       aNodeId[1] = aNodeId[2];
2141       aNode1 = aNode2;
2142     }
2143     Value aValue(aNodeId[0],aNodeId[2]);
2144     MValues::iterator aItr = theValues.find(aValue);
2145     if (aItr != theValues.end()) {
2146       aItr->second += 1;
2147       //aNbConnects = nb;
2148     }
2149     else {
2150       theValues[aValue] = 1;
2151       //aNbConnects = 1;
2152     }
2153     //cout << "NodeIds: "<<aNodeId[0]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl;
2154   }
2155
2156 }
2157
2158 //================================================================================
2159 /*
2160   Class       : BallDiameter
2161   Description : Functor returning diameter of a ball element
2162 */
2163 //================================================================================
2164
2165 double BallDiameter::GetValue( long theId )
2166 {
2167   double diameter = 0;
2168
2169   if ( const SMDS_BallElement* ball =
2170        dynamic_cast<const SMDS_BallElement*>( myMesh->FindElement( theId )))
2171   {
2172     diameter = ball->GetDiameter();
2173   }
2174   return diameter;
2175 }
2176
2177 double BallDiameter::GetBadRate( double Value, int /*nbNodes*/ ) const
2178 {
2179   // meaningless as it is not a quality control functor
2180   return Value;
2181 }
2182
2183 SMDSAbs_ElementType BallDiameter::GetType() const
2184 {
2185   return SMDSAbs_Ball;
2186 }
2187
2188 //================================================================================
2189 /*
2190   Class       : NodeConnectivityNumber
2191   Description : Functor returning number of elements connected to a node
2192 */
2193 //================================================================================
2194
2195 double NodeConnectivityNumber::GetValue( long theId )
2196 {
2197   double nb = 0;
2198
2199   if ( const SMDS_MeshNode* node = myMesh->FindNode( theId ))
2200   {
2201     SMDSAbs_ElementType type;
2202     if ( myMesh->NbVolumes() > 0 )
2203       type = SMDSAbs_Volume;
2204     else if ( myMesh->NbFaces() > 0 )
2205       type = SMDSAbs_Face;
2206     else if ( myMesh->NbEdges() > 0 )
2207       type = SMDSAbs_Edge;
2208     else
2209       return 0;
2210     nb = node->NbInverseElements( type );
2211   }
2212   return nb;
2213 }
2214
2215 double NodeConnectivityNumber::GetBadRate( double Value, int /*nbNodes*/ ) const
2216 {
2217   return Value;
2218 }
2219
2220 SMDSAbs_ElementType NodeConnectivityNumber::GetType() const
2221 {
2222   return SMDSAbs_Node;
2223 }
2224
2225 /*
2226                             PREDICATES
2227 */
2228
2229 //================================================================================
2230 /*
2231   Class       : BadOrientedVolume
2232   Description : Predicate bad oriented volumes
2233 */
2234 //================================================================================
2235
2236 BadOrientedVolume::BadOrientedVolume()
2237 {
2238   myMesh = 0;
2239 }
2240
2241 void BadOrientedVolume::SetMesh( const SMDS_Mesh* theMesh )
2242 {
2243   myMesh = theMesh;
2244 }
2245
2246 bool BadOrientedVolume::IsSatisfy( long theId )
2247 {
2248   if ( myMesh == 0 )
2249     return false;
2250
2251   SMDS_VolumeTool vTool( myMesh->FindElement( theId ));
2252   return !vTool.IsForward();
2253 }
2254
2255 SMDSAbs_ElementType BadOrientedVolume::GetType() const
2256 {
2257   return SMDSAbs_Volume;
2258 }
2259
2260 /*
2261   Class       : BareBorderVolume
2262 */
2263
2264 bool BareBorderVolume::IsSatisfy(long theElementId )
2265 {
2266   SMDS_VolumeTool  myTool;
2267   if ( myTool.Set( myMesh->FindElement(theElementId)))
2268   {
2269     for ( int iF = 0; iF < myTool.NbFaces(); ++iF )
2270       if ( myTool.IsFreeFace( iF ))
2271       {
2272         const SMDS_MeshNode** n = myTool.GetFaceNodes(iF);
2273         std::vector< const SMDS_MeshNode*> nodes( n, n+myTool.NbFaceNodes(iF));
2274         if ( !myMesh->FindElement( nodes, SMDSAbs_Face, /*Nomedium=*/false))
2275           return true;
2276       }
2277   }
2278   return false;
2279 }
2280
2281 //================================================================================
2282 /*
2283   Class       : BareBorderFace
2284 */
2285 //================================================================================
2286
2287 bool BareBorderFace::IsSatisfy(long theElementId )
2288 {
2289   bool ok = false;
2290   if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId))
2291   {
2292     if ( face->GetType() == SMDSAbs_Face )
2293     {
2294       int nbN = face->NbCornerNodes();
2295       for ( int i = 0; i < nbN && !ok; ++i )
2296       {
2297         // check if a link is shared by another face
2298         const SMDS_MeshNode* n1 = face->GetNode( i );
2299         const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN );
2300         SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face );
2301         bool isShared = false;
2302         while ( !isShared && fIt->more() )
2303         {
2304           const SMDS_MeshElement* f = fIt->next();
2305           isShared = ( f != face && f->GetNodeIndex(n2) != -1 );
2306         }
2307         if ( !isShared )
2308         {
2309           const int iQuad = face->IsQuadratic();
2310           myLinkNodes.resize( 2 + iQuad);
2311           myLinkNodes[0] = n1;
2312           myLinkNodes[1] = n2;
2313           if ( iQuad )
2314             myLinkNodes[2] = face->GetNode( i+nbN );
2315           ok = !myMesh->FindElement( myLinkNodes, SMDSAbs_Edge, /*noMedium=*/false);
2316         }
2317       }
2318     }
2319   }
2320   return ok;
2321 }
2322
2323 //================================================================================
2324 /*
2325   Class       : OverConstrainedVolume
2326 */
2327 //================================================================================
2328
2329 bool OverConstrainedVolume::IsSatisfy(long theElementId )
2330 {
2331   // An element is over-constrained if it has N-1 free borders where
2332   // N is the number of edges/faces for a 2D/3D element.
2333   SMDS_VolumeTool  myTool;
2334   if ( myTool.Set( myMesh->FindElement(theElementId)))
2335   {
2336     int nbSharedFaces = 0;
2337     for ( int iF = 0; iF < myTool.NbFaces(); ++iF )
2338       if ( !myTool.IsFreeFace( iF ) && ++nbSharedFaces > 1 )
2339         break;
2340     return ( nbSharedFaces == 1 );
2341   }
2342   return false;
2343 }
2344
2345 //================================================================================
2346 /*
2347   Class       : OverConstrainedFace
2348 */
2349 //================================================================================
2350
2351 bool OverConstrainedFace::IsSatisfy(long theElementId )
2352 {
2353   // An element is over-constrained if it has N-1 free borders where
2354   // N is the number of edges/faces for a 2D/3D element.
2355   if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId))
2356     if ( face->GetType() == SMDSAbs_Face )
2357     {
2358       int nbSharedBorders = 0;
2359       int nbN = face->NbCornerNodes();
2360       for ( int i = 0; i < nbN; ++i )
2361       {
2362         // check if a link is shared by another face
2363         const SMDS_MeshNode* n1 = face->GetNode( i );
2364         const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN );
2365         SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face );
2366         bool isShared = false;
2367         while ( !isShared && fIt->more() )
2368         {
2369           const SMDS_MeshElement* f = fIt->next();
2370           isShared = ( f != face && f->GetNodeIndex(n2) != -1 );
2371         }
2372         if ( isShared && ++nbSharedBorders > 1 )
2373           break;
2374       }
2375       return ( nbSharedBorders == 1 );
2376     }
2377   return false;
2378 }
2379
2380 //================================================================================
2381 /*
2382   Class       : CoincidentNodes
2383   Description : Predicate of Coincident nodes
2384 */
2385 //================================================================================
2386
2387 CoincidentNodes::CoincidentNodes()
2388 {
2389   myToler = 1e-5;
2390 }
2391
2392 bool CoincidentNodes::IsSatisfy( long theElementId )
2393 {
2394   return myCoincidentIDs.Contains( theElementId );
2395 }
2396
2397 SMDSAbs_ElementType CoincidentNodes::GetType() const
2398 {
2399   return SMDSAbs_Node;
2400 }
2401
2402 void CoincidentNodes::SetMesh( const SMDS_Mesh* theMesh )
2403 {
2404   myMeshModifTracer.SetMesh( theMesh );
2405   if ( myMeshModifTracer.IsMeshModified() )
2406   {
2407     TIDSortedNodeSet nodesToCheck;
2408     SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true);
2409     while ( nIt->more() )
2410       nodesToCheck.insert( nodesToCheck.end(), nIt->next() );
2411
2412     std::list< std::list< const SMDS_MeshNode*> > nodeGroups;
2413     SMESH_OctreeNode::FindCoincidentNodes ( nodesToCheck, &nodeGroups, myToler );
2414
2415     myCoincidentIDs.Clear();
2416     std::list< std::list< const SMDS_MeshNode*> >::iterator groupIt = nodeGroups.begin();
2417     for ( ; groupIt != nodeGroups.end(); ++groupIt )
2418     {
2419       std::list< const SMDS_MeshNode*>& coincNodes = *groupIt;
2420       std::list< const SMDS_MeshNode*>::iterator n = coincNodes.begin();
2421       for ( ; n != coincNodes.end(); ++n )
2422         myCoincidentIDs.Add( (*n)->GetID() );
2423     }
2424   }
2425 }
2426
2427 //================================================================================
2428 /*
2429   Class       : CoincidentElements
2430   Description : Predicate of Coincident Elements
2431   Note        : This class is suitable only for visualization of Coincident Elements
2432 */
2433 //================================================================================
2434
2435 CoincidentElements::CoincidentElements()
2436 {
2437   myMesh = 0;
2438 }
2439
2440 void CoincidentElements::SetMesh( const SMDS_Mesh* theMesh )
2441 {
2442   myMesh = theMesh;
2443 }
2444
2445 bool CoincidentElements::IsSatisfy( long theElementId )
2446 {
2447   if ( !myMesh ) return false;
2448
2449   if ( const SMDS_MeshElement* e = myMesh->FindElement( theElementId ))
2450   {
2451     if ( e->GetType() != GetType() ) return false;
2452     std::set< const SMDS_MeshNode* > elemNodes( e->begin_nodes(), e->end_nodes() );
2453     const int nbNodes = e->NbNodes();
2454     SMDS_ElemIteratorPtr invIt = (*elemNodes.begin())->GetInverseElementIterator( GetType() );
2455     while ( invIt->more() )
2456     {
2457       const SMDS_MeshElement* e2 = invIt->next();
2458       if ( e2 == e || e2->NbNodes() != nbNodes ) continue;
2459
2460       bool sameNodes = true;
2461       for ( size_t i = 0; i < elemNodes.size() && sameNodes; ++i )
2462         sameNodes = ( elemNodes.count( e2->GetNode( i )));
2463       if ( sameNodes )
2464         return true;
2465     }
2466   }
2467   return false;
2468 }
2469
2470 SMDSAbs_ElementType CoincidentElements1D::GetType() const
2471 {
2472   return SMDSAbs_Edge;
2473 }
2474 SMDSAbs_ElementType CoincidentElements2D::GetType() const
2475 {
2476   return SMDSAbs_Face;
2477 }
2478 SMDSAbs_ElementType CoincidentElements3D::GetType() const
2479 {
2480   return SMDSAbs_Volume;
2481 }
2482
2483
2484 //================================================================================
2485 /*
2486   Class       : FreeBorders
2487   Description : Predicate for free borders
2488 */
2489 //================================================================================
2490
2491 FreeBorders::FreeBorders()
2492 {
2493   myMesh = 0;
2494 }
2495
2496 void FreeBorders::SetMesh( const SMDS_Mesh* theMesh )
2497 {
2498   myMesh = theMesh;
2499 }
2500
2501 bool FreeBorders::IsSatisfy( long theId )
2502 {
2503   return getNbMultiConnection( myMesh, theId ) == 1;
2504 }
2505
2506 SMDSAbs_ElementType FreeBorders::GetType() const
2507 {
2508   return SMDSAbs_Edge;
2509 }
2510
2511
2512 //================================================================================
2513 /*
2514   Class       : FreeEdges
2515   Description : Predicate for free Edges
2516 */
2517 //================================================================================
2518
2519 FreeEdges::FreeEdges()
2520 {
2521   myMesh = 0;
2522 }
2523
2524 void FreeEdges::SetMesh( const SMDS_Mesh* theMesh )
2525 {
2526   myMesh = theMesh;
2527 }
2528
2529 bool FreeEdges::IsFreeEdge( const SMDS_MeshNode** theNodes, const int theFaceId  )
2530 {
2531   TColStd_MapOfInteger aMap;
2532   for ( int i = 0; i < 2; i++ )
2533   {
2534     SMDS_ElemIteratorPtr anElemIter = theNodes[ i ]->GetInverseElementIterator(SMDSAbs_Face);
2535     while( anElemIter->more() )
2536     {
2537       if ( const SMDS_MeshElement* anElem = anElemIter->next())
2538       {
2539         const int anId = anElem->GetID();
2540         if ( anId != theFaceId && !aMap.Add( anId ))
2541           return false;
2542       }
2543     }
2544   }
2545   return true;
2546 }
2547
2548 bool FreeEdges::IsSatisfy( long theId )
2549 {
2550   if ( myMesh == 0 )
2551     return false;
2552
2553   const SMDS_MeshElement* aFace = myMesh->FindElement( theId );
2554   if ( aFace == 0 || aFace->GetType() != SMDSAbs_Face || aFace->NbNodes() < 3 )
2555     return false;
2556
2557   SMDS_NodeIteratorPtr anIter = aFace->interlacedNodesIterator();
2558   if ( !anIter )
2559     return false;
2560
2561   int i = 0, nbNodes = aFace->NbNodes();
2562   std::vector <const SMDS_MeshNode*> aNodes( nbNodes+1 );
2563   while( anIter->more() )
2564     if ( ! ( aNodes[ i++ ] = anIter->next() ))
2565       return false;
2566   aNodes[ nbNodes ] = aNodes[ 0 ];
2567
2568   for ( i = 0; i < nbNodes; i++ )
2569     if ( IsFreeEdge( &aNodes[ i ], theId ) )
2570       return true;
2571
2572   return false;
2573 }
2574
2575 SMDSAbs_ElementType FreeEdges::GetType() const
2576 {
2577   return SMDSAbs_Face;
2578 }
2579
2580 FreeEdges::Border::Border(long theElemId, long thePntId1, long thePntId2):
2581   myElemId(theElemId)
2582 {
2583   myPntId[0] = thePntId1;  myPntId[1] = thePntId2;
2584   if(thePntId1 > thePntId2){
2585     myPntId[1] = thePntId1;  myPntId[0] = thePntId2;
2586   }
2587 }
2588
2589 bool FreeEdges::Border::operator<(const FreeEdges::Border& x) const{
2590   if(myPntId[0] < x.myPntId[0]) return true;
2591   if(myPntId[0] == x.myPntId[0])
2592     if(myPntId[1] < x.myPntId[1]) return true;
2593   return false;
2594 }
2595
2596 inline void UpdateBorders(const FreeEdges::Border& theBorder,
2597                           FreeEdges::TBorders& theRegistry,
2598                           FreeEdges::TBorders& theContainer)
2599 {
2600   if(theRegistry.find(theBorder) == theRegistry.end()){
2601     theRegistry.insert(theBorder);
2602     theContainer.insert(theBorder);
2603   }else{
2604     theContainer.erase(theBorder);
2605   }
2606 }
2607
2608 void FreeEdges::GetBoreders(TBorders& theBorders)
2609 {
2610   TBorders aRegistry;
2611   SMDS_FaceIteratorPtr anIter = myMesh->facesIterator();
2612   for(; anIter->more(); ){
2613     const SMDS_MeshFace* anElem = anIter->next();
2614     long anElemId = anElem->GetID();
2615     SMDS_ElemIteratorPtr aNodesIter;
2616     if ( anElem->IsQuadratic() )
2617       aNodesIter = static_cast<const SMDS_VtkFace*>(anElem)->
2618         interlacedNodesElemIterator();
2619     else
2620       aNodesIter = anElem->nodesIterator();
2621     long aNodeId[2] = {0,0};
2622     const SMDS_MeshElement* aNode;
2623     if(aNodesIter->more()){
2624       aNode = aNodesIter->next();
2625       aNodeId[0] = aNodeId[1] = aNode->GetID();
2626     }
2627     for(; aNodesIter->more(); ){
2628       aNode = aNodesIter->next();
2629       long anId = aNode->GetID();
2630       Border aBorder(anElemId,aNodeId[1],anId);
2631       aNodeId[1] = anId;
2632       UpdateBorders(aBorder,aRegistry,theBorders);
2633     }
2634     Border aBorder(anElemId,aNodeId[0],aNodeId[1]);
2635     UpdateBorders(aBorder,aRegistry,theBorders);
2636   }
2637 }
2638
2639 //================================================================================
2640 /*
2641   Class       : FreeNodes
2642   Description : Predicate for free nodes
2643 */
2644 //================================================================================
2645
2646 FreeNodes::FreeNodes()
2647 {
2648   myMesh = 0;
2649 }
2650
2651 void FreeNodes::SetMesh( const SMDS_Mesh* theMesh )
2652 {
2653   myMesh = theMesh;
2654 }
2655
2656 bool FreeNodes::IsSatisfy( long theNodeId )
2657 {
2658   const SMDS_MeshNode* aNode = myMesh->FindNode( theNodeId );
2659   if (!aNode)
2660     return false;
2661
2662   return (aNode->NbInverseElements() < 1);
2663 }
2664
2665 SMDSAbs_ElementType FreeNodes::GetType() const
2666 {
2667   return SMDSAbs_Node;
2668 }
2669
2670
2671 //================================================================================
2672 /*
2673   Class       : FreeFaces
2674   Description : Predicate for free faces
2675 */
2676 //================================================================================
2677
2678 FreeFaces::FreeFaces()
2679 {
2680   myMesh = 0;
2681 }
2682
2683 void FreeFaces::SetMesh( const SMDS_Mesh* theMesh )
2684 {
2685   myMesh = theMesh;
2686 }
2687
2688 bool FreeFaces::IsSatisfy( long theId )
2689 {
2690   if (!myMesh) return false;
2691   // check that faces nodes refers to less than two common volumes
2692   const SMDS_MeshElement* aFace = myMesh->FindElement( theId );
2693   if ( !aFace || aFace->GetType() != SMDSAbs_Face )
2694     return false;
2695
2696   int nbNode = aFace->NbNodes();
2697
2698   // collect volumes to check that number of volumes with count equal nbNode not less than 2
2699   typedef std::map< SMDS_MeshElement*, int > TMapOfVolume; // map of volume counters
2700   typedef std::map< SMDS_MeshElement*, int >::iterator TItrMapOfVolume; // iterator
2701   TMapOfVolume mapOfVol;
2702
2703   SMDS_ElemIteratorPtr nodeItr = aFace->nodesIterator();
2704   while ( nodeItr->more() )
2705   {
2706     const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(nodeItr->next());
2707     if ( !aNode ) continue;
2708     SMDS_ElemIteratorPtr volItr = aNode->GetInverseElementIterator(SMDSAbs_Volume);
2709     while ( volItr->more() )
2710     {
2711       SMDS_MeshElement* aVol = (SMDS_MeshElement*)volItr->next();
2712       TItrMapOfVolume    itr = mapOfVol.insert( std::make_pair( aVol, 0 )).first;
2713       (*itr).second++;
2714     } 
2715   }
2716   int nbVol = 0;
2717   TItrMapOfVolume volItr = mapOfVol.begin();
2718   TItrMapOfVolume volEnd = mapOfVol.end();
2719   for ( ; volItr != volEnd; ++volItr )
2720     if ( (*volItr).second >= nbNode )
2721        nbVol++;
2722   // face is not free if number of volumes constructed on their nodes more than one
2723   return (nbVol < 2);
2724 }
2725
2726 SMDSAbs_ElementType FreeFaces::GetType() const
2727 {
2728   return SMDSAbs_Face;
2729 }
2730
2731 //================================================================================
2732 /*
2733   Class       : LinearOrQuadratic
2734   Description : Predicate to verify whether a mesh element is linear
2735 */
2736 //================================================================================
2737
2738 LinearOrQuadratic::LinearOrQuadratic()
2739 {
2740   myMesh = 0;
2741 }
2742
2743 void LinearOrQuadratic::SetMesh( const SMDS_Mesh* theMesh )
2744 {
2745   myMesh = theMesh;
2746 }
2747
2748 bool LinearOrQuadratic::IsSatisfy( long theId )
2749 {
2750   if (!myMesh) return false;
2751   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
2752   if ( !anElem || (myType != SMDSAbs_All && anElem->GetType() != myType) )
2753     return false;
2754   return (!anElem->IsQuadratic());
2755 }
2756
2757 void LinearOrQuadratic::SetType( SMDSAbs_ElementType theType )
2758 {
2759   myType = theType;
2760 }
2761
2762 SMDSAbs_ElementType LinearOrQuadratic::GetType() const
2763 {
2764   return myType;
2765 }
2766
2767 //================================================================================
2768 /*
2769   Class       : GroupColor
2770   Description : Functor for check color of group to which mesh element belongs to
2771 */
2772 //================================================================================
2773
2774 GroupColor::GroupColor()
2775 {
2776 }
2777
2778 bool GroupColor::IsSatisfy( long theId )
2779 {
2780   return myIDs.count( theId );
2781 }
2782
2783 void GroupColor::SetType( SMDSAbs_ElementType theType )
2784 {
2785   myType = theType;
2786 }
2787
2788 SMDSAbs_ElementType GroupColor::GetType() const
2789 {
2790   return myType;
2791 }
2792
2793 static bool isEqual( const Quantity_Color& theColor1,
2794                      const Quantity_Color& theColor2 )
2795 {
2796   // tolerance to compare colors
2797   const double tol = 5*1e-3;
2798   return ( fabs( theColor1.Red()   - theColor2.Red() )   < tol &&
2799            fabs( theColor1.Green() - theColor2.Green() ) < tol &&
2800            fabs( theColor1.Blue()  - theColor2.Blue() )  < tol );
2801 }
2802
2803 void GroupColor::SetMesh( const SMDS_Mesh* theMesh )
2804 {
2805   myIDs.clear();
2806
2807   const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh);
2808   if ( !aMesh )
2809     return;
2810
2811   int nbGrp = aMesh->GetNbGroups();
2812   if ( !nbGrp )
2813     return;
2814
2815   // iterates on groups and find necessary elements ids
2816   const std::set<SMESHDS_GroupBase*>&       aGroups = aMesh->GetGroups();
2817   std::set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin();
2818   for (; GrIt != aGroups.end(); GrIt++)
2819   {
2820     SMESHDS_GroupBase* aGrp = (*GrIt);
2821     if ( !aGrp )
2822       continue;
2823     // check type and color of group
2824     if ( !isEqual( myColor, aGrp->GetColor() ))
2825       continue;
2826
2827     // IPAL52867 (prevent infinite recursion via GroupOnFilter)
2828     if ( SMESHDS_GroupOnFilter * gof = dynamic_cast< SMESHDS_GroupOnFilter* >( aGrp ))
2829       if ( gof->GetPredicate().get() == this )
2830         continue;
2831
2832     SMDSAbs_ElementType aGrpElType = (SMDSAbs_ElementType)aGrp->GetType();
2833     if ( myType == aGrpElType || (myType == SMDSAbs_All && aGrpElType != SMDSAbs_Node) ) {
2834       // add elements IDS into control
2835       int aSize = aGrp->Extent();
2836       for (int i = 0; i < aSize; i++)
2837         myIDs.insert( aGrp->GetID(i+1) );
2838     }
2839   }
2840 }
2841
2842 void GroupColor::SetColorStr( const TCollection_AsciiString& theStr )
2843 {
2844   Kernel_Utils::Localizer loc;
2845   TCollection_AsciiString aStr = theStr;
2846   aStr.RemoveAll( ' ' );
2847   aStr.RemoveAll( '\t' );
2848   for ( int aPos = aStr.Search( ";;" ); aPos != -1; aPos = aStr.Search( ";;" ) )
2849     aStr.Remove( aPos, 2 );
2850   Standard_Real clr[3];
2851   clr[0] = clr[1] = clr[2] = 0.;
2852   for ( int i = 0; i < 3; i++ ) {
2853     TCollection_AsciiString tmpStr = aStr.Token( ";", i+1 );
2854     if ( !tmpStr.IsEmpty() && tmpStr.IsRealValue() )
2855       clr[i] = tmpStr.RealValue();
2856   }
2857   myColor = Quantity_Color( clr[0], clr[1], clr[2], Quantity_TOC_RGB );
2858 }
2859
2860 //=======================================================================
2861 // name    : GetRangeStr
2862 // Purpose : Get range as a string.
2863 //           Example: "1,2,3,50-60,63,67,70-"
2864 //=======================================================================
2865
2866 void GroupColor::GetColorStr( TCollection_AsciiString& theResStr ) const
2867 {
2868   theResStr.Clear();
2869   theResStr += TCollection_AsciiString( myColor.Red() );
2870   theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Green() );
2871   theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Blue() );
2872 }
2873
2874 //================================================================================
2875 /*
2876   Class       : ElemGeomType
2877   Description : Predicate to check element geometry type
2878 */
2879 //================================================================================
2880
2881 ElemGeomType::ElemGeomType()
2882 {
2883   myMesh = 0;
2884   myType = SMDSAbs_All;
2885   myGeomType = SMDSGeom_TRIANGLE;
2886 }
2887
2888 void ElemGeomType::SetMesh( const SMDS_Mesh* theMesh )
2889 {
2890   myMesh = theMesh;
2891 }
2892
2893 bool ElemGeomType::IsSatisfy( long theId )
2894 {
2895   if (!myMesh) return false;
2896   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
2897   if ( !anElem )
2898     return false;
2899   const SMDSAbs_ElementType anElemType = anElem->GetType();
2900   if ( myType != SMDSAbs_All && anElemType != myType )
2901     return false;
2902   bool isOk = ( anElem->GetGeomType() == myGeomType );
2903   return isOk;
2904 }
2905
2906 void ElemGeomType::SetType( SMDSAbs_ElementType theType )
2907 {
2908   myType = theType;
2909 }
2910
2911 SMDSAbs_ElementType ElemGeomType::GetType() const
2912 {
2913   return myType;
2914 }
2915
2916 void ElemGeomType::SetGeomType( SMDSAbs_GeometryType theType )
2917 {
2918   myGeomType = theType;
2919 }
2920
2921 SMDSAbs_GeometryType ElemGeomType::GetGeomType() const
2922 {
2923   return myGeomType;
2924 }
2925
2926 //================================================================================
2927 /*
2928   Class       : ElemEntityType
2929   Description : Predicate to check element entity type
2930 */
2931 //================================================================================
2932
2933 ElemEntityType::ElemEntityType():
2934   myMesh( 0 ),
2935   myType( SMDSAbs_All ),
2936   myEntityType( SMDSEntity_0D )
2937 {
2938 }
2939
2940 void ElemEntityType::SetMesh( const SMDS_Mesh* theMesh )
2941 {
2942   myMesh = theMesh;
2943 }
2944
2945 bool ElemEntityType::IsSatisfy( long theId )
2946 {
2947   if ( !myMesh ) return false;
2948   if ( myType == SMDSAbs_Node )
2949     return myMesh->FindNode( theId );
2950   const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
2951   return ( anElem &&
2952            myEntityType == anElem->GetEntityType() );
2953 }
2954
2955 void ElemEntityType::SetType( SMDSAbs_ElementType theType )
2956 {
2957   myType = theType;
2958 }
2959
2960 SMDSAbs_ElementType ElemEntityType::GetType() const
2961 {
2962   return myType;
2963 }
2964
2965 void ElemEntityType::SetElemEntityType( SMDSAbs_EntityType theEntityType )
2966 {
2967   myEntityType = theEntityType;
2968 }
2969
2970 SMDSAbs_EntityType ElemEntityType::GetElemEntityType() const
2971 {
2972   return myEntityType;
2973 }
2974
2975 //================================================================================
2976 /*!
2977  * \brief Class ConnectedElements
2978  */
2979 //================================================================================
2980
2981 ConnectedElements::ConnectedElements():
2982   myNodeID(0), myType( SMDSAbs_All ), myOkIDsReady( false ) {}
2983
2984 SMDSAbs_ElementType ConnectedElements::GetType() const
2985 { return myType; }
2986
2987 int ConnectedElements::GetNode() const
2988 { return myXYZ.empty() ? myNodeID : 0; } // myNodeID can be found by myXYZ
2989
2990 std::vector<double> ConnectedElements::GetPoint() const
2991 { return myXYZ; }
2992
2993 void ConnectedElements::clearOkIDs()
2994 { myOkIDsReady = false; myOkIDs.clear(); }
2995
2996 void ConnectedElements::SetType( SMDSAbs_ElementType theType )
2997 {
2998   if ( myType != theType || myMeshModifTracer.IsMeshModified() )
2999     clearOkIDs();
3000   myType = theType;
3001 }
3002
3003 void ConnectedElements::SetMesh( const SMDS_Mesh* theMesh )
3004 {
3005   myMeshModifTracer.SetMesh( theMesh );
3006   if ( myMeshModifTracer.IsMeshModified() )
3007   {
3008     clearOkIDs();
3009     if ( !myXYZ.empty() )
3010       SetPoint( myXYZ[0], myXYZ[1], myXYZ[2] ); // find a node near myXYZ it in a new mesh
3011   }
3012 }
3013
3014 void ConnectedElements::SetNode( int nodeID )
3015 {
3016   myNodeID = nodeID;
3017   myXYZ.clear();
3018
3019   bool isSameDomain = false;
3020   if ( myOkIDsReady && myMeshModifTracer.GetMesh() && !myMeshModifTracer.IsMeshModified() )
3021     if ( const SMDS_MeshNode* n = myMeshModifTracer.GetMesh()->FindNode( myNodeID ))
3022     {
3023       SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator( myType );
3024       while ( !isSameDomain && eIt->more() )
3025         isSameDomain = IsSatisfy( eIt->next()->GetID() );
3026     }
3027   if ( !isSameDomain )
3028     clearOkIDs();
3029 }
3030
3031 void ConnectedElements::SetPoint( double x, double y, double z )
3032 {
3033   myXYZ.resize(3);
3034   myXYZ[0] = x;
3035   myXYZ[1] = y;
3036   myXYZ[2] = z;
3037   myNodeID = 0;
3038
3039   bool isSameDomain = false;
3040
3041   // find myNodeID by myXYZ if possible
3042   if ( myMeshModifTracer.GetMesh() )
3043   {
3044     SMESHUtils::Deleter<SMESH_ElementSearcher> searcher
3045       ( SMESH_MeshAlgos::GetElementSearcher( (SMDS_Mesh&) *myMeshModifTracer.GetMesh() ));
3046
3047     std::vector< const SMDS_MeshElement* > foundElems;
3048     searcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_All, foundElems );
3049
3050     if ( !foundElems.empty() )
3051     {
3052       myNodeID = foundElems[0]->GetNode(0)->GetID();
3053       if ( myOkIDsReady && !myMeshModifTracer.IsMeshModified() )
3054         isSameDomain = IsSatisfy( foundElems[0]->GetID() );
3055     }
3056   }
3057   if ( !isSameDomain )
3058     clearOkIDs();
3059 }
3060
3061 bool ConnectedElements::IsSatisfy( long theElementId )
3062 {
3063   // Here we do NOT check if the mesh has changed, we do it in Set...() only!!!
3064
3065   if ( !myOkIDsReady )
3066   {
3067     if ( !myMeshModifTracer.GetMesh() )
3068       return false;
3069     const SMDS_MeshNode* node0 = myMeshModifTracer.GetMesh()->FindNode( myNodeID );
3070     if ( !node0 )
3071       return false;
3072
3073     std::list< const SMDS_MeshNode* > nodeQueue( 1, node0 );
3074     std::set< int > checkedNodeIDs;
3075     // algo:
3076     // foreach node in nodeQueue:
3077     //   foreach element sharing a node:
3078     //     add ID of an element of myType to myOkIDs;
3079     //     push all element nodes absent from checkedNodeIDs to nodeQueue;
3080     while ( !nodeQueue.empty() )
3081     {
3082       const SMDS_MeshNode* node = nodeQueue.front();
3083       nodeQueue.pop_front();
3084
3085       // loop on elements sharing the node
3086       SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3087       while ( eIt->more() )
3088       {
3089         // keep elements of myType
3090         const SMDS_MeshElement* element = eIt->next();
3091         if ( element->GetType() == myType )
3092           myOkIDs.insert( myOkIDs.end(), element->GetID() );
3093
3094         // enqueue nodes of the element
3095         SMDS_ElemIteratorPtr nIt = element->nodesIterator();
3096         while ( nIt->more() )
3097         {
3098           const SMDS_MeshNode* n = static_cast< const SMDS_MeshNode* >( nIt->next() );
3099           if ( checkedNodeIDs.insert( n->GetID() ).second )
3100             nodeQueue.push_back( n );
3101         }
3102       }
3103     }
3104     if ( myType == SMDSAbs_Node )
3105       std::swap( myOkIDs, checkedNodeIDs );
3106
3107     size_t totalNbElems = myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType );
3108     if ( myOkIDs.size() == totalNbElems )
3109       myOkIDs.clear();
3110
3111     myOkIDsReady = true;
3112   }
3113
3114   return myOkIDs.empty() ? true : myOkIDs.count( theElementId );
3115 }
3116
3117 //================================================================================
3118 /*!
3119  * \brief Class CoplanarFaces
3120  */
3121 //================================================================================
3122
3123 namespace
3124 {
3125   inline bool isLessAngle( const gp_Vec& v1, const gp_Vec& v2, const double cos )
3126   {
3127     double dot = v1 * v2; // cos * |v1| * |v2|
3128     double l1  = v1.SquareMagnitude();
3129     double l2  = v2.SquareMagnitude();
3130     return (( dot * cos >= 0 ) && 
3131             ( dot * dot ) / l1 / l2 >= ( cos * cos ));
3132   }
3133 }
3134 CoplanarFaces::CoplanarFaces()
3135   : myFaceID(0), myToler(0)
3136 {
3137 }
3138 void CoplanarFaces::SetMesh( const SMDS_Mesh* theMesh )
3139 {
3140   myMeshModifTracer.SetMesh( theMesh );
3141   if ( myMeshModifTracer.IsMeshModified() )
3142   {
3143     // Build a set of coplanar face ids
3144
3145     myCoplanarIDs.Clear();
3146
3147     if ( !myMeshModifTracer.GetMesh() || !myFaceID || !myToler )
3148       return;
3149
3150     const SMDS_MeshElement* face = myMeshModifTracer.GetMesh()->FindElement( myFaceID );
3151     if ( !face || face->GetType() != SMDSAbs_Face )
3152       return;
3153
3154     bool normOK;
3155     gp_Vec myNorm = getNormale( static_cast<const SMDS_MeshFace*>(face), &normOK );
3156     if (!normOK)
3157       return;
3158
3159     const double cosTol = Cos( myToler * M_PI / 180. );
3160     NCollection_Map< SMESH_TLink, SMESH_TLink > checkedLinks;
3161
3162     std::list< std::pair< const SMDS_MeshElement*, gp_Vec > > faceQueue;
3163     faceQueue.push_back( std::make_pair( face, myNorm ));
3164     while ( !faceQueue.empty() )
3165     {
3166       face   = faceQueue.front().first;
3167       myNorm = faceQueue.front().second;
3168       faceQueue.pop_front();
3169
3170       for ( int i = 0, nbN = face->NbCornerNodes(); i < nbN; ++i )
3171       {
3172         const SMDS_MeshNode*  n1 = face->GetNode( i );
3173         const SMDS_MeshNode*  n2 = face->GetNode(( i+1 )%nbN);
3174         if ( !checkedLinks.Add( SMESH_TLink( n1, n2 )))
3175           continue;
3176         SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator(SMDSAbs_Face);
3177         while ( fIt->more() )
3178         {
3179           const SMDS_MeshElement* f = fIt->next();
3180           if ( f->GetNodeIndex( n2 ) > -1 )
3181           {
3182             gp_Vec norm = getNormale( static_cast<const SMDS_MeshFace*>(f), &normOK );
3183             if (!normOK || isLessAngle( myNorm, norm, cosTol))
3184             {
3185               myCoplanarIDs.Add( f->GetID() );
3186               faceQueue.push_back( std::make_pair( f, norm ));
3187             }
3188           }
3189         }
3190       }
3191     }
3192   }
3193 }
3194 bool CoplanarFaces::IsSatisfy( long theElementId )
3195 {
3196   return myCoplanarIDs.Contains( theElementId );
3197 }
3198
3199 /*
3200  *Class       : RangeOfIds
3201   *Description : Predicate for Range of Ids.
3202   *              Range may be specified with two ways.
3203   *              1. Using AddToRange method
3204   *              2. With SetRangeStr method. Parameter of this method is a string
3205   *                 like as "1,2,3,50-60,63,67,70-"
3206 */
3207
3208 //=======================================================================
3209 // name    : RangeOfIds
3210 // Purpose : Constructor
3211 //=======================================================================
3212 RangeOfIds::RangeOfIds()
3213 {
3214   myMesh = 0;
3215   myType = SMDSAbs_All;
3216 }
3217
3218 //=======================================================================
3219 // name    : SetMesh
3220 // Purpose : Set mesh
3221 //=======================================================================
3222 void RangeOfIds::SetMesh( const SMDS_Mesh* theMesh )
3223 {
3224   myMesh = theMesh;
3225 }
3226
3227 //=======================================================================
3228 // name    : AddToRange
3229 // Purpose : Add ID to the range
3230 //=======================================================================
3231 bool RangeOfIds::AddToRange( long theEntityId )
3232 {
3233   myIds.Add( theEntityId );
3234   return true;
3235 }
3236
3237 //=======================================================================
3238 // name    : GetRangeStr
3239 // Purpose : Get range as a string.
3240 //           Example: "1,2,3,50-60,63,67,70-"
3241 //=======================================================================
3242 void RangeOfIds::GetRangeStr( TCollection_AsciiString& theResStr )
3243 {
3244   theResStr.Clear();
3245
3246   TColStd_SequenceOfInteger     anIntSeq;
3247   TColStd_SequenceOfAsciiString aStrSeq;
3248
3249   TColStd_MapIteratorOfMapOfInteger anIter( myIds );
3250   for ( ; anIter.More(); anIter.Next() )
3251   {
3252     int anId = anIter.Key();
3253     TCollection_AsciiString aStr( anId );
3254     anIntSeq.Append( anId );
3255     aStrSeq.Append( aStr );
3256   }
3257
3258   for ( int i = 1, n = myMin.Length(); i <= n; i++ )
3259   {
3260     int aMinId = myMin( i );
3261     int aMaxId = myMax( i );
3262
3263     TCollection_AsciiString aStr;
3264     if ( aMinId != IntegerFirst() )
3265       aStr += aMinId;
3266
3267     aStr += "-";
3268
3269     if ( aMaxId != IntegerLast() )
3270       aStr += aMaxId;
3271
3272     // find position of the string in result sequence and insert string in it
3273     if ( anIntSeq.Length() == 0 )
3274     {
3275       anIntSeq.Append( aMinId );
3276       aStrSeq.Append( aStr );
3277     }
3278     else
3279     {
3280       if ( aMinId < anIntSeq.First() )
3281       {
3282         anIntSeq.Prepend( aMinId );
3283         aStrSeq.Prepend( aStr );
3284       }
3285       else if ( aMinId > anIntSeq.Last() )
3286       {
3287         anIntSeq.Append( aMinId );
3288         aStrSeq.Append( aStr );
3289       }
3290       else
3291         for ( int j = 1, k = anIntSeq.Length(); j <= k; j++ )
3292           if ( aMinId < anIntSeq( j ) )
3293           {
3294             anIntSeq.InsertBefore( j, aMinId );
3295             aStrSeq.InsertBefore( j, aStr );
3296             break;
3297           }
3298     }
3299   }
3300
3301   if ( aStrSeq.Length() == 0 )
3302     return;
3303
3304   theResStr = aStrSeq( 1 );
3305   for ( int j = 2, k = aStrSeq.Length(); j <= k; j++  )
3306   {
3307     theResStr += ",";
3308     theResStr += aStrSeq( j );
3309   }
3310 }
3311
3312 //=======================================================================
3313 // name    : SetRangeStr
3314 // Purpose : Define range with string
3315 //           Example of entry string: "1,2,3,50-60,63,67,70-"
3316 //=======================================================================
3317 bool RangeOfIds::SetRangeStr( const TCollection_AsciiString& theStr )
3318 {
3319   myMin.Clear();
3320   myMax.Clear();
3321   myIds.Clear();
3322
3323   TCollection_AsciiString aStr = theStr;
3324   for ( int i = 1; i <= aStr.Length(); ++i )
3325   {
3326     char c = aStr.Value( i );
3327     if ( !isdigit( c ) && c != ',' && c != '-' )
3328       aStr.SetValue( i, ',');
3329   }
3330   aStr.RemoveAll( ' ' );
3331
3332   TCollection_AsciiString tmpStr = aStr.Token( ",", 1 );
3333   int i = 1;
3334   while ( tmpStr != "" )
3335   {
3336     tmpStr = aStr.Token( ",", i++ );
3337     int aPos = tmpStr.Search( '-' );
3338
3339     if ( aPos == -1 )
3340     {
3341       if ( tmpStr.IsIntegerValue() )
3342         myIds.Add( tmpStr.IntegerValue() );
3343       else
3344         return false;
3345     }
3346     else
3347     {
3348       TCollection_AsciiString aMaxStr = tmpStr.Split( aPos );
3349       TCollection_AsciiString aMinStr = tmpStr;
3350
3351       while ( aMinStr.Search( "-" ) != -1 ) aMinStr.RemoveAll( '-' );
3352       while ( aMaxStr.Search( "-" ) != -1 ) aMaxStr.RemoveAll( '-' );
3353
3354       if ( (!aMinStr.IsEmpty() && !aMinStr.IsIntegerValue()) ||
3355            (!aMaxStr.IsEmpty() && !aMaxStr.IsIntegerValue()) )
3356         return false;
3357
3358       myMin.Append( aMinStr.IsEmpty() ? IntegerFirst() : aMinStr.IntegerValue() );
3359       myMax.Append( aMaxStr.IsEmpty() ? IntegerLast()  : aMaxStr.IntegerValue() );
3360     }
3361   }
3362
3363   return true;
3364 }
3365
3366 //=======================================================================
3367 // name    : GetType
3368 // Purpose : Get type of supported entities
3369 //=======================================================================
3370 SMDSAbs_ElementType RangeOfIds::GetType() const
3371 {
3372   return myType;
3373 }
3374
3375 //=======================================================================
3376 // name    : SetType
3377 // Purpose : Set type of supported entities
3378 //=======================================================================
3379 void RangeOfIds::SetType( SMDSAbs_ElementType theType )
3380 {
3381   myType = theType;
3382 }
3383
3384 //=======================================================================
3385 // name    : IsSatisfy
3386 // Purpose : Verify whether entity satisfies to this rpedicate
3387 //=======================================================================
3388 bool RangeOfIds::IsSatisfy( long theId )
3389 {
3390   if ( !myMesh )
3391     return false;
3392
3393   if ( myType == SMDSAbs_Node )
3394   {
3395     if ( myMesh->FindNode( theId ) == 0 )
3396       return false;
3397   }
3398   else
3399   {
3400     const SMDS_MeshElement* anElem = myMesh->FindElement( theId );
3401     if ( anElem == 0 || (myType != anElem->GetType() && myType != SMDSAbs_All ))
3402       return false;
3403   }
3404
3405   if ( myIds.Contains( theId ) )
3406     return true;
3407
3408   for ( int i = 1, n = myMin.Length(); i <= n; i++ )
3409     if ( theId >= myMin( i ) && theId <= myMax( i ) )
3410       return true;
3411
3412   return false;
3413 }
3414
3415 /*
3416   Class       : Comparator
3417   Description : Base class for comparators
3418 */
3419 Comparator::Comparator():
3420   myMargin(0)
3421 {}
3422
3423 Comparator::~Comparator()
3424 {}
3425
3426 void Comparator::SetMesh( const SMDS_Mesh* theMesh )
3427 {
3428   if ( myFunctor )
3429     myFunctor->SetMesh( theMesh );
3430 }
3431
3432 void Comparator::SetMargin( double theValue )
3433 {
3434   myMargin = theValue;
3435 }
3436
3437 void Comparator::SetNumFunctor( NumericalFunctorPtr theFunct )
3438 {
3439   myFunctor = theFunct;
3440 }
3441
3442 SMDSAbs_ElementType Comparator::GetType() const
3443 {
3444   return myFunctor ? myFunctor->GetType() : SMDSAbs_All;
3445 }
3446
3447 double Comparator::GetMargin()
3448 {
3449   return myMargin;
3450 }
3451
3452
3453 /*
3454   Class       : LessThan
3455   Description : Comparator "<"
3456 */
3457 bool LessThan::IsSatisfy( long theId )
3458 {
3459   return myFunctor && myFunctor->GetValue( theId ) < myMargin;
3460 }
3461
3462
3463 /*
3464   Class       : MoreThan
3465   Description : Comparator ">"
3466 */
3467 bool MoreThan::IsSatisfy( long theId )
3468 {
3469   return myFunctor && myFunctor->GetValue( theId ) > myMargin;
3470 }
3471
3472
3473 /*
3474   Class       : EqualTo
3475   Description : Comparator "="
3476 */
3477 EqualTo::EqualTo():
3478   myToler(Precision::Confusion())
3479 {}
3480
3481 bool EqualTo::IsSatisfy( long theId )
3482 {
3483   return myFunctor && fabs( myFunctor->GetValue( theId ) - myMargin ) < myToler;
3484 }
3485
3486 void EqualTo::SetTolerance( double theToler )
3487 {
3488   myToler = theToler;
3489 }
3490
3491 double EqualTo::GetTolerance()
3492 {
3493   return myToler;
3494 }
3495
3496 /*
3497   Class       : LogicalNOT
3498   Description : Logical NOT predicate
3499 */
3500 LogicalNOT::LogicalNOT()
3501 {}
3502
3503 LogicalNOT::~LogicalNOT()
3504 {}
3505
3506 bool LogicalNOT::IsSatisfy( long theId )
3507 {
3508   return myPredicate && !myPredicate->IsSatisfy( theId );
3509 }
3510
3511 void LogicalNOT::SetMesh( const SMDS_Mesh* theMesh )
3512 {
3513   if ( myPredicate )
3514     myPredicate->SetMesh( theMesh );
3515 }
3516
3517 void LogicalNOT::SetPredicate( PredicatePtr thePred )
3518 {
3519   myPredicate = thePred;
3520 }
3521
3522 SMDSAbs_ElementType LogicalNOT::GetType() const
3523 {
3524   return myPredicate ? myPredicate->GetType() : SMDSAbs_All;
3525 }
3526
3527
3528 /*
3529   Class       : LogicalBinary
3530   Description : Base class for binary logical predicate
3531 */
3532 LogicalBinary::LogicalBinary()
3533 {}
3534
3535 LogicalBinary::~LogicalBinary()
3536 {}
3537
3538 void LogicalBinary::SetMesh( const SMDS_Mesh* theMesh )
3539 {
3540   if ( myPredicate1 )
3541     myPredicate1->SetMesh( theMesh );
3542
3543   if ( myPredicate2 )
3544     myPredicate2->SetMesh( theMesh );
3545 }
3546
3547 void LogicalBinary::SetPredicate1( PredicatePtr thePredicate )
3548 {
3549   myPredicate1 = thePredicate;
3550 }
3551
3552 void LogicalBinary::SetPredicate2( PredicatePtr thePredicate )
3553 {
3554   myPredicate2 = thePredicate;
3555 }
3556
3557 SMDSAbs_ElementType LogicalBinary::GetType() const
3558 {
3559   if ( !myPredicate1 || !myPredicate2 )
3560     return SMDSAbs_All;
3561
3562   SMDSAbs_ElementType aType1 = myPredicate1->GetType();
3563   SMDSAbs_ElementType aType2 = myPredicate2->GetType();
3564
3565   return aType1 == aType2 ? aType1 : SMDSAbs_All;
3566 }
3567
3568
3569 /*
3570   Class       : LogicalAND
3571   Description : Logical AND
3572 */
3573 bool LogicalAND::IsSatisfy( long theId )
3574 {
3575   return
3576     myPredicate1 &&
3577     myPredicate2 &&
3578     myPredicate1->IsSatisfy( theId ) &&
3579     myPredicate2->IsSatisfy( theId );
3580 }
3581
3582
3583 /*
3584   Class       : LogicalOR
3585   Description : Logical OR
3586 */
3587 bool LogicalOR::IsSatisfy( long theId )
3588 {
3589   return
3590     myPredicate1 &&
3591     myPredicate2 &&
3592     (myPredicate1->IsSatisfy( theId ) ||
3593     myPredicate2->IsSatisfy( theId ));
3594 }
3595
3596
3597 /*
3598                               FILTER
3599 */
3600
3601 // #ifdef WITH_TBB
3602 // #include <tbb/parallel_for.h>
3603 // #include <tbb/enumerable_thread_specific.h>
3604
3605 // namespace Parallel
3606 // {
3607 //   typedef tbb::enumerable_thread_specific< TIdSequence > TIdSeq;
3608
3609 //   struct Predicate
3610 //   {
3611 //     const SMDS_Mesh* myMesh;
3612 //     PredicatePtr     myPredicate;
3613 //     TIdSeq &         myOKIds;
3614 //     Predicate( const SMDS_Mesh* m, PredicatePtr p, TIdSeq & ids ):
3615 //       myMesh(m), myPredicate(p->Duplicate()), myOKIds(ids) {}
3616 //     void operator() ( const tbb::blocked_range<size_t>& r ) const
3617 //     {
3618 //       for ( size_t i = r.begin(); i != r.end(); ++i )
3619 //         if ( myPredicate->IsSatisfy( i ))
3620 //           myOKIds.local().push_back();
3621 //     }
3622 //   }
3623 // }
3624 // #endif
3625
3626 Filter::Filter()
3627 {}
3628
3629 Filter::~Filter()
3630 {}
3631
3632 void Filter::SetPredicate( PredicatePtr thePredicate )
3633 {
3634   myPredicate = thePredicate;
3635 }
3636
3637 void Filter::GetElementsId( const SMDS_Mesh* theMesh,
3638                             PredicatePtr     thePredicate,
3639                             TIdSequence&     theSequence )
3640 {
3641   theSequence.clear();
3642
3643   if ( !theMesh || !thePredicate )
3644     return;
3645
3646   thePredicate->SetMesh( theMesh );
3647
3648   SMDS_ElemIteratorPtr elemIt = theMesh->elementsIterator( thePredicate->GetType() );
3649   if ( elemIt ) {
3650     while ( elemIt->more() ) {
3651       const SMDS_MeshElement* anElem = elemIt->next();
3652       long anId = anElem->GetID();
3653       if ( thePredicate->IsSatisfy( anId ) )
3654         theSequence.push_back( anId );
3655     }
3656   }
3657 }
3658
3659 void Filter::GetElementsId( const SMDS_Mesh*     theMesh,
3660                             Filter::TIdSequence& theSequence )
3661 {
3662   GetElementsId(theMesh,myPredicate,theSequence);
3663 }
3664
3665 /*
3666                               ManifoldPart
3667 */
3668
3669 typedef std::set<SMDS_MeshFace*>                    TMapOfFacePtr;
3670
3671 /*
3672    Internal class Link
3673 */
3674
3675 ManifoldPart::Link::Link( SMDS_MeshNode* theNode1,
3676                           SMDS_MeshNode* theNode2 )
3677 {
3678   myNode1 = theNode1;
3679   myNode2 = theNode2;
3680 }
3681
3682 ManifoldPart::Link::~Link()
3683 {
3684   myNode1 = 0;
3685   myNode2 = 0;
3686 }
3687
3688 bool ManifoldPart::Link::IsEqual( const ManifoldPart::Link& theLink ) const
3689 {
3690   if ( myNode1 == theLink.myNode1 &&
3691        myNode2 == theLink.myNode2 )
3692     return true;
3693   else if ( myNode1 == theLink.myNode2 &&
3694             myNode2 == theLink.myNode1 )
3695     return true;
3696   else
3697     return false;
3698 }
3699
3700 bool ManifoldPart::Link::operator<( const ManifoldPart::Link& x ) const
3701 {
3702   if(myNode1 < x.myNode1) return true;
3703   if(myNode1 == x.myNode1)
3704     if(myNode2 < x.myNode2) return true;
3705   return false;
3706 }
3707
3708 bool ManifoldPart::IsEqual( const ManifoldPart::Link& theLink1,
3709                             const ManifoldPart::Link& theLink2 )
3710 {
3711   return theLink1.IsEqual( theLink2 );
3712 }
3713
3714 ManifoldPart::ManifoldPart()
3715 {
3716   myMesh = 0;
3717   myAngToler = Precision::Angular();
3718   myIsOnlyManifold = true;
3719 }
3720
3721 ManifoldPart::~ManifoldPart()
3722 {
3723   myMesh = 0;
3724 }
3725
3726 void ManifoldPart::SetMesh( const SMDS_Mesh* theMesh )
3727 {
3728   myMesh = theMesh;
3729   process();
3730 }
3731
3732 SMDSAbs_ElementType ManifoldPart::GetType() const
3733 { return SMDSAbs_Face; }
3734
3735 bool ManifoldPart::IsSatisfy( long theElementId )
3736 {
3737   return myMapIds.Contains( theElementId );
3738 }
3739
3740 void ManifoldPart::SetAngleTolerance( const double theAngToler )
3741 { myAngToler = theAngToler; }
3742
3743 double ManifoldPart::GetAngleTolerance() const
3744 { return myAngToler; }
3745
3746 void ManifoldPart::SetIsOnlyManifold( const bool theIsOnly )
3747 { myIsOnlyManifold = theIsOnly; }
3748
3749 void ManifoldPart::SetStartElem( const long  theStartId )
3750 { myStartElemId = theStartId; }
3751
3752 bool ManifoldPart::process()
3753 {
3754   myMapIds.Clear();
3755   myMapBadGeomIds.Clear();
3756
3757   myAllFacePtr.clear();
3758   myAllFacePtrIntDMap.clear();
3759   if ( !myMesh )
3760     return false;
3761
3762   // collect all faces into own map
3763   SMDS_FaceIteratorPtr anFaceItr = myMesh->facesIterator();
3764   for (; anFaceItr->more(); )
3765   {
3766     SMDS_MeshFace* aFacePtr = (SMDS_MeshFace*)anFaceItr->next();
3767     myAllFacePtr.push_back( aFacePtr );
3768     myAllFacePtrIntDMap[aFacePtr] = myAllFacePtr.size()-1;
3769   }
3770
3771   SMDS_MeshFace* aStartFace = (SMDS_MeshFace*)myMesh->FindElement( myStartElemId );
3772   if ( !aStartFace )
3773     return false;
3774
3775   // the map of non manifold links and bad geometry
3776   TMapOfLink aMapOfNonManifold;
3777   TColStd_MapOfInteger aMapOfTreated;
3778
3779   // begin cycle on faces from start index and run on vector till the end
3780   //  and from begin to start index to cover whole vector
3781   const int aStartIndx = myAllFacePtrIntDMap[aStartFace];
3782   bool isStartTreat = false;
3783   for ( int fi = aStartIndx; !isStartTreat || fi != aStartIndx ; fi++ )
3784   {
3785     if ( fi == aStartIndx )
3786       isStartTreat = true;
3787     // as result next time when fi will be equal to aStartIndx
3788
3789     SMDS_MeshFace* aFacePtr = myAllFacePtr[ fi ];
3790     if ( aMapOfTreated.Contains( aFacePtr->GetID() ) )
3791       continue;
3792
3793     aMapOfTreated.Add( aFacePtr->GetID() );
3794     TColStd_MapOfInteger aResFaces;
3795     if ( !findConnected( myAllFacePtrIntDMap, aFacePtr,
3796                          aMapOfNonManifold, aResFaces ) )
3797       continue;
3798     TColStd_MapIteratorOfMapOfInteger anItr( aResFaces );
3799     for ( ; anItr.More(); anItr.Next() )
3800     {
3801       int aFaceId = anItr.Key();
3802       aMapOfTreated.Add( aFaceId );
3803       myMapIds.Add( aFaceId );
3804     }
3805
3806     if ( fi == int( myAllFacePtr.size() - 1 ))
3807       fi = 0;
3808   } // end run on vector of faces
3809   return !myMapIds.IsEmpty();
3810 }
3811
3812 static void getLinks( const SMDS_MeshFace* theFace,
3813                       ManifoldPart::TVectorOfLink& theLinks )
3814 {
3815   int aNbNode = theFace->NbNodes();
3816   SMDS_ElemIteratorPtr aNodeItr = theFace->nodesIterator();
3817   int i = 1;
3818   SMDS_MeshNode* aNode = 0;
3819   for ( ; aNodeItr->more() && i <= aNbNode; )
3820   {
3821
3822     SMDS_MeshNode* aN1 = (SMDS_MeshNode*)aNodeItr->next();
3823     if ( i == 1 )
3824       aNode = aN1;
3825     i++;
3826     SMDS_MeshNode* aN2 = ( i >= aNbNode ) ? aNode : (SMDS_MeshNode*)aNodeItr->next();
3827     i++;
3828     ManifoldPart::Link aLink( aN1, aN2 );
3829     theLinks.push_back( aLink );
3830   }
3831 }
3832
3833 bool ManifoldPart::findConnected
3834                  ( const ManifoldPart::TDataMapFacePtrInt& theAllFacePtrInt,
3835                   SMDS_MeshFace*                           theStartFace,
3836                   ManifoldPart::TMapOfLink&                theNonManifold,
3837                   TColStd_MapOfInteger&                    theResFaces )
3838 {
3839   theResFaces.Clear();
3840   if ( !theAllFacePtrInt.size() )
3841     return false;
3842
3843   if ( getNormale( theStartFace ).SquareModulus() <= gp::Resolution() )
3844   {
3845     myMapBadGeomIds.Add( theStartFace->GetID() );
3846     return false;
3847   }
3848
3849   ManifoldPart::TMapOfLink aMapOfBoundary, aMapToSkip;
3850   ManifoldPart::TVectorOfLink aSeqOfBoundary;
3851   theResFaces.Add( theStartFace->GetID() );
3852   ManifoldPart::TDataMapOfLinkFacePtr aDMapLinkFace;
3853
3854   expandBoundary( aMapOfBoundary, aSeqOfBoundary,
3855                  aDMapLinkFace, theNonManifold, theStartFace );
3856
3857   bool isDone = false;
3858   while ( !isDone && aMapOfBoundary.size() != 0 )
3859   {
3860     bool isToReset = false;
3861     ManifoldPart::TVectorOfLink::iterator pLink = aSeqOfBoundary.begin();
3862     for ( ; !isToReset && pLink != aSeqOfBoundary.end(); ++pLink )
3863     {
3864       ManifoldPart::Link aLink = *pLink;
3865       if ( aMapToSkip.find( aLink ) != aMapToSkip.end() )
3866         continue;
3867       // each link could be treated only once
3868       aMapToSkip.insert( aLink );
3869
3870       ManifoldPart::TVectorOfFacePtr aFaces;
3871       // find next
3872       if ( myIsOnlyManifold &&
3873            (theNonManifold.find( aLink ) != theNonManifold.end()) )
3874         continue;
3875       else
3876       {
3877         getFacesByLink( aLink, aFaces );
3878         // filter the element to keep only indicated elements
3879         ManifoldPart::TVectorOfFacePtr aFiltered;
3880         ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin();
3881         for ( ; pFace != aFaces.end(); ++pFace )
3882         {
3883           SMDS_MeshFace* aFace = *pFace;
3884           if ( myAllFacePtrIntDMap.find( aFace ) != myAllFacePtrIntDMap.end() )
3885             aFiltered.push_back( aFace );
3886         }
3887         aFaces = aFiltered;
3888         if ( aFaces.size() < 2 )  // no neihgbour faces
3889           continue;
3890         else if ( myIsOnlyManifold && aFaces.size() > 2 ) // non manifold case
3891         {
3892           theNonManifold.insert( aLink );
3893           continue;
3894         }
3895       }
3896
3897       // compare normal with normals of neighbor element
3898       SMDS_MeshFace* aPrevFace = aDMapLinkFace[ aLink ];
3899       ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin();
3900       for ( ; pFace != aFaces.end(); ++pFace )
3901       {
3902         SMDS_MeshFace* aNextFace = *pFace;
3903         if ( aPrevFace == aNextFace )
3904           continue;
3905         int anNextFaceID = aNextFace->GetID();
3906         if ( myIsOnlyManifold && theResFaces.Contains( anNextFaceID ) )
3907          // should not be with non manifold restriction. probably bad topology
3908           continue;
3909         // check if face was treated and skipped
3910         if ( myMapBadGeomIds.Contains( anNextFaceID ) ||
3911              !isInPlane( aPrevFace, aNextFace ) )
3912           continue;
3913         // add new element to connected and extend the boundaries.
3914         theResFaces.Add( anNextFaceID );
3915         expandBoundary( aMapOfBoundary, aSeqOfBoundary,
3916                         aDMapLinkFace, theNonManifold, aNextFace );
3917         isToReset = true;
3918       }
3919     }
3920     isDone = !isToReset;
3921   }
3922
3923   return !theResFaces.IsEmpty();
3924 }
3925
3926 bool ManifoldPart::isInPlane( const SMDS_MeshFace* theFace1,
3927                               const SMDS_MeshFace* theFace2 )
3928 {
3929   gp_Dir aNorm1 = gp_Dir( getNormale( theFace1 ) );
3930   gp_XYZ aNorm2XYZ = getNormale( theFace2 );
3931   if ( aNorm2XYZ.SquareModulus() <= gp::Resolution() )
3932   {
3933     myMapBadGeomIds.Add( theFace2->GetID() );
3934     return false;
3935   }
3936   if ( aNorm1.IsParallel( gp_Dir( aNorm2XYZ ), myAngToler ) )
3937     return true;
3938
3939   return false;
3940 }
3941
3942 void ManifoldPart::expandBoundary
3943                    ( ManifoldPart::TMapOfLink&            theMapOfBoundary,
3944                      ManifoldPart::TVectorOfLink&         theSeqOfBoundary,
3945                      ManifoldPart::TDataMapOfLinkFacePtr& theDMapLinkFacePtr,
3946                      ManifoldPart::TMapOfLink&            theNonManifold,
3947                      SMDS_MeshFace*                       theNextFace ) const
3948 {
3949   ManifoldPart::TVectorOfLink aLinks;
3950   getLinks( theNextFace, aLinks );
3951   int aNbLink = (int)aLinks.size();
3952   for ( int i = 0; i < aNbLink; i++ )
3953   {
3954     ManifoldPart::Link aLink = aLinks[ i ];
3955     if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) )
3956       continue;
3957     if ( theMapOfBoundary.find( aLink ) != theMapOfBoundary.end() )
3958     {
3959       if ( myIsOnlyManifold )
3960       {
3961         // remove from boundary
3962         theMapOfBoundary.erase( aLink );
3963         ManifoldPart::TVectorOfLink::iterator pLink = theSeqOfBoundary.begin();
3964         for ( ; pLink != theSeqOfBoundary.end(); ++pLink )
3965         {
3966           ManifoldPart::Link aBoundLink = *pLink;
3967           if ( aBoundLink.IsEqual( aLink ) )
3968           {
3969             theSeqOfBoundary.erase( pLink );
3970             break;
3971           }
3972         }
3973       }
3974     }
3975     else
3976     {
3977       theMapOfBoundary.insert( aLink );
3978       theSeqOfBoundary.push_back( aLink );
3979       theDMapLinkFacePtr[ aLink ] = theNextFace;
3980     }
3981   }
3982 }
3983
3984 void ManifoldPart::getFacesByLink( const ManifoldPart::Link& theLink,
3985                                    ManifoldPart::TVectorOfFacePtr& theFaces ) const
3986 {
3987   std::set<SMDS_MeshCell *> aSetOfFaces;
3988   // take all faces that shared first node
3989   SMDS_ElemIteratorPtr anItr = theLink.myNode1->facesIterator();
3990   for ( ; anItr->more(); )
3991   {
3992     SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next();
3993     if ( !aFace )
3994       continue;
3995     aSetOfFaces.insert( aFace );
3996   }
3997   // take all faces that shared second node
3998   anItr = theLink.myNode2->facesIterator();
3999   // find the common part of two sets
4000   for ( ; anItr->more(); )
4001   {
4002     SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next();
4003     if ( aSetOfFaces.count( aFace ) )
4004       theFaces.push_back( aFace );
4005   }
4006 }
4007
4008 /*
4009   Class       : BelongToMeshGroup
4010   Description : Verify whether a mesh element is included into a mesh group
4011 */
4012 BelongToMeshGroup::BelongToMeshGroup(): myGroup( 0 )
4013 {
4014 }
4015
4016 void BelongToMeshGroup::SetGroup( SMESHDS_GroupBase* g )
4017 {
4018   myGroup = g;
4019 }
4020
4021 void BelongToMeshGroup::SetStoreName( const std::string& sn )
4022 {
4023   myStoreName = sn;
4024 }
4025
4026 void BelongToMeshGroup::SetMesh( const SMDS_Mesh* theMesh )
4027 {
4028   if ( myGroup && myGroup->GetMesh() != theMesh )
4029   {
4030     myGroup = 0;
4031   }
4032   if ( !myGroup && !myStoreName.empty() )
4033   {
4034     if ( const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh))
4035     {
4036       const std::set<SMESHDS_GroupBase*>& grps = aMesh->GetGroups();
4037       std::set<SMESHDS_GroupBase*>::const_iterator g = grps.begin();
4038       for ( ; g != grps.end() && !myGroup; ++g )
4039         if ( *g && myStoreName == (*g)->GetStoreName() )
4040           myGroup = *g;
4041     }
4042   }
4043   if ( myGroup )
4044   {
4045     myGroup->IsEmpty(); // make GroupOnFilter update its predicate
4046   }
4047 }
4048
4049 bool BelongToMeshGroup::IsSatisfy( long theElementId )
4050 {
4051   return myGroup ? myGroup->Contains( theElementId ) : false;
4052 }
4053
4054 SMDSAbs_ElementType BelongToMeshGroup::GetType() const
4055 {
4056   return myGroup ? myGroup->GetType() : SMDSAbs_All;
4057 }
4058
4059 //================================================================================
4060 //  ElementsOnSurface
4061 //================================================================================
4062
4063 ElementsOnSurface::ElementsOnSurface()
4064 {
4065   myIds.Clear();
4066   myType = SMDSAbs_All;
4067   mySurf.Nullify();
4068   myToler = Precision::Confusion();
4069   myUseBoundaries = false;
4070 }
4071
4072 ElementsOnSurface::~ElementsOnSurface()
4073 {
4074 }
4075
4076 void ElementsOnSurface::SetMesh( const SMDS_Mesh* theMesh )
4077 {
4078   myMeshModifTracer.SetMesh( theMesh );
4079   if ( myMeshModifTracer.IsMeshModified())
4080     process();
4081 }
4082
4083 bool ElementsOnSurface::IsSatisfy( long theElementId )
4084 {
4085   return myIds.Contains( theElementId );
4086 }
4087
4088 SMDSAbs_ElementType ElementsOnSurface::GetType() const
4089 { return myType; }
4090
4091 void ElementsOnSurface::SetTolerance( const double theToler )
4092 {
4093   if ( myToler != theToler )
4094     myIds.Clear();
4095   myToler = theToler;
4096 }
4097
4098 double ElementsOnSurface::GetTolerance() const
4099 { return myToler; }
4100
4101 void ElementsOnSurface::SetUseBoundaries( bool theUse )
4102 {
4103   if ( myUseBoundaries != theUse ) {
4104     myUseBoundaries = theUse;
4105     SetSurface( mySurf, myType );
4106   }
4107 }
4108
4109 void ElementsOnSurface::SetSurface( const TopoDS_Shape& theShape,
4110                                     const SMDSAbs_ElementType theType )
4111 {
4112   myIds.Clear();
4113   myType = theType;
4114   mySurf.Nullify();
4115   if ( theShape.IsNull() || theShape.ShapeType() != TopAbs_FACE )
4116     return;
4117   mySurf = TopoDS::Face( theShape );
4118   BRepAdaptor_Surface SA( mySurf, myUseBoundaries );
4119   Standard_Real
4120     u1 = SA.FirstUParameter(),
4121     u2 = SA.LastUParameter(),
4122     v1 = SA.FirstVParameter(),
4123     v2 = SA.LastVParameter();
4124   Handle(Geom_Surface) surf = BRep_Tool::Surface( mySurf );
4125   myProjector.Init( surf, u1,u2, v1,v2 );
4126   process();
4127 }
4128
4129 void ElementsOnSurface::process()
4130 {
4131   myIds.Clear();
4132   if ( mySurf.IsNull() )
4133     return;
4134
4135   if ( !myMeshModifTracer.GetMesh() )
4136     return;
4137
4138   myIds.ReSize( myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType ));
4139
4140   SMDS_ElemIteratorPtr anIter = myMeshModifTracer.GetMesh()->elementsIterator( myType );
4141   for(; anIter->more(); )
4142     process( anIter->next() );
4143 }
4144
4145 void ElementsOnSurface::process( const SMDS_MeshElement* theElemPtr )
4146 {
4147   SMDS_ElemIteratorPtr aNodeItr = theElemPtr->nodesIterator();
4148   bool isSatisfy = true;
4149   for ( ; aNodeItr->more(); )
4150   {
4151     SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next();
4152     if ( !isOnSurface( aNode ) )
4153     {
4154       isSatisfy = false;
4155       break;
4156     }
4157   }
4158   if ( isSatisfy )
4159     myIds.Add( theElemPtr->GetID() );
4160 }
4161
4162 bool ElementsOnSurface::isOnSurface( const SMDS_MeshNode* theNode )
4163 {
4164   if ( mySurf.IsNull() )
4165     return false;
4166
4167   gp_Pnt aPnt( theNode->X(), theNode->Y(), theNode->Z() );
4168   //  double aToler2 = myToler * myToler;
4169 //   if ( mySurf->IsKind(STANDARD_TYPE(Geom_Plane)))
4170 //   {
4171 //     gp_Pln aPln = Handle(Geom_Plane)::DownCast(mySurf)->Pln();
4172 //     if ( aPln.SquareDistance( aPnt ) > aToler2 )
4173 //       return false;
4174 //   }
4175 //   else if ( mySurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)))
4176 //   {
4177 //     gp_Cylinder aCyl = Handle(Geom_CylindricalSurface)::DownCast(mySurf)->Cylinder();
4178 //     double aRad = aCyl.Radius();
4179 //     gp_Ax3 anAxis = aCyl.Position();
4180 //     gp_XYZ aLoc = aCyl.Location().XYZ();
4181 //     double aXDist = anAxis.XDirection().XYZ() * ( aPnt.XYZ() - aLoc );
4182 //     double aYDist = anAxis.YDirection().XYZ() * ( aPnt.XYZ() - aLoc );
4183 //     if ( fabs(aXDist*aXDist + aYDist*aYDist - aRad*aRad) > aToler2 )
4184 //       return false;
4185 //   }
4186 //   else
4187 //     return false;
4188   myProjector.Perform( aPnt );
4189   bool isOn = ( myProjector.IsDone() && myProjector.LowerDistance() <= myToler );
4190
4191   return isOn;
4192 }
4193
4194
4195 //================================================================================
4196 //  ElementsOnShape
4197 //================================================================================
4198
4199 namespace {
4200   const int theIsCheckedFlag = 0x0000100;
4201 }
4202
4203 struct ElementsOnShape::Classifier
4204 {
4205   Classifier() { mySolidClfr = 0; myFlags = 0; }
4206   ~Classifier();
4207   void Init(const TopoDS_Shape& s, double tol, const Bnd_B3d* box = 0 );
4208   bool IsOut(const gp_Pnt& p)        { return SetChecked( true ), (this->*myIsOutFun)( p ); }
4209   TopAbs_ShapeEnum ShapeType() const { return myShape.ShapeType(); }
4210   const TopoDS_Shape& Shape() const  { return myShape; }
4211   const Bnd_B3d* GetBndBox() const   { return & myBox; }
4212   bool IsChecked()                   { return myFlags & theIsCheckedFlag; }
4213   bool IsSetFlag( int flag ) const   { return myFlags & flag; }
4214   void SetChecked( bool is ) { is ? SetFlag( theIsCheckedFlag ) : UnsetFlag( theIsCheckedFlag ); }
4215   void SetFlag  ( int flag ) { myFlags |= flag; }
4216   void UnsetFlag( int flag ) { myFlags &= ~flag; }
4217
4218 private:
4219   bool isOutOfSolid (const gp_Pnt& p);
4220   bool isOutOfBox   (const gp_Pnt& p);
4221   bool isOutOfFace  (const gp_Pnt& p);
4222   bool isOutOfEdge  (const gp_Pnt& p);
4223   bool isOutOfVertex(const gp_Pnt& p);
4224   bool isBox        (const TopoDS_Shape& s);
4225
4226   bool (Classifier::*          myIsOutFun)(const gp_Pnt& p);
4227   BRepClass3d_SolidClassifier* mySolidClfr; // ptr because of a run-time forbidden copy-constructor
4228   Bnd_B3d                      myBox;
4229   GeomAPI_ProjectPointOnSurf   myProjFace;
4230   GeomAPI_ProjectPointOnCurve  myProjEdge;
4231   gp_Pnt                       myVertexXYZ;
4232   TopoDS_Shape                 myShape;
4233   double                       myTol;
4234   int                          myFlags;
4235 };
4236
4237 struct ElementsOnShape::OctreeClassifier : public SMESH_Octree
4238 {
4239   OctreeClassifier( const std::vector< ElementsOnShape::Classifier* >& classifiers );
4240   OctreeClassifier( const OctreeClassifier*                           otherTree,
4241                     const std::vector< ElementsOnShape::Classifier >& clsOther,
4242                     std::vector< ElementsOnShape::Classifier >&       cls );
4243   void GetClassifiersAtPoint( const gp_XYZ& p,
4244                               std::vector< ElementsOnShape::Classifier* >& classifiers );
4245 protected:
4246   OctreeClassifier() {}
4247   SMESH_Octree* newChild() const { return new OctreeClassifier; }
4248   void          buildChildrenData();
4249   Bnd_B3d*      buildRootBox();
4250
4251   std::vector< ElementsOnShape::Classifier* > myClassifiers;
4252 };
4253
4254
4255 ElementsOnShape::ElementsOnShape():
4256   myOctree(0),
4257   myType(SMDSAbs_All),
4258   myToler(Precision::Confusion()),
4259   myAllNodesFlag(false)
4260 {
4261 }
4262
4263 ElementsOnShape::~ElementsOnShape()
4264 {
4265   clearClassifiers();
4266 }
4267
4268 Predicate* ElementsOnShape::clone() const
4269 {
4270   ElementsOnShape* cln = new ElementsOnShape();
4271   cln->SetAllNodes ( myAllNodesFlag );
4272   cln->SetTolerance( myToler );
4273   cln->SetMesh     ( myMeshModifTracer.GetMesh() );
4274   cln->myShape = myShape; // avoid creation of myClassifiers
4275   cln->SetShape    ( myShape, myType );
4276   cln->myClassifiers.resize( myClassifiers.size() );
4277   for ( size_t i = 0; i < myClassifiers.size(); ++i )
4278     cln->myClassifiers[ i ].Init( BRepBuilderAPI_Copy( myClassifiers[ i ].Shape()),
4279                                   myToler, myClassifiers[ i ].GetBndBox() );
4280   if ( myOctree ) // copy myOctree
4281   {
4282     cln->myOctree = new OctreeClassifier( myOctree, myClassifiers, cln->myClassifiers );
4283   }
4284   return cln;
4285 }
4286
4287 SMDSAbs_ElementType ElementsOnShape::GetType() const
4288 {
4289   return myType;
4290 }
4291
4292 void ElementsOnShape::SetTolerance (const double theToler)
4293 {
4294   if (myToler != theToler) {
4295     myToler = theToler;
4296     SetShape(myShape, myType);
4297   }
4298 }
4299
4300 double ElementsOnShape::GetTolerance() const
4301 {
4302   return myToler;
4303 }
4304
4305 void ElementsOnShape::SetAllNodes (bool theAllNodes)
4306 {
4307   myAllNodesFlag = theAllNodes;
4308 }
4309
4310 void ElementsOnShape::SetMesh (const SMDS_Mesh* theMesh)
4311 {
4312   myMeshModifTracer.SetMesh( theMesh );
4313   if ( myMeshModifTracer.IsMeshModified())
4314   {
4315     size_t nbNodes = theMesh ? theMesh->NbNodes() : 0;
4316     if ( myNodeIsChecked.size() == nbNodes )
4317     {
4318       std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false );
4319     }
4320     else
4321     {
4322       SMESHUtils::FreeVector( myNodeIsChecked );
4323       SMESHUtils::FreeVector( myNodeIsOut );
4324       myNodeIsChecked.resize( nbNodes, false );
4325       myNodeIsOut.resize( nbNodes );
4326     }
4327   }
4328 }
4329
4330 bool ElementsOnShape::getNodeIsOut( const SMDS_MeshNode* n, bool& isOut )
4331 {
4332   if ( n->GetID() >= (int) myNodeIsChecked.size() ||
4333        !myNodeIsChecked[ n->GetID() ])
4334     return false;
4335
4336   isOut = myNodeIsOut[ n->GetID() ];
4337   return true;
4338 }
4339
4340 void ElementsOnShape::setNodeIsOut( const SMDS_MeshNode* n, bool  isOut )
4341 {
4342   if ( n->GetID() < (int) myNodeIsChecked.size() )
4343   {
4344     myNodeIsChecked[ n->GetID() ] = true;
4345     myNodeIsOut    [ n->GetID() ] = isOut;
4346   }
4347 }
4348
4349 void ElementsOnShape::SetShape (const TopoDS_Shape&       theShape,
4350                                 const SMDSAbs_ElementType theType)
4351 {
4352   bool shapeChanges = ( myShape != theShape );
4353   myType  = theType;
4354   myShape = theShape;
4355   if ( myShape.IsNull() ) return;
4356
4357   if ( shapeChanges )
4358   {
4359     // find most complex shapes
4360     TopTools_IndexedMapOfShape shapesMap;
4361     TopAbs_ShapeEnum shapeTypes[4] = { TopAbs_SOLID, TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX };
4362     TopExp_Explorer sub;
4363     for ( int i = 0; i < 4; ++i )
4364     {
4365       if ( shapesMap.IsEmpty() )
4366         for ( sub.Init( myShape, shapeTypes[i] ); sub.More(); sub.Next() )
4367           shapesMap.Add( sub.Current() );
4368       if ( i > 0 )
4369         for ( sub.Init( myShape, shapeTypes[i], shapeTypes[i-1] ); sub.More(); sub.Next() )
4370           shapesMap.Add( sub.Current() );
4371     }
4372
4373     clearClassifiers();
4374     myClassifiers.resize( shapesMap.Extent() );
4375     for ( int i = 0; i < shapesMap.Extent(); ++i )
4376       myClassifiers[ i ].Init( shapesMap( i+1 ), myToler );
4377   }
4378
4379   if ( theType == SMDSAbs_Node )
4380   {
4381     SMESHUtils::FreeVector( myNodeIsChecked );
4382     SMESHUtils::FreeVector( myNodeIsOut );
4383   }
4384   else
4385   {
4386     std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false );
4387   }
4388 }
4389
4390 void ElementsOnShape::clearClassifiers()
4391 {
4392   // for ( size_t i = 0; i < myClassifiers.size(); ++i )
4393   //   delete myClassifiers[ i ];
4394   myClassifiers.clear();
4395
4396   delete myOctree;
4397   myOctree = 0;
4398 }
4399
4400 bool ElementsOnShape::IsSatisfy( long elemId )
4401 {
4402   if ( myClassifiers.empty() )
4403     return false;
4404
4405   const SMDS_Mesh* mesh = myMeshModifTracer.GetMesh();
4406   if ( myType == SMDSAbs_Node )
4407     return IsSatisfy( mesh->FindNode( elemId ));
4408   return IsSatisfy( mesh->FindElement( elemId ));
4409 }
4410
4411 bool ElementsOnShape::IsSatisfy (const SMDS_MeshElement* elem)
4412 {
4413   if ( !elem )
4414     return false;
4415
4416   bool isSatisfy = myAllNodesFlag, isNodeOut;
4417
4418   gp_XYZ centerXYZ (0, 0, 0);
4419
4420   if ( !myOctree && myClassifiers.size() > 5 )
4421   {
4422     myWorkClassifiers.resize( myClassifiers.size() );
4423     for ( size_t i = 0; i < myClassifiers.size(); ++i )
4424       myWorkClassifiers[ i ] = & myClassifiers[ i ];
4425     myOctree = new OctreeClassifier( myWorkClassifiers );
4426   }
4427
4428   SMDS_ElemIteratorPtr aNodeItr = elem->nodesIterator();
4429   while (aNodeItr->more() && (isSatisfy == myAllNodesFlag))
4430   {
4431     SMESH_TNodeXYZ aPnt( aNodeItr->next() );
4432     centerXYZ += aPnt;
4433
4434     isNodeOut = true;
4435     if ( !getNodeIsOut( aPnt._node, isNodeOut ))
4436     {
4437       if ( myOctree )
4438       {
4439         myWorkClassifiers.clear();
4440         myOctree->GetClassifiersAtPoint( aPnt, myWorkClassifiers );
4441
4442         for ( size_t i = 0; i < myWorkClassifiers.size(); ++i )
4443           myWorkClassifiers[i]->SetChecked( false );
4444
4445         for ( size_t i = 0; i < myWorkClassifiers.size() && isNodeOut; ++i )
4446           if ( !myWorkClassifiers[i]->IsChecked() )
4447             isNodeOut = myWorkClassifiers[i]->IsOut( aPnt );
4448       }
4449       else
4450       {
4451         for ( size_t i = 0; i < myClassifiers.size() && isNodeOut; ++i )
4452           isNodeOut = myClassifiers[i].IsOut( aPnt );
4453       }
4454       setNodeIsOut( aPnt._node, isNodeOut );
4455     }
4456     isSatisfy = !isNodeOut;
4457   }
4458
4459   // Check the center point for volumes MantisBug 0020168
4460   if ( isSatisfy &&
4461        myAllNodesFlag &&
4462        myClassifiers[0].ShapeType() == TopAbs_SOLID )
4463   {
4464     centerXYZ /= elem->NbNodes();
4465     isSatisfy = false;
4466     if ( myOctree )
4467       for ( size_t i = 0; i < myWorkClassifiers.size() && !isSatisfy; ++i )
4468         isSatisfy = ! myWorkClassifiers[i]->IsOut( centerXYZ );
4469     else
4470       for ( size_t i = 0; i < myClassifiers.size() && !isSatisfy; ++i )
4471         isSatisfy = ! myClassifiers[i].IsOut( centerXYZ );
4472   }
4473
4474   return isSatisfy;
4475 }
4476
4477 bool ElementsOnShape::IsSatisfy (const SMDS_MeshNode* node,
4478                                  TopoDS_Shape*        okShape)
4479 {
4480   if ( !node )
4481     return false;
4482
4483   if ( !myOctree && myClassifiers.size() > 5 )
4484   {
4485     myWorkClassifiers.resize( myClassifiers.size() );
4486     for ( size_t i = 0; i < myClassifiers.size(); ++i )
4487       myWorkClassifiers[ i ] = & myClassifiers[ i ];
4488     myOctree = new OctreeClassifier( myWorkClassifiers );
4489   }
4490
4491   bool isNodeOut = true;
4492
4493   if ( okShape || !getNodeIsOut( node, isNodeOut ))
4494   {
4495     SMESH_NodeXYZ aPnt = node;
4496     if ( myOctree )
4497     {
4498       myWorkClassifiers.clear();
4499       myOctree->GetClassifiersAtPoint( aPnt, myWorkClassifiers );
4500
4501       for ( size_t i = 0; i < myWorkClassifiers.size(); ++i )
4502         myWorkClassifiers[i]->SetChecked( false );
4503
4504       for ( size_t i = 0; i < myWorkClassifiers.size(); ++i )
4505         if ( !myWorkClassifiers[i]->IsChecked() &&
4506              !myWorkClassifiers[i]->IsOut( aPnt ))
4507         {
4508           isNodeOut = false;
4509           if ( okShape )
4510             *okShape = myWorkClassifiers[i]->Shape();
4511           break;
4512         }
4513     }
4514     else
4515     {
4516       for ( size_t i = 0; i < myClassifiers.size(); ++i )
4517         if ( !myClassifiers[i].IsOut( aPnt ))
4518         {
4519           isNodeOut = false;
4520           if ( okShape )
4521             *okShape = myWorkClassifiers[i]->Shape();
4522           break;
4523         }
4524     }
4525     setNodeIsOut( node, isNodeOut );
4526   }
4527
4528   return !isNodeOut;
4529 }
4530
4531 void ElementsOnShape::Classifier::Init( const TopoDS_Shape& theShape,
4532                                         double              theTol,
4533                                         const Bnd_B3d*      theBox )
4534 {
4535   myShape = theShape;
4536   myTol   = theTol;
4537   myFlags = 0;
4538
4539   bool isShapeBox = false;
4540   switch ( myShape.ShapeType() )
4541   {
4542   case TopAbs_SOLID:
4543   {
4544     if (( isShapeBox = isBox( theShape )))
4545     {
4546       myIsOutFun = & ElementsOnShape::Classifier::isOutOfBox;
4547     }
4548     else
4549     {
4550       mySolidClfr = new BRepClass3d_SolidClassifier(theShape);
4551       myIsOutFun = & ElementsOnShape::Classifier::isOutOfSolid;
4552     }
4553     break;
4554   }
4555   case TopAbs_FACE:
4556   {
4557     Standard_Real u1,u2,v1,v2;
4558     Handle(Geom_Surface) surf = BRep_Tool::Surface( TopoDS::Face( theShape ));
4559     surf->Bounds( u1,u2,v1,v2 );
4560     myProjFace.Init(surf, u1,u2, v1,v2, myTol );
4561     myIsOutFun = & ElementsOnShape::Classifier::isOutOfFace;
4562     break;
4563   }
4564   case TopAbs_EDGE:
4565   {
4566     Standard_Real u1, u2;
4567     Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( theShape ), u1, u2);
4568     myProjEdge.Init(curve, u1, u2);
4569     myIsOutFun = & ElementsOnShape::Classifier::isOutOfEdge;
4570     break;
4571   }
4572   case TopAbs_VERTEX:
4573   {
4574     myVertexXYZ = BRep_Tool::Pnt( TopoDS::Vertex( theShape ) );
4575     myIsOutFun = & ElementsOnShape::Classifier::isOutOfVertex;
4576     break;
4577   }
4578   default:
4579     throw SALOME_Exception("Programmer error in usage of ElementsOnShape::Classifier");
4580   }
4581
4582   if ( !isShapeBox )
4583   {
4584     if ( theBox )
4585     {
4586       myBox = *theBox;
4587     }
4588     else
4589     {
4590       Bnd_Box box;
4591       BRepBndLib::Add( myShape, box );
4592       myBox.Clear();
4593       myBox.Add( box.CornerMin() );
4594       myBox.Add( box.CornerMax() );
4595       gp_XYZ halfSize = 0.5 * ( box.CornerMax().XYZ() - box.CornerMin().XYZ() );
4596       for ( int iDim = 1; iDim <= 3; ++iDim )
4597       {
4598         double x = halfSize.Coord( iDim );
4599         halfSize.SetCoord( iDim, x + Max( myTol, 1e-2 * x ));
4600       }
4601       myBox.SetHSize( halfSize );
4602     }
4603   }
4604 }
4605
4606 ElementsOnShape::Classifier::~Classifier()
4607 {
4608   delete mySolidClfr; mySolidClfr = 0;
4609 }
4610
4611 bool ElementsOnShape::Classifier::isOutOfSolid (const gp_Pnt& p)
4612 {
4613   mySolidClfr->Perform( p, myTol );
4614   return ( mySolidClfr->State() != TopAbs_IN && mySolidClfr->State() != TopAbs_ON );
4615 }
4616
4617 bool ElementsOnShape::Classifier::isOutOfBox (const gp_Pnt& p)
4618 {
4619   return myBox.IsOut( p.XYZ() );
4620 }
4621
4622 bool ElementsOnShape::Classifier::isOutOfFace  (const gp_Pnt& p)
4623 {
4624   myProjFace.Perform( p );
4625   if ( myProjFace.IsDone() && myProjFace.LowerDistance() <= myTol )
4626   {
4627     // check relatively to the face
4628     Standard_Real u, v;
4629     myProjFace.LowerDistanceParameters(u, v);
4630     gp_Pnt2d aProjPnt (u, v);
4631     BRepClass_FaceClassifier aClsf ( TopoDS::Face( myShape ), aProjPnt, myTol );
4632     if ( aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON )
4633       return false;
4634   }
4635   return true;
4636 }
4637
4638 bool ElementsOnShape::Classifier::isOutOfEdge  (const gp_Pnt& p)
4639 {
4640   myProjEdge.Perform( p );
4641   return ! ( myProjEdge.NbPoints() > 0 && myProjEdge.LowerDistance() <= myTol );
4642 }
4643
4644 bool ElementsOnShape::Classifier::isOutOfVertex(const gp_Pnt& p)
4645 {
4646   return ( myVertexXYZ.Distance( p ) > myTol );
4647 }
4648
4649 bool ElementsOnShape::Classifier::isBox (const TopoDS_Shape& theShape)
4650 {
4651   TopTools_IndexedMapOfShape vMap;
4652   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4653   if ( vMap.Extent() != 8 )
4654     return false;
4655
4656   myBox.Clear();
4657   for ( int i = 1; i <= 8; ++i )
4658     myBox.Add( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))).XYZ() );
4659
4660   gp_XYZ pMin = myBox.CornerMin(), pMax = myBox.CornerMax();
4661   for ( int i = 1; i <= 8; ++i )
4662   {
4663     gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vMap( i )));
4664     for ( int iC = 1; iC <= 3; ++ iC )
4665     {
4666       double d1 = Abs( pMin.Coord( iC ) - p.Coord( iC ));
4667       double d2 = Abs( pMax.Coord( iC ) - p.Coord( iC ));
4668       if ( Min( d1, d2 ) > myTol )
4669         return false;
4670     }
4671   }
4672   myBox.Enlarge( myTol );
4673   return true;
4674 }
4675
4676 ElementsOnShape::
4677 OctreeClassifier::OctreeClassifier( const std::vector< ElementsOnShape::Classifier* >& classifiers )
4678   :SMESH_Octree( new SMESH_TreeLimit )
4679 {
4680   myClassifiers = classifiers;
4681   compute();
4682 }
4683
4684 ElementsOnShape::
4685 OctreeClassifier::OctreeClassifier( const OctreeClassifier*                           otherTree,
4686                                     const std::vector< ElementsOnShape::Classifier >& clsOther,
4687                                     std::vector< ElementsOnShape::Classifier >&       cls )
4688   :SMESH_Octree( new SMESH_TreeLimit )
4689 {
4690   myBox = new Bnd_B3d( *otherTree->getBox() );
4691
4692   if (( myIsLeaf = otherTree->isLeaf() ))
4693   {
4694     myClassifiers.resize( otherTree->myClassifiers.size() );
4695     for ( size_t i = 0; i < otherTree->myClassifiers.size(); ++i )
4696     {
4697       int ind = otherTree->myClassifiers[i] - & clsOther[0];
4698       myClassifiers[ i ] = & cls[ ind ];
4699     }
4700   }
4701   else if ( otherTree->myChildren )
4702   {
4703     myChildren = new SMESH_Tree< Bnd_B3d, 8 > * [ 8 ];
4704     for ( int i = 0; i < nbChildren(); i++ )
4705       myChildren[i] =
4706         new OctreeClassifier( static_cast<const OctreeClassifier*>( otherTree->myChildren[i]),
4707                               clsOther, cls );
4708   }
4709 }
4710
4711 void ElementsOnShape::
4712 OctreeClassifier::GetClassifiersAtPoint( const gp_XYZ& point,
4713                                          std::vector< ElementsOnShape::Classifier* >& result )
4714 {
4715   if ( getBox()->IsOut( point ))
4716     return;
4717
4718   if ( isLeaf() )
4719   {
4720     for ( size_t i = 0; i < myClassifiers.size(); ++i )
4721       if ( !myClassifiers[i]->GetBndBox()->IsOut( point ))
4722         result.push_back( myClassifiers[i] );
4723   }
4724   else
4725   {
4726     for (int i = 0; i < nbChildren(); i++)
4727       ((OctreeClassifier*) myChildren[i])->GetClassifiersAtPoint( point, result );
4728   }
4729 }
4730
4731 void ElementsOnShape::OctreeClassifier::buildChildrenData()
4732 {
4733   // distribute myClassifiers among myChildren
4734
4735   const int childFlag[8] = { 0x0000001,
4736                              0x0000002,
4737                              0x0000004,
4738                              0x0000008,
4739                              0x0000010,
4740                              0x0000020,
4741                              0x0000040,
4742                              0x0000080 };
4743   int nbInChild[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
4744
4745   for ( size_t i = 0; i < myClassifiers.size(); ++i )
4746   {
4747     for ( int j = 0; j < nbChildren(); j++ )
4748     {
4749       if ( !myClassifiers[i]->GetBndBox()->IsOut( *myChildren[j]->getBox() ))
4750       {
4751         myClassifiers[i]->SetFlag( childFlag[ j ]);
4752         ++nbInChild[ j ];
4753       }
4754     }
4755   }
4756
4757   for ( int j = 0; j < nbChildren(); j++ )
4758   {
4759     OctreeClassifier* child = static_cast<OctreeClassifier*>( myChildren[ j ]);
4760     child->myClassifiers.resize( nbInChild[ j ]);
4761     for ( size_t i = 0; nbInChild[ j ] && i < myClassifiers.size(); ++i )
4762     {
4763       if ( myClassifiers[ i ]->IsSetFlag( childFlag[ j ]))
4764       {
4765         --nbInChild[ j ];
4766         child->myClassifiers[ nbInChild[ j ]] = myClassifiers[ i ];
4767         myClassifiers[ i ]->UnsetFlag( childFlag[ j ]);
4768       }
4769     }
4770   }
4771   SMESHUtils::FreeVector( myClassifiers );
4772
4773   // define if a child isLeaf()
4774   for ( int i = 0; i < nbChildren(); i++ )
4775   {
4776     OctreeClassifier* child = static_cast<OctreeClassifier*>( myChildren[ i ]);
4777     child->myIsLeaf = ( child->myClassifiers.size() <= 5  );
4778   }
4779 }
4780
4781 Bnd_B3d* ElementsOnShape::OctreeClassifier::buildRootBox()
4782 {
4783   Bnd_B3d* box = new Bnd_B3d;
4784   for ( size_t i = 0; i < myClassifiers.size(); ++i )
4785     box->Add( *myClassifiers[i]->GetBndBox() );
4786   return box;
4787 }
4788
4789 /*
4790   Class       : BelongToGeom
4791   Description : Predicate for verifying whether entity belongs to
4792                 specified geometrical support
4793 */
4794
4795 BelongToGeom::BelongToGeom()
4796   : myMeshDS(NULL),
4797     myType(SMDSAbs_NbElementTypes),
4798     myIsSubshape(false),
4799     myTolerance(Precision::Confusion())
4800 {}
4801
4802 Predicate* BelongToGeom::clone() const
4803 {
4804   BelongToGeom* cln = new BelongToGeom( *this );
4805   cln->myElementsOnShapePtr.reset( static_cast<ElementsOnShape*>( myElementsOnShapePtr->clone() ));
4806   return cln;
4807 }
4808
4809 void BelongToGeom::SetMesh( const SMDS_Mesh* theMesh )
4810 {
4811   if ( myMeshDS != theMesh )
4812   {
4813     myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh);
4814     init();
4815   }
4816 }
4817
4818 void BelongToGeom::SetGeom( const TopoDS_Shape& theShape )
4819 {
4820   if ( myShape != theShape )
4821   {
4822     myShape = theShape;
4823     init();
4824   }
4825 }
4826
4827 static bool IsSubShape (const TopTools_IndexedMapOfShape& theMap,
4828                         const TopoDS_Shape&               theShape)
4829 {
4830   if (theMap.Contains(theShape)) return true;
4831
4832   if (theShape.ShapeType() == TopAbs_COMPOUND ||
4833       theShape.ShapeType() == TopAbs_COMPSOLID)
4834   {
4835     TopoDS_Iterator anIt (theShape, Standard_True, Standard_True);
4836     for (; anIt.More(); anIt.Next())
4837     {
4838       if (!IsSubShape(theMap, anIt.Value())) {
4839         return false;
4840       }
4841     }
4842     return true;
4843   }
4844
4845   return false;
4846 }
4847
4848 void BelongToGeom::init()
4849 {
4850   if ( !myMeshDS || myShape.IsNull() ) return;
4851
4852   // is sub-shape of main shape?
4853   TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh();
4854   if (aMainShape.IsNull()) {
4855     myIsSubshape = false;
4856   }
4857   else {
4858     TopTools_IndexedMapOfShape aMap;
4859     TopExp::MapShapes( aMainShape, aMap );
4860     myIsSubshape = IsSubShape( aMap, myShape );
4861     if ( myIsSubshape )
4862     {
4863       aMap.Clear();
4864       TopExp::MapShapes( myShape, aMap );
4865       mySubShapesIDs.Clear();
4866       for ( int i = 1; i <= aMap.Extent(); ++i )
4867       {
4868         int subID = myMeshDS->ShapeToIndex( aMap( i ));
4869         if ( subID > 0 )
4870           mySubShapesIDs.Add( subID );
4871       }
4872     }
4873   }
4874
4875   //if (!myIsSubshape) // to be always ready to check an element not bound to geometry
4876   {
4877     if ( !myElementsOnShapePtr )
4878       myElementsOnShapePtr.reset( new ElementsOnShape() );
4879     myElementsOnShapePtr->SetTolerance( myTolerance );
4880     myElementsOnShapePtr->SetAllNodes( true ); // "belong", while false means "lays on"
4881     myElementsOnShapePtr->SetMesh( myMeshDS );
4882     myElementsOnShapePtr->SetShape( myShape, myType );
4883   }
4884 }
4885
4886 bool BelongToGeom::IsSatisfy (long theId)
4887 {
4888   if (myMeshDS == 0 || myShape.IsNull())
4889     return false;
4890
4891   if (!myIsSubshape)
4892   {
4893     return myElementsOnShapePtr->IsSatisfy(theId);
4894   }
4895
4896   // Case of sub-mesh
4897
4898   if (myType == SMDSAbs_Node)
4899   {
4900     if ( const SMDS_MeshNode* aNode = myMeshDS->FindNode( theId ))
4901     {
4902       if ( aNode->getshapeId() < 1 )
4903         return myElementsOnShapePtr->IsSatisfy(theId);
4904       else
4905         return mySubShapesIDs.Contains( aNode->getshapeId() );
4906     }
4907   }
4908   else
4909   {
4910     if ( const SMDS_MeshElement* anElem = myMeshDS->FindElement( theId ))
4911     {
4912       if ( anElem->GetType() == myType )
4913       {
4914         if ( anElem->getshapeId() < 1 )
4915           return myElementsOnShapePtr->IsSatisfy(theId);
4916         else
4917           return mySubShapesIDs.Contains( anElem->getshapeId() );
4918       }
4919     }
4920   }
4921
4922   return false;
4923 }
4924
4925 void BelongToGeom::SetType (SMDSAbs_ElementType theType)
4926 {
4927   if ( myType != theType )
4928   {
4929     myType = theType;
4930     init();
4931   }
4932 }
4933
4934 SMDSAbs_ElementType BelongToGeom::GetType() const
4935 {
4936   return myType;
4937 }
4938
4939 TopoDS_Shape BelongToGeom::GetShape()
4940 {
4941   return myShape;
4942 }
4943
4944 const SMESHDS_Mesh* BelongToGeom::GetMeshDS() const
4945 {
4946   return myMeshDS;
4947 }
4948
4949 void BelongToGeom::SetTolerance (double theTolerance)
4950 {
4951   myTolerance = theTolerance;
4952   init();
4953 }
4954
4955 double BelongToGeom::GetTolerance()
4956 {
4957   return myTolerance;
4958 }
4959
4960 /*
4961   Class       : LyingOnGeom
4962   Description : Predicate for verifying whether entiy lying or partially lying on
4963   specified geometrical support
4964 */
4965
4966 LyingOnGeom::LyingOnGeom()
4967   : myMeshDS(NULL),
4968     myType(SMDSAbs_NbElementTypes),
4969     myIsSubshape(false),
4970     myTolerance(Precision::Confusion())
4971 {}
4972
4973 Predicate* LyingOnGeom::clone() const
4974 {
4975   LyingOnGeom* cln = new LyingOnGeom( *this );
4976   cln->myElementsOnShapePtr.reset( static_cast<ElementsOnShape*>( myElementsOnShapePtr->clone() ));
4977   return cln;
4978 }
4979
4980 void LyingOnGeom::SetMesh( const SMDS_Mesh* theMesh )
4981 {
4982   if ( myMeshDS != theMesh )
4983   {
4984     myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh);
4985     init();
4986   }
4987 }
4988
4989 void LyingOnGeom::SetGeom( const TopoDS_Shape& theShape )
4990 {
4991   if ( myShape != theShape )
4992   {
4993     myShape = theShape;
4994     init();
4995   }
4996 }
4997
4998 void LyingOnGeom::init()
4999 {
5000   if (!myMeshDS || myShape.IsNull()) return;
5001
5002   // is sub-shape of main shape?
5003   TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh();
5004   if (aMainShape.IsNull()) {
5005     myIsSubshape = false;
5006   }
5007   else {
5008     myIsSubshape = myMeshDS->IsGroupOfSubShapes( myShape );
5009   }
5010
5011   if (myIsSubshape)
5012   {
5013     TopTools_IndexedMapOfShape shapes;
5014     TopExp::MapShapes( myShape, shapes );
5015     mySubShapesIDs.Clear();
5016     for ( int i = 1; i <= shapes.Extent(); ++i )
5017     {
5018       int subID = myMeshDS->ShapeToIndex( shapes( i ));
5019       if ( subID > 0 )
5020         mySubShapesIDs.Add( subID );
5021     }
5022   }
5023   // else // to be always ready to check an element not bound to geometry
5024   {
5025     if ( !myElementsOnShapePtr )
5026       myElementsOnShapePtr.reset( new ElementsOnShape() );
5027     myElementsOnShapePtr->SetTolerance( myTolerance );
5028     myElementsOnShapePtr->SetAllNodes( false ); // lays on, while true means "belong"
5029     myElementsOnShapePtr->SetMesh( myMeshDS );
5030     myElementsOnShapePtr->SetShape( myShape, myType );
5031   }
5032 }
5033
5034 bool LyingOnGeom::IsSatisfy( long theId )
5035 {
5036   if ( myMeshDS == 0 || myShape.IsNull() )
5037     return false;
5038
5039   if (!myIsSubshape)
5040   {
5041     return myElementsOnShapePtr->IsSatisfy(theId);
5042   }
5043
5044   // Case of sub-mesh
5045
5046   const SMDS_MeshElement* elem =
5047     ( myType == SMDSAbs_Node ) ? myMeshDS->FindNode( theId ) : myMeshDS->FindElement( theId );
5048
5049   if ( mySubShapesIDs.Contains( elem->getshapeId() ))
5050     return true;
5051
5052   if ( elem->GetType() != SMDSAbs_Node && elem->GetType() == myType )
5053   {
5054     SMDS_ElemIteratorPtr nodeItr = elem->nodesIterator();
5055     while ( nodeItr->more() )
5056     {
5057       const SMDS_MeshElement* aNode = nodeItr->next();
5058       if ( mySubShapesIDs.Contains( aNode->getshapeId() ))
5059         return true;
5060     }
5061   }
5062
5063   return false;
5064 }
5065
5066 void LyingOnGeom::SetType( SMDSAbs_ElementType theType )
5067 {
5068   if ( myType != theType )
5069   {
5070     myType = theType;
5071     init();
5072   }
5073 }
5074
5075 SMDSAbs_ElementType LyingOnGeom::GetType() const
5076 {
5077   return myType;
5078 }
5079
5080 TopoDS_Shape LyingOnGeom::GetShape()
5081 {
5082   return myShape;
5083 }
5084
5085 const SMESHDS_Mesh* LyingOnGeom::GetMeshDS() const
5086 {
5087   return myMeshDS;
5088 }
5089
5090 void LyingOnGeom::SetTolerance (double theTolerance)
5091 {
5092   myTolerance = theTolerance;
5093   init();
5094 }
5095
5096 double LyingOnGeom::GetTolerance()
5097 {
5098   return myTolerance;
5099 }
5100
5101 TSequenceOfXYZ::TSequenceOfXYZ(): myElem(0)
5102 {}
5103
5104 TSequenceOfXYZ::TSequenceOfXYZ(size_type n) : myArray(n), myElem(0)
5105 {}
5106
5107 TSequenceOfXYZ::TSequenceOfXYZ(size_type n, const gp_XYZ& t) : myArray(n,t), myElem(0)
5108 {}
5109
5110 TSequenceOfXYZ::TSequenceOfXYZ(const TSequenceOfXYZ& theSequenceOfXYZ) : myArray(theSequenceOfXYZ.myArray), myElem(theSequenceOfXYZ.myElem)
5111 {}
5112
5113 template <class InputIterator>
5114 TSequenceOfXYZ::TSequenceOfXYZ(InputIterator theBegin, InputIterator theEnd): myArray(theBegin,theEnd), myElem(0)
5115 {}
5116
5117 TSequenceOfXYZ::~TSequenceOfXYZ()
5118 {}
5119
5120 TSequenceOfXYZ& TSequenceOfXYZ::operator=(const TSequenceOfXYZ& theSequenceOfXYZ)
5121 {
5122   myArray = theSequenceOfXYZ.myArray;
5123   myElem  = theSequenceOfXYZ.myElem;
5124   return *this;
5125 }
5126
5127 gp_XYZ& TSequenceOfXYZ::operator()(size_type n)
5128 {
5129   return myArray[n-1];
5130 }
5131
5132 const gp_XYZ& TSequenceOfXYZ::operator()(size_type n) const
5133 {
5134   return myArray[n-1];
5135 }
5136
5137 void TSequenceOfXYZ::clear()
5138 {
5139   myArray.clear();
5140 }
5141
5142 void TSequenceOfXYZ::reserve(size_type n)
5143 {
5144   myArray.reserve(n);
5145 }
5146
5147 void TSequenceOfXYZ::push_back(const gp_XYZ& v)
5148 {
5149   myArray.push_back(v);
5150 }
5151
5152 TSequenceOfXYZ::size_type TSequenceOfXYZ::size() const
5153 {
5154   return myArray.size();
5155 }
5156
5157 SMDSAbs_EntityType TSequenceOfXYZ::getElementEntity() const
5158 {
5159   return myElem ? myElem->GetEntityType() : SMDSEntity_Last;
5160 }
5161
5162 TMeshModifTracer::TMeshModifTracer():
5163   myMeshModifTime(0), myMesh(0)
5164 {
5165 }
5166 void TMeshModifTracer::SetMesh( const SMDS_Mesh* theMesh )
5167 {
5168   if ( theMesh != myMesh )
5169     myMeshModifTime = 0;
5170   myMesh = theMesh;
5171 }
5172 bool TMeshModifTracer::IsMeshModified()
5173 {
5174   bool modified = false;
5175   if ( myMesh )
5176   {
5177     modified = ( myMeshModifTime != myMesh->GetMTime() );
5178     myMeshModifTime = myMesh->GetMTime();
5179   }
5180   return modified;
5181 }