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