Salome HOME
PAL16231 (3D Extrusion produced crossing hexahedrons)
[modules/smesh.git] / src / SMESH / SMESH_Block.cxx
1 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3 // 
4 //  This library is free software; you can redistribute it and/or 
5 //  modify it under the terms of the GNU Lesser General Public 
6 //  License as published by the Free Software Foundation; either 
7 //  version 2.1 of the License. 
8 // 
9 //  This library is distributed in the hope that it will be useful, 
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 //  Lesser General Public License for more details. 
13 // 
14 //  You should have received a copy of the GNU Lesser General Public 
15 //  License along with this library; if not, write to the Free Software 
16 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
17 // 
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19
20 // File      : SMESH_Pattern.hxx
21 // Created   : Mon Aug  2 10:30:00 2004
22 // Author    : Edward AGAPOV (eap)
23
24 #include "SMESH_Block.hxx"
25
26 #include <BRepAdaptor_Curve.hxx>
27 #include <BRepAdaptor_Curve2d.hxx>
28 #include <BRepAdaptor_Surface.hxx>
29 #include <BRepTools.hxx>
30 #include <BRepTools_WireExplorer.hxx>
31 #include <BRep_Builder.hxx>
32 #include <BRep_Tool.hxx>
33 #include <Bnd_Box.hxx>
34 #include <Extrema_ExtPC.hxx>
35 #include <Extrema_POnCurv.hxx>
36 #include <Geom2d_Curve.hxx>
37 #include <TopExp_Explorer.hxx>
38 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
39 #include <TopTools_ListIteratorOfListOfShape.hxx>
40 #include <TopTools_ListOfShape.hxx>
41 #include <TopoDS.hxx>
42 #include <TopoDS_Compound.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Wire.hxx>
46 #include <gp_Trsf.hxx>
47 #include <gp_Vec.hxx>
48 #include <math_FunctionSetRoot.hxx>
49
50 #include "SMDS_MeshNode.hxx"
51 #include "SMDS_MeshVolume.hxx"
52 #include "SMDS_VolumeTool.hxx"
53 #include "utilities.h"
54
55 #include <list>
56
57 using namespace std;
58
59 //#define DEBUG_PARAM_COMPUTE
60
61 //================================================================================
62 /*!
63  * \brief Set edge data
64   * \param edgeID - block subshape ID
65   * \param curve - edge geometry
66   * \param isForward - is curve orientation coincides with edge orientation in the block
67  */
68 //================================================================================
69
70 void SMESH_Block::TEdge::Set( const int edgeID, Adaptor3d_Curve* curve, const bool isForward )
71 {
72   myCoordInd = SMESH_Block::GetCoordIndOnEdge( edgeID );
73   if ( myC3d ) delete myC3d;
74   myC3d = curve;
75   myFirst = curve->FirstParameter();
76   myLast = curve->LastParameter();
77   if ( !isForward )
78     std::swap( myFirst, myLast );
79 }
80
81 //================================================================================
82 /*!
83  * \brief Set coordinates of nodes at edge ends to work with mesh block
84   * \param edgeID - block subshape ID
85   * \param node1 - coordinates of node with lower ID
86   * \param node2 - coordinates of node with upper ID
87  */
88 //================================================================================
89
90 void SMESH_Block::TEdge::Set( const int edgeID, const gp_XYZ& node1, const gp_XYZ& node2 )
91 {
92   myCoordInd = SMESH_Block::GetCoordIndOnEdge( edgeID );
93   myNodes[ 0 ] = node1;
94   myNodes[ 1 ] = node2;
95
96   if ( myC3d ) delete myC3d;
97   myC3d = 0;
98 }
99
100 //=======================================================================
101 //function : SMESH_Block::TEdge::GetU
102 //purpose  : 
103 //=======================================================================
104
105 double SMESH_Block::TEdge::GetU( const gp_XYZ& theParams ) const
106 {
107   double u = theParams.Coord( myCoordInd );
108   if ( !myC3d ) // if mesh block
109     return u;
110   return ( 1 - u ) * myFirst + u * myLast;
111 }
112
113 //=======================================================================
114 //function : SMESH_Block::TEdge::Point
115 //purpose  : 
116 //=======================================================================
117
118 gp_XYZ SMESH_Block::TEdge::Point( const gp_XYZ& theParams ) const
119 {
120   double u = GetU( theParams );
121   if ( myC3d ) return myC3d->Value( u ).XYZ();
122   // mesh block
123   return myNodes[0] * ( 1 - u ) + myNodes[1] * u;
124 }
125
126 //================================================================================
127 /*!
128  * \brief Destructor
129  */
130 //================================================================================
131
132 SMESH_Block::TEdge::~TEdge()
133 {
134   if ( myC3d ) delete myC3d;
135 }
136
137 //================================================================================
138 /*!
139  * \brief Set face data
140   * \param faceID - block subshape ID
141   * \param S - face surface geometry
142   * \param c2d - 4 pcurves in the order as returned by GetFaceEdgesIDs(faceID)
143   * \param isForward - orientation of pcurves comparing with block edge direction
144  */
145 //================================================================================
146
147 void SMESH_Block::TFace::Set( const int          faceID,
148                               Adaptor3d_Surface* S,
149                               Adaptor2d_Curve2d* c2D[4],
150                               const bool         isForward[4] )
151 {
152   if ( myS ) delete myS;
153   myS = S;
154   // pcurves
155   vector< int > edgeIdVec;
156   GetFaceEdgesIDs( faceID, edgeIdVec );
157   for ( int iE = 0; iE < edgeIdVec.size(); iE++ ) // loop on 4 edges
158   {
159     myCoordInd[ iE ] = GetCoordIndOnEdge( edgeIdVec[ iE ] );
160     if ( myC2d[ iE ]) delete myC2d[ iE ];
161     myC2d[ iE ] = c2D[ iE ];
162     myFirst[ iE ] = myC2d[ iE ]->FirstParameter();
163     myLast [ iE ] = myC2d[ iE ]->LastParameter();
164     if ( !isForward[ iE ])
165       std::swap( myFirst[ iE ], myLast[ iE ] );
166   }
167   // 2d corners
168   myCorner[ 0 ] = myC2d[ 0 ]->Value( myFirst[0] ).XY();
169   myCorner[ 1 ] = myC2d[ 0 ]->Value( myLast[0] ).XY();
170   myCorner[ 2 ] = myC2d[ 1 ]->Value( myLast[1] ).XY();
171   myCorner[ 3 ] = myC2d[ 1 ]->Value( myFirst[1] ).XY();
172 }
173
174 //================================================================================
175 /*!
176  * \brief Set face data to work with mesh block
177   * \param faceID - block subshape ID
178   * \param edgeU0 - filled data of edge u0 = GetFaceEdgesIDs(faceID)[ 0 ]
179   * \param edgeU1 - filled data of edge u1 = GetFaceEdgesIDs(faceID)[ 1 ]
180  */
181 //================================================================================
182
183 void SMESH_Block::TFace::Set( const int faceID, const TEdge& edgeU0, const TEdge& edgeU1 )
184 {
185   vector< int > edgeIdVec;
186   GetFaceEdgesIDs( faceID, edgeIdVec );
187   myNodes[ 0 ] = edgeU0.NodeXYZ( 1 );
188   myNodes[ 1 ] = edgeU0.NodeXYZ( 0 );
189   myNodes[ 2 ] = edgeU1.NodeXYZ( 0 );
190   myNodes[ 3 ] = edgeU1.NodeXYZ( 1 );
191   myCoordInd[ 0 ] = GetCoordIndOnEdge( edgeIdVec[ 0 ] );
192   myCoordInd[ 1 ] = GetCoordIndOnEdge( edgeIdVec[ 1 ] );
193   myCoordInd[ 2 ] = GetCoordIndOnEdge( edgeIdVec[ 2 ] );
194   myCoordInd[ 3 ] = GetCoordIndOnEdge( edgeIdVec[ 3 ] );
195   if ( myS ) delete myS;
196   myS = 0;
197 }
198
199 //================================================================================
200 /*!
201  * \brief Destructor
202  */
203 //================================================================================
204
205 SMESH_Block::TFace::~TFace()
206 {
207   if ( myS ) delete myS;
208   for ( int i = 0 ; i < 4; ++i )
209     if ( myC2d[ i ]) delete myC2d[ i ];
210 }
211
212 //=======================================================================
213 //function : SMESH_Block::TFace::GetCoefs
214 //purpose  : return coefficients for addition of [0-3]-th edge and vertex
215 //=======================================================================
216
217 void SMESH_Block::TFace::GetCoefs(int           iE,
218                                   const gp_XYZ& theParams,
219                                   double&       Ecoef,
220                                   double&       Vcoef ) const
221 {
222   double dU = theParams.Coord( GetUInd() );
223   double dV = theParams.Coord( GetVInd() );
224   switch ( iE ) {
225   case 0:
226     Ecoef = ( 1 - dV ); // u0
227     Vcoef = ( 1 - dU ) * ( 1 - dV ); break; // 00
228   case 1:
229     Ecoef = dV; // u1
230     Vcoef = dU * ( 1 - dV ); break; // 10
231   case 2:
232     Ecoef = ( 1 - dU ); // 0v
233     Vcoef = dU * dV  ; break; // 11
234   case 3:
235     Ecoef = dU  ; // 1v
236     Vcoef = ( 1 - dU ) * dV  ; break; // 01
237   default: ASSERT(0);
238   }
239 }
240
241 //=======================================================================
242 //function : SMESH_Block::TFace::GetUV
243 //purpose  : 
244 //=======================================================================
245
246 gp_XY SMESH_Block::TFace::GetUV( const gp_XYZ& theParams ) const
247 {
248   gp_XY uv(0.,0.);
249   for ( int iE = 0; iE < 4; iE++ ) // loop on 4 edges
250   {
251     double Ecoef = 0, Vcoef = 0;
252     GetCoefs( iE, theParams, Ecoef, Vcoef );
253     // edge addition
254     double u = theParams.Coord( myCoordInd[ iE ] );
255     u = ( 1 - u ) * myFirst[ iE ] + u * myLast[ iE ];
256     uv += Ecoef * myC2d[ iE ]->Value( u ).XY();
257     // corner addition
258     uv -= Vcoef * myCorner[ iE ];
259   }
260   return uv;
261 }
262
263 //=======================================================================
264 //function : SMESH_Block::TFace::Point
265 //purpose  : 
266 //=======================================================================
267
268 gp_XYZ SMESH_Block::TFace::Point( const gp_XYZ& theParams ) const
269 {
270   gp_XYZ p(0.,0.,0.);
271   if ( !myS ) // if mesh block
272   {
273     for ( int iE = 0; iE < 4; iE++ ) // loop on 4 edges
274     {
275       double Ecoef = 0, Vcoef = 0;
276       GetCoefs( iE, theParams, Ecoef, Vcoef );
277       // edge addition
278       double u = theParams.Coord( myCoordInd[ iE ] );
279       int i1 = 0, i2 = 1;
280       switch ( iE ) {
281       case 1: i1 = 3; i2 = 2; break;
282       case 2: i1 = 1; i2 = 2; break;
283       case 3: i1 = 0; i2 = 3; break;
284       }
285       p += Ecoef * ( myNodes[ i1 ] * ( 1 - u ) + myNodes[ i2 ] * u );
286       // corner addition
287       p -= Vcoef * myNodes[ iE ];
288     }
289     
290   }
291   else // shape block
292   {
293     gp_XY uv = GetUV( theParams );
294     p = myS->Value( uv.X(), uv.Y() ).XYZ();
295   }
296   return p;
297 }
298
299 //=======================================================================
300 //function : GetShapeCoef
301 //purpose  : 
302 //=======================================================================
303
304 double* SMESH_Block::GetShapeCoef (const int theShapeID)
305 {
306   static double shapeCoef[][3] = {
307     //    V000,        V100,        V010,         V110
308     { -1,-1,-1 }, {  1,-1,-1 }, { -1, 1,-1 }, {  1, 1,-1 },
309     //    V001,        V101,        V011,         V111,
310     { -1,-1, 1 }, {  1,-1, 1 }, { -1, 1, 1 }, {  1, 1, 1 },
311     //    Ex00,        Ex10,        Ex01,         Ex11,
312     {  0,-1,-1 }, {  0, 1,-1 }, {  0,-1, 1 }, {  0, 1, 1 },
313     //    E0y0,        E1y0,        E0y1,         E1y1,
314     { -1, 0,-1 }, {  1, 0,-1 }, { -1, 0, 1 }, {  1, 0, 1 },
315     //    E00z,        E10z,        E01z,         E11z,
316     { -1,-1, 0 }, {  1,-1, 0 }, { -1, 1, 0 }, {  1, 1, 0 },
317     //    Fxy0,        Fxy1,        Fx0z,         Fx1z,         F0yz,           F1yz,
318     {  0, 0,-1 }, {  0, 0, 1 }, {  0,-1, 0 }, {  0, 1, 0 }, { -1, 0, 0 }, {  1, 0, 0 },
319     // ID_Shell
320     {  0, 0, 0 }
321   };
322   if ( theShapeID < ID_V000 || theShapeID > ID_F1yz )
323     return shapeCoef[ ID_Shell - 1 ];
324
325   return shapeCoef[ theShapeID - 1 ];
326 }
327
328 //=======================================================================
329 //function : ShellPoint
330 //purpose  : return coordinates of a point in shell
331 //=======================================================================
332
333 bool SMESH_Block::ShellPoint( const gp_XYZ& theParams, gp_XYZ& thePoint ) const
334 {
335   thePoint.SetCoord( 0., 0., 0. );
336   for ( int shapeID = ID_V000; shapeID < ID_Shell; shapeID++ )
337   {
338     // coef
339     double* coefs = GetShapeCoef( shapeID );
340     double k = 1;
341     for ( int iCoef = 0; iCoef < 3; iCoef++ ) {
342       if ( coefs[ iCoef ] != 0 ) {
343         if ( coefs[ iCoef ] < 0 )
344           k *= ( 1. - theParams.Coord( iCoef + 1 ));
345         else
346           k *= theParams.Coord( iCoef + 1 );
347       }
348     }
349     // add point on a shape
350     if ( fabs( k ) > DBL_MIN )
351     {
352       gp_XYZ Ps;
353       if ( shapeID < ID_Ex00 ) // vertex
354         VertexPoint( shapeID, Ps );
355       else if ( shapeID < ID_Fxy0 ) { // edge
356         EdgePoint( shapeID, theParams, Ps );
357         k = -k;
358       } else // face
359         FacePoint( shapeID, theParams, Ps );
360
361       thePoint += k * Ps;
362     }
363   }
364   return true;
365 }
366
367 //=======================================================================
368 //function : ShellPoint
369 //purpose  : computes coordinates of a point in shell by points on sub-shapes;
370 //           thePointOnShape[ subShapeID ] must be a point on a subShape
371 //=======================================================================
372
373 bool SMESH_Block::ShellPoint(const gp_XYZ&         theParams,
374                              const vector<gp_XYZ>& thePointOnShape,
375                              gp_XYZ&               thePoint )
376 {
377   if ( thePointOnShape.size() < ID_F1yz )
378     return false;
379
380   double x = theParams.X(), y = theParams.Y(), z = theParams.Z();
381   double x1 = 1. - x,       y1 = 1. - y,       z1 = 1. - z;
382   const vector<gp_XYZ>& p = thePointOnShape;
383
384   thePoint = 
385     x1 * p[ID_F0yz] + x * p[ID_F1yz] +
386     y1 * p[ID_Fx0z] + y * p[ID_Fx1z] +
387     z1 * p[ID_Fxy0] + z * p[ID_Fxy1] +
388     x1 * (y1 * (z1 * p[ID_V000] + z * p[ID_V001])  +
389           y  * (z1 * p[ID_V010] + z * p[ID_V011])) +
390     x  * (y1 * (z1 * p[ID_V100] + z * p[ID_V101])  +
391           y  * (z1 * p[ID_V110] + z * p[ID_V111]));
392   thePoint -=
393     x1 * (y1 * p[ID_E00z] + y * p[ID_E01z]) + 
394     x  * (y1 * p[ID_E10z] + y * p[ID_E11z]) + 
395     y1 * (z1 * p[ID_Ex00] + z * p[ID_Ex01]) + 
396     y  * (z1 * p[ID_Ex10] + z * p[ID_Ex11]) + 
397     z1 * (x1 * p[ID_E0y0] + x * p[ID_E1y0]) + 
398     z  * (x1 * p[ID_E0y1] + x * p[ID_E1y1]);
399
400   return true;
401 }
402
403 //=======================================================================
404 //function : Constructor
405 //purpose  : 
406 //=======================================================================
407
408 SMESH_Block::SMESH_Block():
409   myNbIterations(0),
410   mySumDist(0.),
411   myTolerance(-1.) // to be re-initialized
412 {
413 }
414
415 //=======================================================================
416 //function : ComputeParameters
417 //purpose  : compute point parameters in the block
418 //=======================================================================
419
420 bool SMESH_Block::ComputeParameters(const gp_Pnt& thePoint,
421                                     gp_XYZ&       theParams,
422                                     const int     theShapeID,
423                                     const gp_XYZ& theParamsHint)
424 {
425   if ( VertexParameters( theShapeID, theParams ))
426     return true;
427
428   if ( IsEdgeID( theShapeID )) {
429     TEdge& e = myEdge[ theShapeID - ID_FirstE ];
430     Adaptor3d_Curve* curve = e.GetCurve();
431     Extrema_ExtPC anExtPC( thePoint, *curve, curve->FirstParameter(), curve->LastParameter() );
432     int i, nb = anExtPC.IsDone() ? anExtPC.NbExt() : 0;
433     for ( i = 1; i <= nb; i++ ) {
434       if ( anExtPC.IsMin( i ))
435         return EdgeParameters( theShapeID, anExtPC.Point( i ).Parameter(), theParams );
436     }
437     return false;
438   }
439
440   const bool isOnFace = IsFaceID( theShapeID );
441   double * coef = GetShapeCoef( theShapeID );
442
443   // Find the first guess paremeters
444
445   gp_XYZ start(0, 0, 0);
446
447   bool hasHint = ( 0 <= theParamsHint.X() && theParamsHint.X() <= 1 &&
448                    0 <= theParamsHint.Y() && theParamsHint.Y() <= 1 &&
449                    0 <= theParamsHint.Y() && theParamsHint.Y() <= 1 );
450   if ( !hasHint && !myGridComputed )
451   {
452     // define the first guess by thePoint projection on lines
453     // connecting vertices
454     bool needGrid = false;
455     gp_XYZ par000( 0, 0, 0 ), par111( 1, 1, 1 );
456     double zero = DBL_MIN * DBL_MIN;
457     for ( int iEdge = 0, iParam = 1; iParam <= 3 && !needGrid; iParam++ )
458     {
459       if ( isOnFace && coef[ iParam - 1 ] != 0 ) {
460         iEdge += 4;
461         continue;
462       }
463       double sumParam = 0;
464       for ( int iE = 0; iE < 4; iE++, iEdge++ ) { // loop on 4 parallel edges
465         gp_Pnt p0 = myEdge[ iEdge ].Point( par000 );
466         gp_Pnt p1 = myEdge[ iEdge ].Point( par111 );
467         gp_Vec v01( p0, p1 ), v0P( p0, thePoint );
468         double len2 = v01.SquareMagnitude();
469         double par = 0;
470         if ( len2 > zero ) {
471           par = v0P.Dot( v01 ) / len2;
472           if ( par < 0 || par > 1 ) { // projection falls out of line ends => needGrid
473             needGrid = true;
474             break;
475           }
476         }
477         sumParam += par;
478       }
479       start.SetCoord( iParam, sumParam / 4.);
480     }
481     if ( needGrid ) {
482       // compute nodes of 3 x 3 x 3 grid
483       int iNode = 0;
484       Bnd_Box box;
485       for ( double x = 0.25; x < 0.9; x += 0.25 )
486         for ( double y = 0.25; y < 0.9; y += 0.25 )
487           for ( double z = 0.25; z < 0.9; z += 0.25 ) {
488             TxyzPair & prmPtn = my3x3x3GridNodes[ iNode++ ];
489             prmPtn.first.SetCoord( x, y, z );
490             ShellPoint( prmPtn.first, prmPtn.second );
491             box.Add( gp_Pnt( prmPtn.second ));
492           }
493       myGridComputed = true;
494       myTolerance = sqrt( box.SquareExtent() ) * 1e-5;
495     }
496   }
497
498   if ( hasHint )
499   {
500     start = theParamsHint;
501   }
502   else if ( myGridComputed )
503   {
504     double minDist = DBL_MAX;
505     gp_XYZ* bestParam = 0;
506     for ( int iNode = 0; iNode < 27; iNode++ ) {
507       TxyzPair & prmPtn = my3x3x3GridNodes[ iNode ];
508       double dist = ( thePoint.XYZ() - prmPtn.second ).SquareModulus();
509       if ( dist < minDist ) {
510         minDist = dist;
511         bestParam = & prmPtn.first;
512       }
513     }
514     start = *bestParam;
515   }
516
517   int    faceIndex = -1;
518   double faceParam = 0.;
519   if ( isOnFace ) {
520     // put a point on the face
521     for ( int iCoord = 0; iCoord < 3; iCoord++ )
522       if ( coef[ iCoord ] ) {
523         faceIndex = iCoord;
524         faceParam = ( coef[ faceIndex ] < 0.5 ) ? 0.0 : 1.0;
525         start.SetCoord( iCoord + 1, faceParam );
526       }
527   }
528
529 #ifdef DEBUG_PARAM_COMPUTE
530   cout << " #### POINT " <<thePoint.X()<<" "<<thePoint.Y()<<" "<<thePoint.Z()<<" ####"<< endl;
531 #endif
532
533   if ( myTolerance < 0 ) myTolerance = 1e-6;
534
535   const double parDelta = 1e-4;
536   const double sqTolerance = myTolerance * myTolerance;
537
538   gp_XYZ solution = start, params = start;
539   double sqDistance = 1e100; 
540   int nbLoops = 0;
541   while ( nbLoops <= 100 )
542   {
543     gp_XYZ P;
544     ShellPoint( params, P );
545
546     gp_Vec dP( thePoint, P );
547     double sqDist = dP.SquareMagnitude();
548 #ifdef DEBUG_PARAM_COMPUTE
549     cout << "PARAMS: ( " << params.X() <<" "<< params.Y() <<" "<< params.Z() <<" )"<< endl;
550     cout << "DIST: " << sqrt( sqDist ) << endl;
551 #endif
552     if ( sqDist > sqDistance ) { // solution get worse
553       break;
554     }
555     sqDistance = sqDist;
556     solution   = params;
557     if ( sqDist < sqTolerance ) { // a solution found
558       break;
559     }
560     // look for a better solution
561     for ( int iP = 1; iP <= 3; iP++ ) {
562       if ( iP - 1 == faceIndex )
563         continue;
564       // see where we move with a small (=parDelta) step in this direction
565       gp_XYZ nearParams = params;
566       bool onEdge = ( params.Coord( iP ) + parDelta > 1. );
567       if ( onEdge )
568         nearParams.SetCoord( iP, params.Coord( iP ) - parDelta );
569       else
570         nearParams.SetCoord( iP, params.Coord( iP ) + parDelta );
571       gp_XYZ Pi;
572       ShellPoint( nearParams, Pi );
573       gp_Vec dPi ( P, Pi );
574       if ( onEdge ) dPi *= -1.;
575       // modify a parameter
576       double mag = dPi.Magnitude();
577       if ( mag < DBL_MIN )
578         continue;
579       gp_Vec dir = dPi / mag; // dir we move modifying the parameter
580       double dist = dir * dP; // where we should get to
581       double dPar = dist / mag * parDelta; // predict parameter change
582       double curPar = params.Coord( iP );
583       double par = curPar - dPar; // new parameter value
584       while ( par > 1 || par < 0 ) {
585         dPar /= 2.;
586         par = curPar - dPar;
587       }
588       params.SetCoord( iP, par );
589     }
590
591     nbLoops++;
592   }
593 #ifdef DEBUG_PARAM_COMPUTE
594   myNbIterations += nbLoops*4; // how many times ShellPoint called
595   mySumDist += sqrt( sqDistance );
596   cout << " ------ SOLUTION: ( "<<solution.X()<<" "<<solution.Y()<<" "<<solution.Z()<<" )"<<endl
597        << " ------ DIST : " << sqrt( sqDistance ) << "\t Tol=" << myTolerance << "\t Nb LOOPS=" << nbLoops << endl
598        << " ------ NB IT: " << myNbIterations << ",  SUM DIST: " << mySumDist << endl;
599 #endif
600
601   theParams = solution;
602
603   if ( faceIndex >= 0 )
604     theParams.SetCoord( faceIndex + 1, faceParam );
605
606   return true;
607 }
608
609 //=======================================================================
610 //function : VertexParameters
611 //purpose  : return parameters of a vertex given by TShapeID
612 //=======================================================================
613
614 bool SMESH_Block::VertexParameters(const int theVertexID, gp_XYZ& theParams)
615 {
616   switch ( theVertexID ) {
617   case ID_V000: theParams.SetCoord(0., 0., 0.); return true;
618   case ID_V100: theParams.SetCoord(1., 0., 0.); return true;
619   case ID_V110: theParams.SetCoord(1., 1., 0.); return true;
620   case ID_V010: theParams.SetCoord(0., 1., 0.); return true;
621   default:;
622   }
623   return false;
624 }
625
626 //=======================================================================
627 //function : EdgeParameters
628 //purpose  : return parameters of a point given by theU on edge
629 //=======================================================================
630
631 bool SMESH_Block::EdgeParameters(const int theEdgeID, const double theU, gp_XYZ& theParams)
632 {
633   if ( IsEdgeID( theEdgeID )) {
634     vector< int > vertexVec;
635     GetEdgeVertexIDs( theEdgeID, vertexVec );
636     VertexParameters( vertexVec[0], theParams );
637     TEdge& e = myEdge[ theEdgeID - ID_Ex00 ];
638     double param = ( theU - e.EndParam(0) ) / ( e.EndParam(1) - e.EndParam(0) );
639     theParams.SetCoord( e.CoordInd(), param );
640     return true;
641   }
642   return false;
643 }
644
645 //=======================================================================
646 //function : DumpShapeID
647 //purpose  : debug an id of a block sub-shape
648 //=======================================================================
649
650 #define CASEDUMP(id,strm) case id: strm << #id; break;
651
652 ostream& SMESH_Block::DumpShapeID (const int id, ostream& stream)
653 {
654   switch ( id ) {
655   CASEDUMP( ID_V000, stream );
656   CASEDUMP( ID_V100, stream );
657   CASEDUMP( ID_V010, stream );
658   CASEDUMP( ID_V110, stream );
659   CASEDUMP( ID_V001, stream );
660   CASEDUMP( ID_V101, stream );
661   CASEDUMP( ID_V011, stream );
662   CASEDUMP( ID_V111, stream );
663   CASEDUMP( ID_Ex00, stream );
664   CASEDUMP( ID_Ex10, stream );
665   CASEDUMP( ID_Ex01, stream );
666   CASEDUMP( ID_Ex11, stream );
667   CASEDUMP( ID_E0y0, stream );
668   CASEDUMP( ID_E1y0, stream );
669   CASEDUMP( ID_E0y1, stream );
670   CASEDUMP( ID_E1y1, stream );
671   CASEDUMP( ID_E00z, stream );
672   CASEDUMP( ID_E10z, stream );
673   CASEDUMP( ID_E01z, stream );
674   CASEDUMP( ID_E11z, stream );
675   CASEDUMP( ID_Fxy0, stream );
676   CASEDUMP( ID_Fxy1, stream );
677   CASEDUMP( ID_Fx0z, stream );
678   CASEDUMP( ID_Fx1z, stream );
679   CASEDUMP( ID_F0yz, stream );
680   CASEDUMP( ID_F1yz, stream );
681   CASEDUMP( ID_Shell, stream );
682   default: stream << "ID_INVALID";
683   }
684   return stream;
685 }
686
687 //=======================================================================
688 //function : GetShapeIDByParams
689 //purpose  : define an id of the block sub-shape by normlized point coord
690 //=======================================================================
691
692 int SMESH_Block::GetShapeIDByParams ( const gp_XYZ& theCoord )
693 {
694   //   id ( 0 - 26 ) computation:
695
696   //   vertex     ( 0 - 7 )  : id = 1*x + 2*y + 4*z
697
698   //   edge || X  ( 8 - 11 ) : id = 8   + 1*y + 2*z
699   //   edge || Y  ( 12 - 15 ): id = 1*x + 12  + 2*z
700   //   edge || Z  ( 16 - 19 ): id = 1*x + 2*y + 16 
701
702   //   face || XY ( 20 - 21 ): id = 8   + 12  + 1*z - 0
703   //   face || XZ ( 22 - 23 ): id = 8   + 1*y + 16  - 2
704   //   face || YZ ( 24 - 25 ): id = 1*x + 12  + 16  - 4
705
706   static int iAddBnd[]    = { 1, 2, 4 };
707   static int iAddNotBnd[] = { 8, 12, 16 };
708   static int iFaceSubst[] = { 0, 2, 4 };
709
710   int id = 0;
711   int iOnBoundary = 0;
712   for ( int iCoord = 0; iCoord < 3; iCoord++ )
713   {
714     double val = theCoord.Coord( iCoord + 1 );
715     if ( val == 0.0 )
716       iOnBoundary++;
717     else if ( val == 1.0 )
718       id += iAddBnd[ iOnBoundary++ ];
719     else
720       id += iAddNotBnd[ iCoord ];
721   }
722   if ( iOnBoundary == 1 ) // face
723     id -= iFaceSubst[ (id - 20) / 4 ];
724   else if ( iOnBoundary == 0 ) // shell
725     id = 26;
726
727   if ( id > 26 || id < 0 ) {
728     MESSAGE( "GetShapeIDByParams() = " << id
729             <<" "<< theCoord.X() <<" "<< theCoord.Y() <<" "<< theCoord.Z() );
730   }
731
732   return id + 1; // shape ids start at 1
733 }
734
735 //=======================================================================
736 //function : GetOrderedEdges
737 //purpose  : return nb wires and a list of oredered edges
738 //=======================================================================
739
740 int SMESH_Block::GetOrderedEdges (const TopoDS_Face&   theFace,
741                                   TopoDS_Vertex        theFirstVertex,
742                                   list< TopoDS_Edge >& theEdges,
743                                   list< int >  &       theNbVertexInWires)
744 {
745   // put wires in a list, so that an outer wire comes first
746   list<TopoDS_Wire> aWireList;
747   TopoDS_Wire anOuterWire = BRepTools::OuterWire( theFace );
748   aWireList.push_back( anOuterWire );
749   for ( TopoDS_Iterator wIt (theFace); wIt.More(); wIt.Next() )
750     if ( !anOuterWire.IsSame( wIt.Value() ))
751       aWireList.push_back( TopoDS::Wire( wIt.Value() ));
752
753   // loop on edges of wires
754   theNbVertexInWires.clear();
755   list<TopoDS_Wire>::iterator wlIt = aWireList.begin();
756   for ( ; wlIt != aWireList.end(); wlIt++ )
757   {
758     int iE;
759     BRepTools_WireExplorer wExp( *wlIt, theFace );
760     for ( iE = 0; wExp.More(); wExp.Next(), iE++ )
761     {
762       TopoDS_Edge edge = wExp.Current();
763       edge = TopoDS::Edge( edge.Oriented( wExp.Orientation() ));
764       theEdges.push_back( edge );
765     }
766     theNbVertexInWires.push_back( iE );
767     iE = 0;
768     if ( wlIt == aWireList.begin() && theEdges.size() > 1 ) { // the outer wire
769       // orient closed edges
770       list< TopoDS_Edge >::iterator eIt, eIt2;
771       for ( eIt = theEdges.begin(); eIt != theEdges.end(); eIt++ )
772       {
773         TopoDS_Edge& edge = *eIt;
774         if ( TopExp::FirstVertex( edge ).IsSame( TopExp::LastVertex( edge ) ))
775         {
776           eIt2 = eIt;
777           bool isNext = ( eIt2 == theEdges.begin() );
778           TopoDS_Edge edge2 = isNext ? *(++eIt2) : *(--eIt2);
779           double f1,l1,f2,l2;
780           Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( edge, theFace, f1,l1 );
781           Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( edge2, theFace, f2,l2 );
782           gp_Pnt2d pf = c1->Value( edge.Orientation() == TopAbs_FORWARD ? f1 : l1 );
783           gp_Pnt2d pl = c1->Value( edge.Orientation() == TopAbs_FORWARD ? l1 : f1 );
784           bool isFirst = ( edge2.Orientation() == TopAbs_FORWARD ? isNext : !isNext );
785           gp_Pnt2d p2 = c2->Value( isFirst ? f2 : l2 );
786           isFirst = ( p2.SquareDistance( pf ) < p2.SquareDistance( pl ));
787           if ( isNext ? isFirst : !isFirst )
788             edge.Reverse();
789           // to make a seam go first
790           if ( theFirstVertex.IsNull() )
791             theFirstVertex = TopExp::FirstVertex( edge, true );
792         }
793       }
794       // rotate theEdges until it begins from theFirstVertex
795       if ( ! theFirstVertex.IsNull() ) {
796         TopoDS_Vertex vv[2];
797         TopExp::Vertices( theEdges.front(), vv[0], vv[1], true );
798         // on closed face, make seam edge the first in the list
799         while ( !vv[0].IsSame( theFirstVertex ) || vv[0].IsSame( vv[1] ))
800         {
801           theEdges.splice(theEdges.end(), theEdges,
802                           theEdges.begin(), ++theEdges.begin());
803           TopExp::Vertices( theEdges.front(), vv[0], vv[1], true );
804           if ( iE++ > theNbVertexInWires.back() ) {
805 #ifdef _DEBUG_
806             gp_Pnt p = BRep_Tool::Pnt( theFirstVertex );
807             cout << " : Warning : vertex "<< theFirstVertex.TShape().operator->()
808                  << " ( " << p.X() << " " << p.Y() << " " << p.Z() << " )" 
809                  << " not found in outer wire of face "<< theFace.TShape().operator->()
810                  << " with vertices: " <<  endl;
811             wExp.Init( *wlIt, theFace );
812             for ( int i = 0; wExp.More(); wExp.Next(), i++ )
813             {
814               TopoDS_Edge edge = wExp.Current();
815               edge = TopoDS::Edge( edge.Oriented( wExp.Orientation() ));
816               TopoDS_Vertex v = TopExp::FirstVertex( edge, true );
817               gp_Pnt p = BRep_Tool::Pnt( v );
818               cout << i << " " << v.TShape().operator->() << " "
819                    << p.X() << " " << p.Y() << " " << p.Z() << " " << endl;
820             }
821 #endif
822             break; // break infinite loop
823           }
824         }
825       }
826     } // end outer wire
827   }
828
829   return aWireList.size();
830 }
831 //================================================================================
832 /*!
833  * \brief Call it after geometry initialisation
834  */
835 //================================================================================
836
837 void SMESH_Block::init()
838 {
839   myNbIterations = 0;
840   mySumDist = 0;
841   myGridComputed = false;
842 }
843
844 //=======================================================================
845 //function : LoadMeshBlock
846 //purpose  : prepare to work with theVolume
847 //=======================================================================
848
849 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
850
851 bool SMESH_Block::LoadMeshBlock(const SMDS_MeshVolume*        theVolume,
852                                 const int                     theNode000Index,
853                                 const int                     theNode001Index,
854                                 vector<const SMDS_MeshNode*>& theOrderedNodes)
855 {
856   MESSAGE(" ::LoadMeshBlock()");
857   init();
858
859   SMDS_VolumeTool vTool;
860   if (!vTool.Set( theVolume ) || vTool.NbNodes() != 8 ||
861       !vTool.IsLinked( theNode000Index, theNode001Index )) {
862     MESSAGE(" Bad arguments ");
863     return false;
864   }
865   vTool.SetExternalNormal();
866   // In terms of indices used for access to nodes and faces in SMDS_VolumeTool:
867   int V000, V100, V010, V110, V001, V101, V011, V111; // 8 vertices
868   int Fxy0, Fxy1; // bottom and top faces
869   // vertices of faces
870   vector<int> vFxy0, vFxy1;
871
872   V000 = theNode000Index;
873   V001 = theNode001Index;
874
875   // get faces sharing V000 and V001
876   list<int> fV000, fV001;
877   int i, iF, iE, iN;
878   for ( iF = 0; iF < vTool.NbFaces(); ++iF ) {
879     const int* nid = vTool.GetFaceNodesIndices( iF );
880     for ( iN = 0; iN < 4; ++iN )
881       if ( nid[ iN ] == V000 ) {
882         fV000.push_back( iF );
883       } else if ( nid[ iN ] == V001 ) {
884         fV001.push_back( iF );
885       }
886   }
887
888   // find the bottom (Fxy0), the top (Fxy1) faces
889   list<int>::iterator fIt1, fIt2, Fxy0Pos;
890   for ( fIt1 = fV000.begin(); fIt1 != fV000.end(); fIt1++) {
891     fIt2 = std::find( fV001.begin(), fV001.end(), *fIt1 );
892     if ( fIt2 != fV001.end() ) { // *fIt1 is in the both lists
893       fV001.erase( fIt2 ); // erase Fx0z or F0yz from fV001
894     } else { // *fIt1 is in fV000 only
895       Fxy0Pos = fIt1; // points to Fxy0
896     }
897   }
898   Fxy0 = *Fxy0Pos;
899   Fxy1 = fV001.front();
900   const SMDS_MeshNode** nn = vTool.GetNodes();
901
902   // find bottom veritices, their order is that a face normal is external
903   vFxy0.resize(4);
904   const int* nid = vTool.GetFaceNodesIndices( Fxy0 );
905   for ( i = 0; i < 4; ++i )
906     if ( nid[ i ] == V000 )
907       break;
908   for ( iN = 0; iN < 4; ++iN, ++i ) {
909     if ( i == 4 ) i = 0;
910     vFxy0[ iN ] = nid[ i ];
911   }
912   // find top veritices, their order is that a face normal is external
913   vFxy1.resize(4);
914   nid = vTool.GetFaceNodesIndices( Fxy1 );
915   for ( i = 0; i < 4; ++i )
916     if ( nid[ i ] == V001 )
917       break;
918   for ( iN = 0; iN < 4; ++iN, ++i ) {
919     if ( i == 4 ) i = 0;
920     vFxy1[ iN ] = nid[ i ];
921   }
922   // find indices of the rest veritices 
923   V100 = vFxy0[3];
924   V010 = vFxy0[1];
925   V110 = vFxy0[2];
926   V101 = vFxy1[1];
927   V011 = vFxy1[3];
928   V111 = vFxy1[2];
929
930   // set points coordinates
931   myPnt[ ID_V000 - 1 ] = gpXYZ( nn[ V000 ] );
932   myPnt[ ID_V100 - 1 ] = gpXYZ( nn[ V100 ] );
933   myPnt[ ID_V010 - 1 ] = gpXYZ( nn[ V010 ] );
934   myPnt[ ID_V110 - 1 ] = gpXYZ( nn[ V110 ] );
935   myPnt[ ID_V001 - 1 ] = gpXYZ( nn[ V001 ] );
936   myPnt[ ID_V101 - 1 ] = gpXYZ( nn[ V101 ] );
937   myPnt[ ID_V011 - 1 ] = gpXYZ( nn[ V011 ] );
938   myPnt[ ID_V111 - 1 ] = gpXYZ( nn[ V111 ] );
939
940   // fill theOrderedNodes
941   theOrderedNodes.resize( 8 );
942   theOrderedNodes[ 0 ] = nn[ V000 ];
943   theOrderedNodes[ 1 ] = nn[ V100 ];
944   theOrderedNodes[ 2 ] = nn[ V010 ];
945   theOrderedNodes[ 3 ] = nn[ V110 ];
946   theOrderedNodes[ 4 ] = nn[ V001 ];
947   theOrderedNodes[ 5 ] = nn[ V101 ];
948   theOrderedNodes[ 6 ] = nn[ V011 ];
949   theOrderedNodes[ 7 ] = nn[ V111 ];
950   
951   // fill edges
952   vector< int > vertexVec;
953   for ( iE = 0; iE < NbEdges(); ++iE ) {
954     GetEdgeVertexIDs(( iE + ID_FirstE ), vertexVec );
955     myEdge[ iE ].Set(( iE + ID_FirstE ),
956                      myPnt[ vertexVec[0] - 1 ],
957                      myPnt[ vertexVec[1] - 1 ]);
958   }
959
960   // fill faces' corners
961   for ( iF = ID_Fxy0; iF < ID_Shell; ++iF )
962   {
963     TFace& tFace = myFace[ iF - ID_FirstF ];
964     vector< int > edgeIdVec(4, -1);
965     GetFaceEdgesIDs( iF, edgeIdVec );
966     tFace.Set( iF, myEdge[ edgeIdVec [ 0 ] - ID_Ex00], myEdge[ edgeIdVec [ 1 ] - ID_Ex00]);
967   }
968
969   return true;
970 }
971
972 //=======================================================================
973 //function : LoadBlockShapes
974 //purpose  : Initialize block geometry with theShell,
975 //           add sub-shapes of theBlock to theShapeIDMap so that they get
976 //           IDs acoording to enum TShapeID
977 //=======================================================================
978
979 bool SMESH_Block::LoadBlockShapes(const TopoDS_Shell&         theShell,
980                                   const TopoDS_Vertex&        theVertex000,
981                                   const TopoDS_Vertex&        theVertex001,
982                                   TopTools_IndexedMapOfOrientedShape& theShapeIDMap )
983 {
984   MESSAGE(" ::LoadBlockShapes()");
985   return ( FindBlockShapes( theShell, theVertex000, theVertex001, theShapeIDMap ) &&
986            LoadBlockShapes( theShapeIDMap ));
987 }
988
989 //=======================================================================
990 //function : LoadBlockShapes
991 //purpose  : add sub-shapes of theBlock to theShapeIDMap so that they get
992 //           IDs acoording to enum TShapeID
993 //=======================================================================
994
995 bool SMESH_Block::FindBlockShapes(const TopoDS_Shell&         theShell,
996                                   const TopoDS_Vertex&        theVertex000,
997                                   const TopoDS_Vertex&        theVertex001,
998                                   TopTools_IndexedMapOfOrientedShape& theShapeIDMap )
999 {
1000   MESSAGE(" ::FindBlockShapes()");
1001
1002   // 8 vertices
1003   TopoDS_Shape V000, V100, V010, V110, V001, V101, V011, V111;
1004   // 12 edges
1005   TopoDS_Shape Ex00, Ex10, Ex01, Ex11;
1006   TopoDS_Shape E0y0, E1y0, E0y1, E1y1;
1007   TopoDS_Shape E00z, E10z, E01z, E11z;
1008   // 6 faces
1009   TopoDS_Shape Fxy0, Fx0z, F0yz, Fxy1, Fx1z, F1yz;
1010
1011   // nb of faces bound to a vertex in TopTools_IndexedDataMapOfShapeListOfShape
1012   // filled by TopExp::MapShapesAndAncestors()
1013   const int NB_FACES_BY_VERTEX = 6;
1014
1015   TopTools_IndexedDataMapOfShapeListOfShape vfMap;
1016   TopExp::MapShapesAndAncestors( theShell, TopAbs_VERTEX, TopAbs_FACE, vfMap );
1017   if ( vfMap.Extent() != 8 ) {
1018     MESSAGE(" Wrong nb of vertices in the block: " << vfMap.Extent() );
1019     return false;
1020   }
1021
1022   V000 = theVertex000;
1023   V001 = theVertex001;
1024
1025   if ( V000.IsNull() ) {
1026     // find vertex 000 - the one with smallest coordinates
1027     double minVal = DBL_MAX, minX, val;
1028     for ( int i = 1; i <= 8; i++ ) {
1029       const TopoDS_Vertex& v = TopoDS::Vertex( vfMap.FindKey( i ));
1030       gp_Pnt P = BRep_Tool::Pnt( v );
1031       val = P.X() + P.Y() + P.Z();
1032       if ( val < minVal || ( val == minVal && P.X() < minX )) {
1033         V000 = v;
1034         minVal = val;
1035         minX = P.X();
1036       }
1037     }
1038     // find vertex 001 - the one on the most vertical edge passing through V000
1039     TopTools_IndexedDataMapOfShapeListOfShape veMap;
1040     TopExp::MapShapesAndAncestors( theShell, TopAbs_VERTEX, TopAbs_EDGE, veMap );
1041     gp_Vec dir001 = gp::DZ();
1042     gp_Pnt p000 = BRep_Tool::Pnt( TopoDS::Vertex( V000 ));
1043     double maxVal = -DBL_MAX;
1044     TopTools_ListIteratorOfListOfShape eIt ( veMap.FindFromKey( V000 ));
1045     for (  ; eIt.More(); eIt.Next() ) {
1046       const TopoDS_Edge& e = TopoDS::Edge( eIt.Value() );
1047       TopoDS_Vertex v = TopExp::FirstVertex( e );
1048       if ( v.IsSame( V000 ))
1049         v = TopExp::LastVertex( e );
1050       val = dir001 * gp_Vec( p000, BRep_Tool::Pnt( v )).Normalized();
1051       if ( val > maxVal ) {
1052         V001 = v;
1053         maxVal = val;
1054       }
1055     }
1056   }
1057
1058   // find the bottom (Fxy0), Fx0z and F0yz faces
1059
1060   const TopTools_ListOfShape& f000List = vfMap.FindFromKey( V000 );
1061   const TopTools_ListOfShape& f001List = vfMap.FindFromKey( V001 );
1062   if (f000List.Extent() != NB_FACES_BY_VERTEX ||
1063       f001List.Extent() != NB_FACES_BY_VERTEX ) {
1064     MESSAGE(" LoadBlockShapes() " << f000List.Extent() << " " << f001List.Extent());
1065     return false;
1066   }
1067   TopTools_ListIteratorOfListOfShape f001It, f000It ( f000List );
1068   int i, j, iFound1, iFound2;
1069   for ( j = 0; f000It.More(); f000It.Next(), j++ )
1070   {
1071     if ( NB_FACES_BY_VERTEX == 6 && j % 2 ) continue; // each face encounters twice
1072     const TopoDS_Shape& F = f000It.Value();
1073     for ( i = 0, f001It.Initialize( f001List ); f001It.More(); f001It.Next(), i++ ) {
1074       if ( NB_FACES_BY_VERTEX == 6 && i % 2 ) continue; // each face encounters twice
1075       if ( F.IsSame( f001It.Value() ))
1076         break;
1077     }
1078     if ( f001It.More() ) // Fx0z or F0yz found
1079       if ( Fx0z.IsNull() ) {
1080         Fx0z = F;
1081         iFound1 = i;
1082       } else {
1083         F0yz = F;
1084         iFound2 = i;
1085       }
1086     else // F is the bottom face
1087       Fxy0 = F;
1088   }
1089   if ( Fxy0.IsNull() || Fx0z.IsNull() || F0yz.IsNull() ) {
1090     MESSAGE( Fxy0.IsNull() <<" "<< Fx0z.IsNull() <<" "<< F0yz.IsNull() );
1091     return false;
1092   }
1093
1094   // choose the top face (Fxy1)
1095   for ( i = 0, f001It.Initialize( f001List ); f001It.More(); f001It.Next(), i++ ) {
1096     if ( NB_FACES_BY_VERTEX == 6 && i % 2 ) continue; // each face encounters twice
1097     if ( i != iFound1 && i != iFound2 )
1098       break;
1099   }
1100   Fxy1 = f001It.Value();
1101   if ( Fxy1.IsNull() ) {
1102     MESSAGE(" LoadBlockShapes() error ");
1103     return false;
1104   }
1105
1106   // find bottom edges and veritices
1107   list< TopoDS_Edge > eList;
1108   list< int >         nbVertexInWires;
1109   GetOrderedEdges( TopoDS::Face( Fxy0 ), TopoDS::Vertex( V000 ), eList, nbVertexInWires );
1110   if ( nbVertexInWires.size() != 1 || nbVertexInWires.front() != 4 ) {
1111     MESSAGE(" LoadBlockShapes() error ");
1112     return false;
1113   }
1114   list< TopoDS_Edge >::iterator elIt = eList.begin();
1115   for ( i = 0; elIt != eList.end(); elIt++, i++ )
1116     switch ( i ) {
1117     case 0: E0y0 = *elIt; V010 = TopExp::LastVertex( *elIt, true ); break;
1118     case 1: Ex10 = *elIt; V110 = TopExp::LastVertex( *elIt, true ); break;
1119     case 2: E1y0 = *elIt; V100 = TopExp::LastVertex( *elIt, true ); break;
1120     case 3: Ex00 = *elIt; break;
1121     default:;
1122     }
1123   if ( i != 4 || E0y0.IsNull() || Ex10.IsNull() || E1y0.IsNull() || Ex00.IsNull() ) {
1124     MESSAGE(" LoadBlockShapes() error, eList.size()=" << eList.size());
1125     return false;
1126   }
1127
1128
1129   // find top edges and veritices
1130   eList.clear();
1131   GetOrderedEdges( TopoDS::Face( Fxy1 ), TopoDS::Vertex( V001 ), eList, nbVertexInWires );
1132   if ( nbVertexInWires.size() != 1 || nbVertexInWires.front() != 4 ) {
1133     MESSAGE(" LoadBlockShapes() error ");
1134     return false;
1135   }
1136   for ( i = 0, elIt = eList.begin(); elIt != eList.end(); elIt++, i++ )
1137     switch ( i ) {
1138     case 0: Ex01 = *elIt; V101 = TopExp::LastVertex( *elIt, true ); break;
1139     case 1: E1y1 = *elIt; V111 = TopExp::LastVertex( *elIt, true ); break;
1140     case 2: Ex11 = *elIt; V011 = TopExp::LastVertex( *elIt, true ); break;
1141     case 3: E0y1 = *elIt; break;
1142     default:;
1143     }
1144   if ( i != 4 || Ex01.IsNull() || E1y1.IsNull() || Ex11.IsNull() || E0y1.IsNull() ) {
1145     MESSAGE(" LoadBlockShapes() error, eList.size()=" << eList.size());
1146     return false;
1147   }
1148
1149   // swap Fx0z and F0yz if necessary
1150   TopExp_Explorer exp( Fx0z, TopAbs_VERTEX );
1151   for ( ; exp.More(); exp.Next() ) // Fx0z shares V101 and V100
1152     if ( V101.IsSame( exp.Current() ) || V100.IsSame( exp.Current() ))
1153       break; // V101 or V100 found
1154   if ( !exp.More() ) { // not found
1155     std::swap( Fx0z, F0yz);
1156   }
1157
1158   // find Fx1z and F1yz faces
1159   const TopTools_ListOfShape& f111List = vfMap.FindFromKey( V111 );
1160   const TopTools_ListOfShape& f110List = vfMap.FindFromKey( V110 );
1161   if (f111List.Extent() != NB_FACES_BY_VERTEX ||
1162       f110List.Extent() != NB_FACES_BY_VERTEX ) {
1163     MESSAGE(" LoadBlockShapes() " << f111List.Extent() << " " << f110List.Extent());
1164     return false;
1165   }
1166   TopTools_ListIteratorOfListOfShape f111It, f110It ( f110List);
1167   for ( j = 0 ; f110It.More(); f110It.Next(), j++ ) {
1168     if ( NB_FACES_BY_VERTEX == 6 && j % 2 ) continue; // each face encounters twice
1169     const TopoDS_Shape& F = f110It.Value();
1170     for ( i = 0, f111It.Initialize( f111List ); f111It.More(); f111It.Next(), i++ ) {
1171       if ( NB_FACES_BY_VERTEX == 6 && i % 2 ) continue; // each face encounters twice
1172       if ( F.IsSame( f111It.Value() )) { // Fx1z or F1yz found
1173         if ( Fx1z.IsNull() )
1174           Fx1z = F;
1175         else
1176           F1yz = F;
1177       }
1178     }
1179   }
1180   if ( Fx1z.IsNull() || F1yz.IsNull() ) {
1181     MESSAGE(" LoadBlockShapes() error ");
1182     return false;
1183   }
1184
1185   // swap Fx1z and F1yz if necessary
1186   for ( exp.Init( Fx1z, TopAbs_VERTEX ); exp.More(); exp.Next() )
1187     if ( V010.IsSame( exp.Current() ) || V011.IsSame( exp.Current() ))
1188       break;
1189   if ( !exp.More() ) {
1190     std::swap( Fx1z, F1yz);
1191   }
1192
1193   // find vertical edges
1194   for ( exp.Init( Fx0z, TopAbs_EDGE ); exp.More(); exp.Next() ) {
1195     const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
1196     const TopoDS_Shape& vFirst = TopExp::FirstVertex( edge, true );
1197     if ( vFirst.IsSame( V001 ))
1198       E00z = edge;
1199     else if ( vFirst.IsSame( V100 ))
1200       E10z = edge;
1201   }
1202   if ( E00z.IsNull() || E10z.IsNull() ) {
1203     MESSAGE(" LoadBlockShapes() error ");
1204     return false;
1205   }
1206   for ( exp.Init( Fx1z, TopAbs_EDGE ); exp.More(); exp.Next() ) {
1207     const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
1208     const TopoDS_Shape& vFirst = TopExp::FirstVertex( edge, true );
1209     if ( vFirst.IsSame( V111 ))
1210       E11z = edge;
1211     else if ( vFirst.IsSame( V010 ))
1212       E01z = edge;
1213   }
1214   if ( E01z.IsNull() || E11z.IsNull() ) {
1215     MESSAGE(" LoadBlockShapes() error ");
1216     return false;
1217   }
1218
1219   // load shapes in theShapeIDMap
1220
1221   theShapeIDMap.Clear();
1222   
1223   theShapeIDMap.Add(V000.Oriented( TopAbs_FORWARD ));
1224   theShapeIDMap.Add(V100.Oriented( TopAbs_FORWARD ));
1225   theShapeIDMap.Add(V010.Oriented( TopAbs_FORWARD ));
1226   theShapeIDMap.Add(V110.Oriented( TopAbs_FORWARD ));
1227   theShapeIDMap.Add(V001.Oriented( TopAbs_FORWARD ));
1228   theShapeIDMap.Add(V101.Oriented( TopAbs_FORWARD ));
1229   theShapeIDMap.Add(V011.Oriented( TopAbs_FORWARD ));
1230   theShapeIDMap.Add(V111.Oriented( TopAbs_FORWARD ));
1231
1232   theShapeIDMap.Add(Ex00);
1233   theShapeIDMap.Add(Ex10);
1234   theShapeIDMap.Add(Ex01);
1235   theShapeIDMap.Add(Ex11);
1236
1237   theShapeIDMap.Add(E0y0);
1238   theShapeIDMap.Add(E1y0);
1239   theShapeIDMap.Add(E0y1);
1240   theShapeIDMap.Add(E1y1);
1241
1242   theShapeIDMap.Add(E00z);
1243   theShapeIDMap.Add(E10z);
1244   theShapeIDMap.Add(E01z);
1245   theShapeIDMap.Add(E11z);
1246
1247   theShapeIDMap.Add(Fxy0);
1248   theShapeIDMap.Add(Fxy1);
1249   theShapeIDMap.Add(Fx0z);
1250   theShapeIDMap.Add(Fx1z);
1251   theShapeIDMap.Add(F0yz);
1252   theShapeIDMap.Add(F1yz);
1253   
1254   theShapeIDMap.Add(theShell);
1255
1256   return true;
1257 }
1258
1259 //================================================================================
1260 /*!
1261  * \brief Initialize block geometry with shapes from theShapeIDMap
1262   * \param theShapeIDMap - map of block subshapes
1263   * \retval bool - is a success
1264  */
1265 //================================================================================
1266
1267 bool SMESH_Block::LoadBlockShapes(const TopTools_IndexedMapOfOrientedShape& theShapeIDMap)
1268 {
1269   init();
1270
1271   // store shapes geometry
1272   for ( int shapeID = 1; shapeID < theShapeIDMap.Extent(); shapeID++ )
1273   {
1274     const TopoDS_Shape& S = theShapeIDMap( shapeID );
1275     switch ( S.ShapeType() )
1276     {
1277     case TopAbs_VERTEX: {
1278
1279       if ( !IsVertexID( ID_V111 )) return false;
1280       myPnt[ shapeID - ID_V000 ] = BRep_Tool::Pnt( TopoDS::Vertex( S )).XYZ();
1281       break;
1282     }
1283     case TopAbs_EDGE: {
1284
1285       if ( !IsEdgeID( shapeID )) return false;
1286       const TopoDS_Edge& edge = TopoDS::Edge( S );
1287       TEdge& tEdge = myEdge[ shapeID - ID_FirstE ];
1288       tEdge.Set( shapeID,
1289                  new BRepAdaptor_Curve( edge ),
1290                  IsForwardEdge( edge, theShapeIDMap ));
1291       break;
1292     }
1293     case TopAbs_FACE: {
1294
1295       if ( !LoadFace( TopoDS::Face( S ), shapeID, theShapeIDMap ))
1296         return false;
1297       break;
1298     }
1299     default: break;
1300     }
1301   } // loop on shapes in theShapeIDMap
1302
1303   return true;
1304 }
1305
1306 //================================================================================
1307 /*!
1308  * \brief Load face geometry
1309   * \param theFace - face
1310   * \param theFaceID - face in-block ID
1311   * \param theShapeIDMap - map of block subshapes
1312   * \retval bool - is a success
1313  * 
1314  * It is enough to compute params or coordinates on the face.
1315  * Face subshapes must be loaded into theShapeIDMap before
1316  */
1317 //================================================================================
1318
1319 bool SMESH_Block::LoadFace(const TopoDS_Face& theFace,
1320                            const int          theFaceID,
1321                            const TopTools_IndexedMapOfOrientedShape& theShapeIDMap)
1322 {
1323   if ( !IsFaceID( theFaceID ) ) return false;
1324   // pcurves
1325   Adaptor2d_Curve2d* c2d[4];
1326   bool isForward[4];
1327   vector< int > edgeIdVec;
1328   GetFaceEdgesIDs( theFaceID, edgeIdVec );
1329   for ( int iE = 0; iE < edgeIdVec.size(); iE++ ) // loop on 4 edges
1330   {
1331     if ( edgeIdVec[ iE ] > theShapeIDMap.Extent() )
1332       return false;
1333     const TopoDS_Edge& edge = TopoDS::Edge( theShapeIDMap( edgeIdVec[ iE ]));
1334     c2d[ iE ] = new BRepAdaptor_Curve2d( edge, theFace );
1335     isForward[ iE ] = IsForwardEdge( edge, theShapeIDMap );
1336   }
1337   TFace& tFace = myFace[ theFaceID - ID_FirstF ];
1338   tFace.Set( theFaceID, new BRepAdaptor_Surface( theFace ), c2d, isForward );
1339   return true;
1340 }
1341
1342 //================================================================================
1343 /*!
1344  * \brief/ Insert theShape into theShapeIDMap with theShapeID
1345   * \param theShape - shape to insert
1346   * \param theShapeID - shape in-block ID
1347   * \param theShapeIDMap - map of block subshapes
1348  */
1349 //================================================================================
1350
1351 bool SMESH_Block::Insert(const TopoDS_Shape& theShape,
1352                          const int           theShapeID,
1353                          TopTools_IndexedMapOfOrientedShape& theShapeIDMap)
1354 {
1355   if ( !theShape.IsNull() && theShapeID > 0 )
1356   {
1357     if ( theShapeIDMap.Contains( theShape ))
1358       return ( theShapeIDMap.FindIndex( theShape ) == theShapeID );
1359
1360     if ( theShapeID <= theShapeIDMap.Extent() ) {
1361         theShapeIDMap.Substitute( theShapeID, theShape );
1362     }
1363     else {
1364       while ( theShapeIDMap.Extent() < theShapeID - 1 ) {
1365         TopoDS_Compound comp;
1366         BRep_Builder().MakeCompound( comp );
1367         theShapeIDMap.Add( comp );
1368       }
1369       theShapeIDMap.Add( theShape );
1370     }
1371     return true;
1372   }
1373   return false;
1374 }
1375
1376 //=======================================================================
1377 //function : GetFaceEdgesIDs
1378 //purpose  : return edges IDs in the order u0, u1, 0v, 1v
1379 //           u0 means "|| u, v == 0"
1380 //=======================================================================
1381
1382 void SMESH_Block::GetFaceEdgesIDs (const int faceID, vector< int >& edgeVec )
1383 {
1384   edgeVec.resize( 4 );
1385   switch ( faceID ) {
1386   case ID_Fxy0:
1387     edgeVec[ 0 ] = ID_Ex00;
1388     edgeVec[ 1 ] = ID_Ex10;
1389     edgeVec[ 2 ] = ID_E0y0;
1390     edgeVec[ 3 ] = ID_E1y0;
1391     break;
1392   case ID_Fxy1:
1393     edgeVec[ 0 ] = ID_Ex01;
1394     edgeVec[ 1 ] = ID_Ex11;
1395     edgeVec[ 2 ] = ID_E0y1;
1396     edgeVec[ 3 ] = ID_E1y1;
1397     break;
1398   case ID_Fx0z:
1399     edgeVec[ 0 ] = ID_Ex00;
1400     edgeVec[ 1 ] = ID_Ex01;
1401     edgeVec[ 2 ] = ID_E00z;
1402     edgeVec[ 3 ] = ID_E10z;
1403     break;
1404   case ID_Fx1z:
1405     edgeVec[ 0 ] = ID_Ex10;
1406     edgeVec[ 1 ] = ID_Ex11;
1407     edgeVec[ 2 ] = ID_E01z;
1408     edgeVec[ 3 ] = ID_E11z;
1409     break;
1410   case ID_F0yz:
1411     edgeVec[ 0 ] = ID_E0y0;
1412     edgeVec[ 1 ] = ID_E0y1;
1413     edgeVec[ 2 ] = ID_E00z;
1414     edgeVec[ 3 ] = ID_E01z;
1415     break;
1416   case ID_F1yz:
1417     edgeVec[ 0 ] = ID_E1y0;
1418     edgeVec[ 1 ] = ID_E1y1;
1419     edgeVec[ 2 ] = ID_E10z;
1420     edgeVec[ 3 ] = ID_E11z;
1421     break;
1422   default:
1423     MESSAGE(" GetFaceEdgesIDs(), wrong face ID: " << faceID );
1424   }
1425 }
1426
1427 //=======================================================================
1428 //function : GetEdgeVertexIDs
1429 //purpose  : return vertex IDs of an edge
1430 //=======================================================================
1431
1432 void SMESH_Block::GetEdgeVertexIDs (const int edgeID, vector< int >& vertexVec )
1433 {
1434   vertexVec.resize( 2 );
1435   switch ( edgeID ) {
1436
1437   case ID_Ex00:
1438     vertexVec[ 0 ] = ID_V000;
1439     vertexVec[ 1 ] = ID_V100;
1440     break;
1441   case ID_Ex10:
1442     vertexVec[ 0 ] = ID_V010;
1443     vertexVec[ 1 ] = ID_V110;
1444     break;
1445   case ID_Ex01:
1446     vertexVec[ 0 ] = ID_V001;
1447     vertexVec[ 1 ] = ID_V101;
1448     break;
1449   case ID_Ex11:
1450     vertexVec[ 0 ] = ID_V011;
1451     vertexVec[ 1 ] = ID_V111;
1452     break;
1453
1454   case ID_E0y0:
1455     vertexVec[ 0 ] = ID_V000;
1456     vertexVec[ 1 ] = ID_V010;
1457     break;
1458   case ID_E1y0:
1459     vertexVec[ 0 ] = ID_V100;
1460     vertexVec[ 1 ] = ID_V110;
1461     break;
1462   case ID_E0y1:
1463     vertexVec[ 0 ] = ID_V001;
1464     vertexVec[ 1 ] = ID_V011;
1465     break;
1466   case ID_E1y1:
1467     vertexVec[ 0 ] = ID_V101;
1468     vertexVec[ 1 ] = ID_V111;
1469     break;
1470
1471   case ID_E00z:
1472     vertexVec[ 0 ] = ID_V000;
1473     vertexVec[ 1 ] = ID_V001;
1474     break;
1475   case ID_E10z:
1476     vertexVec[ 0 ] = ID_V100;
1477     vertexVec[ 1 ] = ID_V101;
1478     break;
1479   case ID_E01z:
1480     vertexVec[ 0 ] = ID_V010;
1481     vertexVec[ 1 ] = ID_V011;
1482     break;
1483   case ID_E11z:
1484     vertexVec[ 0 ] = ID_V110;
1485     vertexVec[ 1 ] = ID_V111;
1486     break;
1487   default:
1488     vertexVec.resize(0);
1489     MESSAGE(" GetEdgeVertexIDs(), wrong edge ID: " << edgeID );
1490   }
1491 }
1492