Salome HOME
Fix compilation on Debian
[modules/smesh.git] / src / StdMeshers / StdMeshers_CompositeHexa_3D.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 //  SMESH SMESH : implementaion of SMESH idl descriptions
21 // File      : StdMeshers_CompositeHexa_3D.cxx
22 // Module    : SMESH
23 // Created   : Tue Nov 25 11:04:59 2008
24 // Author    : Edward AGAPOV (eap)
25
26 #include "StdMeshers_CompositeHexa_3D.hxx"
27
28 #include "SMDS_Mesh.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESH_Block.hxx"
32 #include "SMESH_Comment.hxx"
33 #include "SMESH_ComputeError.hxx"
34 #include "SMESH_Mesh.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_subMesh.hxx"
37
38 #include <BRepAdaptor_Surface.hxx>
39 #include <BRep_Tool.hxx>
40 #include <Standard_ErrorHandler.hxx>
41 #include <Standard_Failure.hxx>
42 #include <TopExp_Explorer.hxx>
43 #include <TopTools_MapIteratorOfMapOfShape.hxx>
44 #include <TopTools_MapOfShape.hxx>
45 #include <TopTools_SequenceOfShape.hxx>
46 #include <TopoDS.hxx>
47 #include <TopoDS_Edge.hxx>
48 #include <TopoDS_Face.hxx>
49 #include <TopoDS_Vertex.hxx>
50 #include <gp_Pnt.hxx>
51 #include <gp_Pnt2d.hxx>
52 #include <gp_Vec.hxx>
53 #include <gp_XYZ.hxx>
54
55 #include <list>
56 #include <set>
57 #include <vector>
58
59
60 #ifdef _DEBUG_
61
62 //#define DEB_FACES
63 //#define DEB_GRID
64 #define DUMP_VERT(msg,V) \
65 // { TopoDS_Vertex v = V; gp_Pnt p = BRep_Tool::Pnt(v);\
66 //   cout << msg << "( "<< p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;}
67
68 #else
69
70 #define DUMP_VERT(msg,v)
71
72 #endif
73
74 //================================================================================
75 // text for message about an internal error
76 #define ERR_LI(txt) SMESH_Comment(txt) << ":" << __LINE__
77
78 // order corresponds to right order of edges in CASCADE face
79 enum EQuadSides{ Q_BOTTOM=0, Q_RIGHT, Q_TOP, Q_LEFT,   Q_CHILD, Q_PARENT };
80
81 enum EBoxSides{ B_BOTTOM=0, B_RIGHT, B_TOP, B_LEFT, B_FRONT, B_BACK, B_UNDEFINED };
82
83 //================================================================================
84 /*!
85  * \brief Convertor of a pair of integers to a sole index
86  */
87 struct _Indexer
88 {
89   int _xSize, _ySize;
90   _Indexer( int xSize, int ySize ): _xSize(xSize), _ySize(ySize) {}
91   int size() const { return _xSize * _ySize; }
92   int operator()(const int x, const int y) const { return y * _xSize + x; }
93 };
94
95 //================================================================================
96 /*!
97  * \brief Wrapper of a composite or an ordinary edge.
98  */
99 class _FaceSide
100 {
101 public:
102   _FaceSide(const _FaceSide& other);
103   _FaceSide(const TopoDS_Edge& edge=TopoDS_Edge());
104   _FaceSide(const list<TopoDS_Edge>& edges);
105   _FaceSide* GetSide(const int i);
106   const _FaceSide* GetSide(const int i) const;
107   int size() const { return myChildren.size(); }
108   int NbVertices() const;
109   TopoDS_Vertex FirstVertex() const;
110   TopoDS_Vertex LastVertex() const;
111   TopoDS_Vertex Vertex(int i) const;
112   TopoDS_Edge   Edge(int i) const;
113   bool Contain( const _FaceSide& side, int* which=0 ) const;
114   bool Contain( const TopoDS_Vertex& vertex ) const;
115   void AppendSide( const _FaceSide& side );
116   void SetBottomSide( int i );
117   int GetNbSegments(SMESH_Mesh& mesh) const;
118   bool StoreNodes(SMESH_Mesh& mesh, vector<const SMDS_MeshNode*>& myGrid, bool reverse );
119   void SetID(EQuadSides id) { myID = id; }
120   static inline const TopoDS_TShape* ptr(const TopoDS_Shape& theShape)
121   { return theShape.TShape().operator->(); }
122   void Dump() const;
123
124 private:
125
126
127   TopoDS_Edge       myEdge;
128   list< _FaceSide > myChildren;
129   int               myNbChildren;
130
131   TopTools_MapOfShape myVertices;
132
133   EQuadSides        myID; // debug
134 };
135 //================================================================================
136 /*!
137  * \brief Class corresponding to a meshed composite face of a box.
138  *        Provides simplified access to it's sub-mesh data.
139  */
140 class _QuadFaceGrid
141 {
142   typedef list< _QuadFaceGrid > TChildren;
143 public:
144   _QuadFaceGrid();
145
146 public: //** Methods to find and orient faces of 6 sides of the box **//
147   
148   //!< initialization
149   bool Init(const TopoDS_Face& f);
150
151   //!< try to unite self with other face
152   bool AddContinuousFace( const _QuadFaceGrid& f );
153
154   //!< Try to set the side as bottom hirizontal side
155   bool SetBottomSide(const _FaceSide& side, int* sideIndex=0);
156
157   //!< Return face adjacent to zero-based i-th side of this face
158   _QuadFaceGrid* FindAdjacentForSide(int i, list<_QuadFaceGrid>& faces, EBoxSides id) const;
159
160   //!< Reverse edges in order to have the bottom edge going along axes of the unit box
161   void ReverseEdges(/*int e1, int e2*/);
162
163   bool IsComplex() const { return !myChildren.empty(); }
164
165   int NbChildren() const { return myChildren.size(); }
166
167   typedef SMDS_SetIterator< const _QuadFaceGrid&,
168                             TChildren::const_iterator,
169                             SMDS::SimpleAccessor<const _QuadFaceGrid&,TChildren::const_iterator>,
170                             SMDS::PassAllValueFilter<_QuadFaceGrid> >
171     TChildIterator;
172
173   TChildIterator GetChildren() const
174   { return TChildIterator( myChildren.begin(), myChildren.end()); }
175
176 public: //** Loading and access to mesh **//
177
178   //!< Load nodes of a mesh
179   bool LoadGrid( SMESH_Mesh& mesh );
180
181   //!< Return number of segments on the hirizontal sides
182   int GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers=false) const;
183
184   //!< Return number of segments on the vertical sides
185   int GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers=false) const;
186
187   //!< Return edge on the hirizontal bottom sides
188   int GetHoriEdges(vector<TopoDS_Edge> & edges) const;
189
190   //!< Return a node by its position
191   const SMDS_MeshNode* GetNode(int iHori, int iVert) const;
192
193   //!< Return node coordinates by its position
194   gp_XYZ GetXYZ(int iHori, int iVert) const;
195
196 public: //** Access to member fields **//
197
198   //!< Return i-th face side (0<i<4)
199   const _FaceSide& GetSide(int i) const;
200
201   //!< Return it's face, NULL if it is composite
202   TopoDS_Face GetFace() const { return myFace; }
203
204   //!< Return normal to the face at vertex v
205   bool GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const;
206
207   SMESH_ComputeErrorPtr GetError() const { return myError; }
208
209   void SetID(EBoxSides id) { myID = id; }
210
211   void DumpGrid() const;
212
213   void DumpVertices() const;
214
215 private:
216
217   bool error(const std::string& text, int code = COMPERR_ALGO_FAILED)
218   { myError = SMESH_ComputeError::New( code, text ); return false; }
219
220   bool error(const SMESH_ComputeErrorPtr& err)
221   { myError = err; return ( !myError || myError->IsOK() ); }
222
223   bool loadCompositeGrid(SMESH_Mesh& mesh);
224
225   bool fillGrid(SMESH_Mesh&                    theMesh,
226                 vector<const SMDS_MeshNode*> & theGrid,
227                 const _Indexer&                theIndexer,
228                 int                            theX,
229                 int                            theY);
230
231   bool locateChildren();
232
233   void setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers );
234
235   TopoDS_Face myFace;
236   _FaceSide   mySides;
237   bool        myReverse;
238
239   TChildren   myChildren;
240
241   _QuadFaceGrid* myLeftBottomChild;
242   _QuadFaceGrid* myRightBrother;
243   _QuadFaceGrid* myUpBrother;
244
245   _Indexer    myIndexer;
246   vector<const SMDS_MeshNode*>  myGrid;
247
248   SMESH_ComputeErrorPtr         myError;
249
250   EBoxSides   myID; // debug
251 };
252
253 //================================================================================
254 /*!
255  * \brief Constructor
256  */
257 //================================================================================
258
259 StdMeshers_CompositeHexa_3D::StdMeshers_CompositeHexa_3D(int hypId, int studyId, SMESH_Gen* gen)
260   :SMESH_3D_Algo(hypId, studyId, gen)
261 {
262   _name = "CompositeHexa_3D";
263   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);       // 1 bit /shape type
264 }
265
266 //================================================================================
267 /*!
268  * \brief always return true
269  */
270 //================================================================================
271
272 bool StdMeshers_CompositeHexa_3D::CheckHypothesis(SMESH_Mesh&         aMesh,
273                                                   const TopoDS_Shape& aShape,
274                                                   Hypothesis_Status&  aStatus)
275 {
276   aStatus = HYP_OK;
277   return true;
278 }
279
280 //================================================================================
281 /*!
282  * \brief Tries to find 6 sides of a box
283  */
284 //================================================================================
285
286 bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
287                                                 list< _QuadFaceGrid >& boxFaces,
288                                                 _QuadFaceGrid * &      fBottom,
289                                                 _QuadFaceGrid * &      fTop,
290                                                 _QuadFaceGrid * &      fFront,
291                                                 _QuadFaceGrid * &      fBack,
292                                                 _QuadFaceGrid * &      fLeft,
293                                                 _QuadFaceGrid * &      fRight)
294 {
295   list< _QuadFaceGrid >::iterator boxFace;
296   TopExp_Explorer exp;
297   int nbFaces = 0;
298   for ( exp.Init( shape, TopAbs_FACE); exp.More(); exp.Next(), ++nbFaces )
299   {
300     _QuadFaceGrid f;
301     if ( !f.Init( TopoDS::Face( exp.Current() )))
302       return error (COMPERR_BAD_SHAPE);
303
304     _QuadFaceGrid* prevContinuous = 0; 
305     for ( boxFace = boxFaces.begin(); boxFace != boxFaces.end(); ++boxFace )
306     {
307       if ( prevContinuous )
308       {
309         if ( prevContinuous->AddContinuousFace( *boxFace ))
310           boxFace = --boxFaces.erase( boxFace );
311       }
312       else if ( boxFace->AddContinuousFace( f ))
313       {
314         prevContinuous = & (*boxFace);
315       }   
316     }
317     if ( !prevContinuous )
318       boxFaces.push_back( f );
319   }
320   // Check what we have
321   if ( boxFaces.size() != 6 && nbFaces != 6)
322     return error
323       (COMPERR_BAD_SHAPE,
324        SMESH_Comment("Can't find 6 sides of a box. Number of found sides - ")<<boxFaces.size());
325
326   if ( boxFaces.size() != 6 && nbFaces == 6 ) { // strange ordinary box with continuous faces
327     boxFaces.resize( 6 );
328     boxFace = boxFaces.begin();
329     for ( exp.Init( shape, TopAbs_FACE); exp.More(); exp.Next(), ++boxFace )
330       boxFace->Init( TopoDS::Face( exp.Current() ) );
331   }
332   // ----------------------------------------
333   // Find out position of faces within a box
334   // ----------------------------------------
335   // start from a bottom face
336   fBottom = &boxFaces.front();
337   fBottom->SetID( B_BOTTOM );
338   // find vertical faces
339   fFront = fBottom->FindAdjacentForSide( Q_BOTTOM, boxFaces, B_FRONT );
340   fLeft  = fBottom->FindAdjacentForSide( Q_RIGHT,  boxFaces, B_LEFT  );
341   fBack  = fBottom->FindAdjacentForSide( Q_TOP,    boxFaces, B_BACK  );
342   fRight = fBottom->FindAdjacentForSide( Q_LEFT,   boxFaces, B_RIGHT );
343   // check the found
344   if ( !fFront || !fBack || !fLeft || !fRight )
345     return error(COMPERR_BAD_SHAPE);
346   // find a top face
347   fTop = 0;
348   for ( boxFace = ++boxFaces.begin(); boxFace != boxFaces.end() && !fTop; ++boxFace )
349   {
350     fTop = & (*boxFace);
351     fTop->SetID( B_TOP );
352     if ( fTop==fFront || fTop==fLeft || fTop==fBack || fTop==fRight )
353       fTop = 0;
354   }
355   // set bottom of the top side
356   if ( !fTop->SetBottomSide( fFront->GetSide( Q_TOP ) )) {
357     if ( !fFront->IsComplex() )
358       return error( ERR_LI("Error in StdMeshers_CompositeHexa_3D::Compute()"));
359     else {
360       _QuadFaceGrid::TChildIterator chIt = fFront->GetChildren();
361       while ( chIt.more() ) {
362         const _QuadFaceGrid& frontChild = chIt.next();
363         if ( fTop->SetBottomSide( frontChild.GetSide( Q_TOP )))
364           break;
365       }
366     }
367   }
368   if ( !fTop )
369     return error(COMPERR_BAD_SHAPE);
370
371   // orient bottom egde of faces along axes of the unit box
372   fBottom->ReverseEdges();
373   fBack  ->ReverseEdges();
374   fLeft  ->ReverseEdges();
375
376   return true;
377 }
378
379 //================================================================================
380 /*!
381  * \brief Computes hexahedral mesh on a box with composite sides
382  *  \param aMesh - mesh to compute
383  *  \param aShape - shape to mesh
384  *  \retval bool - succes sign
385  */
386 //================================================================================
387
388 bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
389                                           const TopoDS_Shape& theShape)
390 {
391   SMESH_MesherHelper helper( theMesh );
392   _quadraticMesh = helper.IsQuadraticSubMesh( theShape );
393   helper.SetElementsOnShape( true );
394
395   // -------------------------
396   // Try to find 6 side faces
397   // -------------------------
398   list< _QuadFaceGrid > boxFaceContainer;
399   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
400   if ( ! findBoxFaces( theShape, boxFaceContainer,
401                        fBottom, fTop, fFront, fBack, fLeft, fRight))
402     return false;
403
404   // ------------------------------------------
405   // Fill columns of nodes with existing nodes
406   // ------------------------------------------
407
408   // let faces load their grids
409   if ( !fBottom->LoadGrid( theMesh )) return error( fBottom->GetError() );
410   if ( !fBack  ->LoadGrid( theMesh )) return error( fBack  ->GetError() );
411   if ( !fLeft  ->LoadGrid( theMesh )) return error( fLeft  ->GetError() );
412   if ( !fFront ->LoadGrid( theMesh )) return error( fFront ->GetError() );
413   if ( !fRight ->LoadGrid( theMesh )) return error( fRight ->GetError() );
414   if ( !fTop   ->LoadGrid( theMesh )) return error( fTop   ->GetError() );
415
416   int x, xSize = fBottom->GetNbHoriSegments(theMesh) + 1, X = xSize - 1;
417   int y, ySize = fBottom->GetNbVertSegments(theMesh) + 1, Y = ySize - 1;
418   int z, zSize = fFront ->GetNbVertSegments(theMesh) + 1, Z = zSize - 1;
419   _Indexer colIndex( xSize, ySize );
420   vector< vector< const SMDS_MeshNode* > > columns( colIndex.size() );
421
422   // fill node columns by front and back box sides
423   for ( x = 0; x < xSize; ++x ) {
424     vector< const SMDS_MeshNode* >& column0 = columns[ colIndex( x, 0 )];
425     vector< const SMDS_MeshNode* >& column1 = columns[ colIndex( x, Y )];
426     column0.resize( zSize );
427     column1.resize( zSize );
428     for ( z = 0; z < zSize; ++z ) {
429       column0[ z ] = fFront->GetNode( x, z );
430       column1[ z ] = fBack ->GetNode( x, z );
431     }
432   }
433   // fill node columns by left and right box sides
434   for ( y = 1; y < ySize-1; ++y ) {
435     vector< const SMDS_MeshNode* >& column0 = columns[ colIndex( 0, y )];
436     vector< const SMDS_MeshNode* >& column1 = columns[ colIndex( X, y )];
437     column0.resize( zSize );
438     column1.resize( zSize );
439     for ( z = 0; z < zSize; ++z ) {
440       column0[ z ] = fLeft ->GetNode( y, z );
441       column1[ z ] = fRight->GetNode( y, z );
442     }
443   }
444   // get nodes from top and bottom box sides
445   for ( x = 1; x < xSize-1; ++x ) {
446     for ( y = 1; y < ySize-1; ++y ) {
447       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
448       column.resize( zSize );
449       column.front() = fBottom->GetNode( x, y );
450       column.back()  = fTop   ->GetNode( x, y );
451     }
452   }
453
454   // ----------------------------
455   // Add internal nodes of a box
456   // ----------------------------
457   // projection points of internal nodes on box sub-shapes by which
458   // coordinates of internal nodes are computed
459   vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
460
461   // projections on vertices are constant
462   pointsOnShapes[ SMESH_Block::ID_V000 ] = fBottom->GetXYZ( 0, 0 );
463   pointsOnShapes[ SMESH_Block::ID_V100 ] = fBottom->GetXYZ( X, 0 );
464   pointsOnShapes[ SMESH_Block::ID_V010 ] = fBottom->GetXYZ( 0, Y );
465   pointsOnShapes[ SMESH_Block::ID_V110 ] = fBottom->GetXYZ( X, Y );
466   pointsOnShapes[ SMESH_Block::ID_V001 ] = fTop->GetXYZ( 0, 0 );
467   pointsOnShapes[ SMESH_Block::ID_V101 ] = fTop->GetXYZ( X, 0 );
468   pointsOnShapes[ SMESH_Block::ID_V011 ] = fTop->GetXYZ( 0, Y );
469   pointsOnShapes[ SMESH_Block::ID_V111 ] = fTop->GetXYZ( X, Y );
470
471   for ( x = 1; x < xSize-1; ++x )
472   {
473     gp_XYZ params; // normalized parameters of internal node within a unit box
474     params.SetCoord( 1, x / double(X) );
475     for ( y = 1; y < ySize-1; ++y )
476     {
477       params.SetCoord( 2, y / double(Y) );
478       // column to fill during z loop
479       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
480       // points projections on horizontal edges
481       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = fBottom->GetXYZ( x, 0 );
482       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = fBottom->GetXYZ( x, Y );
483       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = fBottom->GetXYZ( 0, y );
484       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = fBottom->GetXYZ( X, y );
485       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = fTop->GetXYZ( x, 0 );
486       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = fTop->GetXYZ( x, Y );
487       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = fTop->GetXYZ( 0, y );
488       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = fTop->GetXYZ( X, y );
489       // points projections on horizontal faces
490       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = fBottom->GetXYZ( x, y );
491       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = fTop   ->GetXYZ( x, y );
492       for ( z = 1; z < zSize-1; ++z ) // z loop
493       {
494         params.SetCoord( 3, z / double(Z) );
495         // point projections on vertical edges
496         pointsOnShapes[ SMESH_Block::ID_E00z ] = fFront->GetXYZ( 0, z );    
497         pointsOnShapes[ SMESH_Block::ID_E10z ] = fFront->GetXYZ( X, z );    
498         pointsOnShapes[ SMESH_Block::ID_E01z ] = fBack->GetXYZ( 0, z );    
499         pointsOnShapes[ SMESH_Block::ID_E11z ] = fBack->GetXYZ( X, z );
500         // point projections on vertical faces
501         pointsOnShapes[ SMESH_Block::ID_Fx0z ] = fFront->GetXYZ( x, z );    
502         pointsOnShapes[ SMESH_Block::ID_Fx1z ] = fBack ->GetXYZ( x, z );    
503         pointsOnShapes[ SMESH_Block::ID_F0yz ] = fLeft ->GetXYZ( y, z );    
504         pointsOnShapes[ SMESH_Block::ID_F1yz ] = fRight->GetXYZ( y, z );
505
506         // compute internal node coordinates
507         gp_XYZ coords;
508         SMESH_Block::ShellPoint( params, pointsOnShapes, coords );
509         column[ z ] = helper.AddNode( coords.X(), coords.Y(), coords.Z() );
510
511 #ifdef DEB_GRID
512         // debug
513         //cout << "----------------------------------------------------------------------"<<endl;
514         //for ( int id = SMESH_Block::ID_V000; id < SMESH_Block::ID_Shell; ++id)
515         //{
516         //  gp_XYZ p = pointsOnShapes[ id ];
517         //  SMESH_Block::DumpShapeID( id,cout)<<" ( "<<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;
518         //}
519         //cout << "Params: ( "<< params.X()<<", "<<params.Y()<<", "<<params.Z()<<" )"<<endl;
520         //cout << "coords: ( "<< coords.X()<<", "<<coords.Y()<<", "<<coords.Z()<<" )"<<endl;
521 #endif
522       }
523     }
524   }
525   // faces no more needed, free memory
526   boxFaceContainer.clear();
527
528   // ----------------
529   // Add hexahedrons
530   // ----------------
531   for ( x = 0; x < xSize-1; ++x ) {
532     for ( y = 0; y < ySize-1; ++y ) {
533       vector< const SMDS_MeshNode* >& col00 = columns[ colIndex( x, y )];
534       vector< const SMDS_MeshNode* >& col10 = columns[ colIndex( x+1, y )];
535       vector< const SMDS_MeshNode* >& col01 = columns[ colIndex( x, y+1 )];
536       vector< const SMDS_MeshNode* >& col11 = columns[ colIndex( x+1, y+1 )];
537       for ( z = 0; z < zSize-1; ++z )
538       {
539         // bottom face normal of a hexa mush point outside the volume
540         helper.AddVolume(col00[z],   col01[z],   col11[z],   col10[z],
541                          col00[z+1], col01[z+1], col11[z+1], col10[z+1]);
542       }
543     }
544   }
545   return true;
546 }
547
548 //================================================================================
549 /*!
550  *  Evaluate
551  */
552 //================================================================================
553
554 bool StdMeshers_CompositeHexa_3D::Evaluate(SMESH_Mesh&         theMesh,
555                                            const TopoDS_Shape& theShape,
556                                            MapShapeNbElems&    aResMap)
557 {
558   // -------------------------
559   // Try to find 6 side faces
560   // -------------------------
561   list< _QuadFaceGrid > boxFaceContainer;
562   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
563   if ( ! findBoxFaces( theShape, boxFaceContainer,
564                        fBottom, fTop, fFront, fBack, fLeft, fRight))
565     return false;
566
567   // Find a less complex side
568   _QuadFaceGrid * lessComplexSide = & boxFaceContainer.front();
569   list< _QuadFaceGrid >::iterator face = boxFaceContainer.begin();
570   for ( ++face; face != boxFaceContainer.end() && lessComplexSide->IsComplex(); ++face )
571     if ( face->NbChildren() < lessComplexSide->NbChildren() )
572       lessComplexSide = & *face;
573
574   // Get an 1D size of lessComplexSide
575   int nbSeg1 = 0;
576   vector<TopoDS_Edge> edges;
577   if ( !lessComplexSide->GetHoriEdges(edges) )
578     return false;
579   for ( size_t i = 0; i < edges.size(); ++i )
580   {
581     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( edges[i] )];
582     if ( !nbElems.empty() )
583       nbSeg1 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
584   }
585
586   // Get an 1D size of a box side ortogonal to lessComplexSide
587   int nbSeg2 = 0;
588   _QuadFaceGrid* ortoSide =
589     lessComplexSide->FindAdjacentForSide( Q_LEFT, boxFaceContainer, B_UNDEFINED );
590   edges.clear();
591   if ( !ortoSide || !ortoSide->GetHoriEdges(edges) ) return false;
592   for ( size_t i = 0; i < edges.size(); ++i )
593   {
594     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( edges[i] )];
595     if ( !nbElems.empty() )
596       nbSeg2 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
597   }
598
599   // Get an 2D size of a box side ortogonal to lessComplexSide
600   int nbFaces = 0, nbQuadFace = 0;
601   list< TopoDS_Face > sideFaces;
602   if ( ortoSide->IsComplex() )
603     for ( _QuadFaceGrid::TChildIterator child = ortoSide->GetChildren(); child.more(); )
604       sideFaces.push_back( child.next().GetFace() );
605   else
606     sideFaces.push_back( ortoSide->GetFace() );
607   //
608   list< TopoDS_Face >::iterator f = sideFaces.begin();
609   for ( ; f != sideFaces.end(); ++f )
610   {
611     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( *f )];
612     if ( !nbElems.empty() )
613     {
614       nbFaces    = nbElems[ SMDSEntity_Quadrangle ];
615       nbQuadFace = nbElems[ SMDSEntity_Quad_Quadrangle ];
616     }
617   }
618
619   // Fill nb of elements
620   vector<int> aResVec(SMDSEntity_Last,0);
621   int nbSeg3 = ( nbFaces + nbQuadFace ) / nbSeg2;
622   aResVec[SMDSEntity_Node]       = (nbSeg1-1) * (nbSeg2-1) * (nbSeg3-1);
623   aResVec[SMDSEntity_Hexa]       = nbSeg1 * nbFaces;
624   aResVec[SMDSEntity_Quad_Hexa]  = nbSeg1 * nbQuadFace;
625
626   aResMap.insert( make_pair( theMesh.GetSubMesh(theShape), aResVec ));
627
628   return true;
629 }
630
631
632 //================================================================================
633 /*!
634  * \brief constructor of non-initialized _QuadFaceGrid
635  */
636 //================================================================================
637
638 _QuadFaceGrid::_QuadFaceGrid():
639   myReverse(false), myRightBrother(0), myUpBrother(0), myIndexer(0,0), myID(B_UNDEFINED)
640 {
641 }
642
643 //================================================================================
644 /*!
645  * \brief Initialization
646  */
647 //================================================================================
648
649 bool _QuadFaceGrid::Init(const TopoDS_Face& f)
650 {
651   myFace         = f;
652   mySides        = _FaceSide();
653   myReverse      = false;
654   myLeftBottomChild = myRightBrother = myUpBrother = 0;
655   myChildren.clear();
656   myGrid.clear();
657   //if ( myFace.Orientation() != TopAbs_FORWARD )
658     //myFace.Reverse();
659
660   TopoDS_Vertex V;
661   list< TopoDS_Edge > edges;
662   list< int > nbEdgesInWire;
663   int nbWire = SMESH_Block::GetOrderedEdges (myFace, V, edges, nbEdgesInWire);
664   if ( nbWire != 1 )
665     return false;
666
667   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
668   if ( nbEdgesInWire.front() == 4 ) // exactly 4 edges
669   {
670     for ( ; edgeIt != edges.end(); ++edgeIt )
671       mySides.AppendSide( _FaceSide( *edgeIt ));
672   }
673   else if ( nbEdgesInWire.front() > 4 ) { // more than 4 edges - try to unite some
674     list< TopoDS_Edge > sideEdges;
675     while ( !edges.empty()) {
676       sideEdges.clear();
677       sideEdges.splice( sideEdges.end(), edges, edges.begin());// edges.front()->sideEdges.back()
678       while ( !edges.empty() ) {
679         if ( SMESH_Algo::IsContinuous( sideEdges.back(), edges.front() )) {
680           sideEdges.splice( sideEdges.end(), edges, edges.begin());
681         }
682         else if ( SMESH_Algo::IsContinuous( sideEdges.front(), edges.back() )) {
683           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
684         }
685         else {
686           break;
687         }
688       }
689       mySides.AppendSide( _FaceSide( sideEdges ));
690     }
691   }
692   if (mySides.size() != 4)
693     return false;
694
695 #ifdef _DEBUG_
696   mySides.GetSide( Q_BOTTOM )->SetID( Q_BOTTOM );
697   mySides.GetSide( Q_RIGHT  )->SetID( Q_RIGHT );
698   mySides.GetSide( Q_TOP    )->SetID( Q_TOP );
699   mySides.GetSide( Q_LEFT   )->SetID( Q_LEFT );
700 #endif
701
702   return true;
703 }
704
705 //================================================================================
706 /*!
707  * \brief Try to unite self with other ordinary face
708  */
709 //================================================================================
710
711 bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid& other )
712 {
713   for ( int i = 0; i < 4; ++i )
714   {
715     const _FaceSide& otherSide = other.GetSide( i );
716     int iMyCommon;
717     if ( mySides.Contain( otherSide, &iMyCommon ) ) {
718       // check if normals of two faces are collinear at all vertices of a otherSide
719       const double angleTol = M_PI / 180. / 2.;
720       int iV, nbV = otherSide.NbVertices(), nbCollinear = 0;
721       for ( iV = 0; iV < nbV; ++iV )
722       {
723         TopoDS_Vertex v = otherSide.Vertex( iV );
724         gp_Vec n1, n2;
725         if ( !GetNormal( v, n1 ) || !other.GetNormal( v, n2 ))
726           continue;
727         if ( n1 * n2 < 0 )
728           n1.Reverse();
729         if ( n1.Angle(n2) < angleTol )
730           nbCollinear++;
731         else
732           break;
733       }
734       if ( nbCollinear > 1 ) { // this face becomes composite if not yet is
735         DUMP_VERT("Cont 1", mySides.GetSide(iMyCommon)->FirstVertex());
736         DUMP_VERT("Cont 2", mySides.GetSide(iMyCommon)->LastVertex());
737         DUMP_VERT("Cont 3", otherSide.FirstVertex());
738         DUMP_VERT("Cont 4", otherSide.LastVertex());
739         if ( myChildren.empty() ) {
740           myChildren.push_back( *this );
741           myFace.Nullify();
742         }
743         if ( other.IsComplex() )
744           for ( TChildIterator children = other.GetChildren(); children.more(); )
745             myChildren.push_back( children.next() );
746         else
747           myChildren.push_back( other );
748
749         myLeftBottomChild = 0;
750         //int otherBottomIndex = ( 4 + i - iMyCommon + 2 ) % 4;
751         //myChildren.back().SetBottomSide( other.GetSide( otherBottomIndex ));
752
753         // collect vertices in mySides
754         if ( other.IsComplex() )
755           for ( TChildIterator children = other.GetChildren(); children.more(); )
756           {
757             const _QuadFaceGrid& child =  children.next();
758             for ( int i = 0; i < 4; ++i )
759               mySides.AppendSide( child.GetSide(i) );
760           }
761         else
762           for ( int i = 0; i < 4; ++i )
763             mySides.AppendSide( other.GetSide(i) );
764
765         return true;
766       }
767     }
768   }
769   return false;
770 }
771
772 //================================================================================
773 /*!
774  * \brief Try to set the side as bottom hirizontal side
775  */
776 //================================================================================
777
778 bool _QuadFaceGrid::SetBottomSide(const _FaceSide& bottom, int* sideIndex)
779 {
780   myLeftBottomChild = myRightBrother = myUpBrother = 0;
781
782   int myBottomIndex;
783   if ( myChildren.empty() )
784   {
785     if ( mySides.Contain( bottom, &myBottomIndex )) {
786       mySides.SetBottomSide( myBottomIndex );
787       if ( sideIndex )
788         *sideIndex = myBottomIndex;
789       return true;
790     }
791   }
792   else
793   {
794     TChildren::iterator childFace = myChildren.begin(), childEnd = myChildren.end();
795     for ( ; childFace != childEnd; ++childFace )
796     {
797       if ( childFace->SetBottomSide( bottom, &myBottomIndex ))
798       {
799         TChildren::iterator orientedCild = childFace;
800         for ( childFace = myChildren.begin(); childFace != childEnd; ++childFace ) {
801           if ( childFace != orientedCild )
802             childFace->SetBottomSide( childFace->GetSide( myBottomIndex ));
803         }
804         if ( sideIndex )
805           *sideIndex = myBottomIndex;
806         return true;
807       }
808     }
809   }
810   return false;
811 }
812
813 //================================================================================
814 /*!
815  * \brief Return face adjacent to i-th side of this face, (0<i<4)
816  */
817 //================================================================================
818
819 _QuadFaceGrid* _QuadFaceGrid::FindAdjacentForSide(int                  i,
820                                                   list<_QuadFaceGrid>& faces,
821                                                   EBoxSides            id) const
822 {
823   const _FaceSide & iSide = GetSide( i );
824   list< _QuadFaceGrid >::iterator boxFace = faces.begin();
825   for ( ; boxFace != faces.end(); ++boxFace )
826   {
827     _QuadFaceGrid* f  = & (*boxFace);
828     if ( f != this && f->SetBottomSide( iSide ))
829       return f->SetID( id ), f;
830   }
831   return (_QuadFaceGrid*) 0;
832 }
833
834 //================================================================================
835 /*!
836  * \brief Return i-th side
837  */
838 //================================================================================
839
840 const _FaceSide& _QuadFaceGrid::GetSide(int i) const
841 {
842   if ( myChildren.empty() )
843     return *mySides.GetSide(i);
844
845   _QuadFaceGrid* me = const_cast<_QuadFaceGrid*>(this);
846   if ( !me->locateChildren() || !myLeftBottomChild )
847     return *mySides.GetSide(i);
848
849   const _QuadFaceGrid* child = myLeftBottomChild;
850   switch ( i ){
851   case Q_BOTTOM:
852   case Q_LEFT:
853     break;
854   case Q_RIGHT:
855     while ( child->myRightBrother )
856       child = child->myRightBrother;
857     break;
858   case Q_TOP:
859     while ( child->myUpBrother )
860       child = child->myUpBrother;
861     break;
862   default: ;
863   }
864   return child->GetSide( i );
865 }
866
867 //================================================================================
868 /*!
869  * \brief Reverse edges in order to have them oriented along axes of the unit box
870  */
871 //================================================================================
872
873 void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
874 {
875   myReverse = !myReverse;
876
877 // #ifdef DEB_FACES
878 //   if ( !myFace.IsNull() )
879 //     TopAbs::Print(myFace.Orientation(), cout);
880 // #endif
881
882   if ( myChildren.empty() )
883   {
884 //     mySides.GetSide( e1 )->Reverse();
885 //     mySides.GetSide( e2 )->Reverse();
886     DumpVertices();
887   }
888   else
889   {
890     DumpVertices();
891     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
892     for ( ; child != childEnd; ++child )
893       child->ReverseEdges( /*e1, e2*/ );
894   }
895 }
896
897 //================================================================================
898 /*!
899  * \brief Load nodes of a mesh
900  */
901 //================================================================================
902
903 bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
904 {
905   if ( !myChildren.empty() )
906   {
907     // Let child faces load their grids
908     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
909     for ( ; child != childEnd; ++child ) {
910       child->SetID( myID );
911       if ( !child->LoadGrid( mesh ) )
912         return error( child->GetError() );
913     }
914     // Fill myGrid with nodes of patches
915     return loadCompositeGrid( mesh );
916   }
917
918   // ---------------------------------------
919   // Fill myGrid with nodes bound to myFace
920   // ---------------------------------------
921
922   if ( !myGrid.empty() )
923     return true;
924
925   SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace )->GetSubMeshDS();
926   // check that all faces are quadrangular
927   SMDS_ElemIteratorPtr fIt = faceSubMesh->GetElements();
928   while ( fIt->more() )
929     if ( fIt->next()->NbNodes() % 4 > 0 )
930       return error("Non-quadrangular mesh faces are not allowed on sides of a composite block");
931   
932   myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
933   myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh );
934
935   myGrid.resize( myIndexer.size() );
936
937   // strore nodes bound to the bottom edge
938   mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse );
939
940   // store the rest nodes row by row
941
942   const SMDS_MeshNode* dummy = mesh.GetMeshDS()->AddNode(0,0,0);
943   const SMDS_MeshElement* firstQuad = dummy; // most left face above the last row of found nodes
944   
945   int nbFoundNodes = myIndexer._xSize;
946   while ( nbFoundNodes != myGrid.size() )
947   {
948     // first and last nodes of the last filled row of nodes
949     const SMDS_MeshNode* n1down = myGrid[ nbFoundNodes - myIndexer._xSize ];
950     const SMDS_MeshNode* n2down = myGrid[ nbFoundNodes - myIndexer._xSize + 1];
951     const SMDS_MeshNode* n1downLast = myGrid[ nbFoundNodes-1 ];
952
953     // find the first face above the row by the first two left nodes
954     //
955     // n1up     n2up
956     //     o---o
957     //     |   |
958     //     o---o  o  o  o  o
959     //n1down    n2down
960     //
961     TIDSortedElemSet emptySet, avoidSet;
962     avoidSet.insert( firstQuad );
963     firstQuad = SMESH_MeshEditor::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
964     while ( firstQuad && !faceSubMesh->Contains( firstQuad )) {
965       avoidSet.insert( firstQuad );
966       firstQuad = SMESH_MeshEditor::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
967     }
968     if ( !firstQuad || !faceSubMesh->Contains( firstQuad ))
969       return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
970
971     // find the node of quad bound to the left geom edge
972     int i2down = firstQuad->GetNodeIndex( n2down );
973     const SMDS_MeshNode* n1up = firstQuad->GetNode(( i2down+2 ) % 4 );
974     myGrid[ nbFoundNodes++ ] = n1up;
975     // the 4-the node of the first quad
976     int i1down = firstQuad->GetNodeIndex( n1down );
977     const SMDS_MeshNode* n2up = firstQuad->GetNode(( i1down+2 ) % 4 );
978     myGrid[ nbFoundNodes++ ] = n2up;
979
980     n1down = n2down;
981     n1up   = n2up;
982     const SMDS_MeshElement* quad = firstQuad;
983
984     // find the rest nodes by remaining faces above the row
985     //
986     //             n1up
987     //     o---o--o
988     //     |   |  | ->
989     //     o---o--o  o  o  o
990     //                      n1downLast
991     //
992     while ( n1down != n1downLast )
993     {
994       // next face
995       avoidSet.clear(); avoidSet.insert( quad );
996       quad = SMESH_MeshEditor::FindFaceInSet( n1down, n1up, emptySet, avoidSet );
997       if ( !quad || quad->NbNodes() % 4 > 0)
998         return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
999
1000       // next node
1001       if ( quad->GetNode( i1down ) != n1down ) // check already found index
1002         i1down = quad->GetNodeIndex( n1down );
1003       n2up = quad->GetNode(( i1down+2 ) % 4 );
1004       myGrid[ nbFoundNodes++ ] = n2up;
1005
1006       n1down = myGrid[ nbFoundNodes - myIndexer._xSize - 1 ];
1007       n1up   = n2up;
1008     }
1009   }
1010   mesh.GetMeshDS()->RemoveNode(dummy);
1011   DumpGrid(); // debug
1012
1013   return true;
1014 }
1015
1016 //================================================================================
1017 /*!
1018  * \brief Find out mutual location of children: find their right and up brothers
1019  */
1020 //================================================================================
1021
1022 bool _QuadFaceGrid::locateChildren()
1023 {
1024   if ( myLeftBottomChild )
1025     return true;
1026
1027   TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1028
1029   // find a child sharing it's first bottom vertex with no other brother
1030   myLeftBottomChild = 0;
1031   for ( ; !myLeftBottomChild && child != childEnd; ++child )
1032   {
1033     TopoDS_Vertex leftVertex = child->GetSide( Q_BOTTOM ).FirstVertex();
1034     bool sharedVertex = false;
1035     TChildren::iterator otherChild = myChildren.begin();
1036     for ( ; otherChild != childEnd && !sharedVertex; ++otherChild )
1037       if ( otherChild != child )
1038         sharedVertex = otherChild->mySides.Contain( leftVertex );
1039     if ( !sharedVertex ) {
1040       myLeftBottomChild = & (*child);
1041       DUMP_VERT("0 left bottom Vertex: ",leftVertex );
1042     }
1043   }
1044   if (!myLeftBottomChild)
1045     return error(ERR_LI("Error in locateChildren()"));
1046
1047   set< _QuadFaceGrid* > notLocatedChilren;
1048   for (child = myChildren.begin() ; child != childEnd; ++child )
1049     notLocatedChilren.insert( & (*child));
1050
1051   // connect myLeftBottomChild to it's right and upper brothers
1052   notLocatedChilren.erase( myLeftBottomChild );
1053   myLeftBottomChild->setBrothers( notLocatedChilren );
1054   if ( !notLocatedChilren.empty() )
1055     return error(ERR_LI("Error in locateChildren()"));
1056
1057   return true;
1058 }
1059
1060 //================================================================================
1061 /*!
1062  * \brief Fill myGrid with nodes of patches
1063  */
1064 //================================================================================
1065
1066 bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
1067 {
1068   // Find out mutual location of children: find their right and up brothers
1069   if ( !locateChildren() )
1070     return false;
1071
1072   // Load nodes according to mutual location of children
1073
1074   // grid size
1075   myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments(mesh, /*withBrothers=*/true);
1076   myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments(mesh, /*withBrothers=*/true);
1077
1078   myGrid.resize( myIndexer.size() );
1079
1080   int fromX = myReverse ? myIndexer._xSize : 0;
1081   if (!myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
1082     return error( myLeftBottomChild->GetError() );
1083
1084   DumpGrid();
1085
1086   return true;
1087 }
1088
1089 //================================================================================
1090 /*!
1091  * \brief Find right an upper brothers among notLocatedBrothers
1092  */
1093 //================================================================================
1094
1095 void _QuadFaceGrid::setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers )
1096 {
1097   if ( !notLocatedBrothers.empty() )
1098   {
1099     // find right brother
1100     TopoDS_Vertex rightVertex = GetSide( Q_BOTTOM ).LastVertex();
1101     DUMP_VERT("1 right bottom Vertex: ",rightVertex );
1102     set< _QuadFaceGrid* >::iterator brIt, brEnd = notLocatedBrothers.end();
1103     for ( brIt = notLocatedBrothers.begin(); !myRightBrother && brIt != brEnd; ++brIt )
1104     {
1105       _QuadFaceGrid* brother = *brIt;
1106       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1107       DUMP_VERT( "brother left bottom: ", brotherLeftVertex );
1108       if ( rightVertex.IsSame( brotherLeftVertex )) {
1109         myRightBrother = brother;
1110         notLocatedBrothers.erase( myRightBrother );
1111       }
1112     }
1113     // find upper brother
1114     TopoDS_Vertex upVertex = GetSide( Q_LEFT ).FirstVertex();
1115     DUMP_VERT("1 left up Vertex: ",upVertex);
1116     brIt = notLocatedBrothers.begin(), brEnd = notLocatedBrothers.end();
1117     for ( ; !myUpBrother && brIt != brEnd; ++brIt )
1118     {
1119       _QuadFaceGrid* brother = *brIt;
1120       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1121       DUMP_VERT("brother left bottom: ", brotherLeftVertex);
1122       if ( upVertex.IsSame( brotherLeftVertex )) {
1123         myUpBrother = brother;
1124         notLocatedBrothers.erase( myUpBrother );
1125       }
1126     }
1127     // recursive call
1128     if ( myRightBrother )
1129       myRightBrother->setBrothers( notLocatedBrothers );
1130     if ( myUpBrother )
1131       myUpBrother->setBrothers( notLocatedBrothers );
1132   }
1133 }
1134
1135 //================================================================================
1136 /*!
1137  * \brief Store nodes of a simple face into grid starting from (x,y) position
1138  */
1139 //================================================================================
1140
1141 bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
1142                              vector<const SMDS_MeshNode*> & theGrid,
1143                              const _Indexer&                theIndexer,
1144                              int                            theX,
1145                              int                            theY)
1146 {
1147   if ( myGrid.empty() && !LoadGrid( theMesh ))
1148     return false;
1149
1150   // store my own grid in the global grid
1151
1152   int fromX = myReverse ? theX - myIndexer._xSize: theX;
1153
1154   for ( int i = 0, x = fromX; i < myIndexer._xSize; ++i, ++x )
1155     for ( int j = 0, y = theY; j < myIndexer._ySize; ++j, ++y )
1156       theGrid[ theIndexer( x, y )] = myGrid[ myIndexer( i, j )];
1157
1158   // store grids of my right and upper brothers
1159
1160   if ( myRightBrother )
1161   {
1162     if ( myReverse )
1163       fromX += 1;
1164     else
1165       fromX += myIndexer._xSize - 1;
1166     if ( !myRightBrother->fillGrid( theMesh, theGrid, theIndexer, fromX, theY ))
1167       return error( myRightBrother->GetError() );
1168   }
1169   if ( myUpBrother )
1170   {
1171     if ( !myUpBrother->fillGrid( theMesh, theGrid, theIndexer,
1172                                  theX, theY + myIndexer._ySize - 1))
1173       return error( myUpBrother->GetError() );
1174   }
1175   return true;
1176 }
1177
1178 //================================================================================
1179 /*!
1180  * \brief Return number of segments on the hirizontal sides
1181  */
1182 //================================================================================
1183
1184 int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
1185 {
1186   int nbSegs = 0;
1187   if ( myLeftBottomChild )
1188   {
1189     nbSegs += myLeftBottomChild->GetNbHoriSegments( mesh, true );
1190   }
1191   else
1192   {
1193     nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments(mesh);
1194     if ( withBrothers && myRightBrother )
1195       nbSegs += myRightBrother->GetNbHoriSegments( mesh, withBrothers );
1196   }
1197   return nbSegs;
1198 }
1199
1200 //================================================================================
1201 /*!
1202  * \brief Return number of segments on the vertical sides
1203  */
1204 //================================================================================
1205
1206 int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
1207 {
1208   int nbSegs = 0;
1209   if ( myLeftBottomChild )
1210   {
1211     nbSegs += myLeftBottomChild->GetNbVertSegments( mesh, true );
1212   }
1213   else
1214   {
1215     nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh);
1216     if ( withBrothers && myUpBrother )
1217       nbSegs += myUpBrother->GetNbVertSegments( mesh, withBrothers );
1218   }
1219   return nbSegs;
1220 }
1221
1222 //================================================================================
1223 /*!
1224  * \brief Return edge on the hirizontal bottom sides
1225  */
1226 //================================================================================
1227
1228 int _QuadFaceGrid::GetHoriEdges(vector<TopoDS_Edge> & edges) const
1229 {
1230   if ( myLeftBottomChild )
1231   {
1232     return myLeftBottomChild->GetHoriEdges( edges );
1233   }
1234   else
1235   {
1236     const _FaceSide* bottom  = mySides.GetSide( Q_BOTTOM );
1237     int i = 0;
1238     while ( true ) {
1239       TopoDS_Edge e = bottom->Edge( i++ );
1240       if ( e.IsNull() )
1241         break;
1242       else
1243         edges.push_back( e );
1244     }
1245     if ( myRightBrother )
1246       myRightBrother->GetHoriEdges( edges );
1247   }
1248   return edges.size();
1249 }
1250
1251 //================================================================================
1252 /*!
1253  * \brief Return a node by its position
1254  */
1255 //================================================================================
1256
1257 const SMDS_MeshNode* _QuadFaceGrid::GetNode(int iHori, int iVert) const
1258 {
1259   return myGrid[ myIndexer( iHori, iVert )];
1260 }
1261
1262 //================================================================================
1263 /*!
1264  * \brief Return node coordinates by its position
1265  */
1266 //================================================================================
1267
1268 gp_XYZ _QuadFaceGrid::GetXYZ(int iHori, int iVert) const
1269 {
1270   const SMDS_MeshNode* n = myGrid[ myIndexer( iHori, iVert )];
1271   return gp_XYZ( n->X(), n->Y(), n->Z() );
1272 }
1273
1274 //================================================================================
1275 /*!
1276  * \brief Return normal to the face at vertex v
1277  */
1278 //================================================================================
1279
1280 bool _QuadFaceGrid::GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const
1281 {
1282   if ( myChildren.empty() )
1283   {
1284     if ( mySides.Contain( v )) {
1285       try {
1286         gp_Pnt2d uv = BRep_Tool::Parameters( v, myFace );
1287         BRepAdaptor_Surface surface( myFace );
1288         gp_Pnt p; gp_Vec d1u, d1v;
1289         surface.D1( uv.X(), uv.Y(), p, d1u, d1v );
1290         n = d1u.Crossed( d1v );
1291         return true;
1292       }
1293       catch (Standard_Failure) {
1294         return false;
1295       }
1296     }
1297   }
1298   else
1299   {
1300     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1301     for ( ; child != childEnd; ++child )
1302       if ( child->GetNormal( v, n ))
1303         return true;
1304   }
1305   return false;
1306 }
1307
1308 //================================================================================
1309 /*!
1310  * \brief Dumps coordinates of grid nodes
1311  */
1312 //================================================================================
1313
1314 void _QuadFaceGrid::DumpGrid() const
1315 {
1316 #ifdef DEB_GRID
1317   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1318   cout << "****** Face " << names[ myID ] << endl;
1319
1320   if ( myChildren.empty() || !myGrid.empty() )
1321   {
1322     cout << "x size: " << myIndexer._xSize << "; y size: " << myIndexer._ySize << endl;
1323     for ( int y = 0; y < myIndexer._ySize; ++y ) {
1324       cout << "-- row " << y << endl;
1325       for ( int x = 0; x < myIndexer._xSize; ++x ) {
1326         const SMDS_MeshNode* n = myGrid[ myIndexer( x, y ) ];
1327         cout << x << " ( " << n->X() << ", " << n->Y() << ", " << n->Z() << " )" << endl;
1328       }
1329     }
1330   }
1331   else
1332   {
1333     cout << "Nb children: " << myChildren.size() << endl;
1334     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1335     for ( int i=0; child != childEnd; ++child, ++i ) {
1336       cout << "   *** SUBFACE " << i+1 << endl;
1337       ((_QuadFaceGrid&)(*child)).SetID( myID );
1338       child->DumpGrid();
1339     }
1340   }
1341 #endif
1342 }
1343
1344 //================================================================================
1345 /*!
1346  * \brief Dump vertices
1347  */
1348 //================================================================================
1349
1350 void _QuadFaceGrid::DumpVertices() const
1351 {
1352 #ifdef DEB_FACES
1353   cout << "****** Face ";
1354   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1355   if ( myID >= B_BOTTOM && myID < B_BACK )
1356     cout << names[ myID ] << endl;
1357   else
1358     cout << "UNDEFINED" << endl;
1359
1360   if ( myChildren.empty() )
1361   {
1362     for ( int i = 0; i < 4; ++i )
1363     {
1364       cout << "  Side "; mySides.GetSide( i )->Dump();
1365     }
1366   }
1367   else
1368   {
1369     cout << "-- Nb children: " << myChildren.size() << endl;
1370     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1371     for ( int i=0; child != childEnd; ++child, ++i ) {
1372       cout << "   *** SUBFACE " << i+1 << endl;
1373       ((_QuadFaceGrid&)(*child)).SetID( myID );
1374       child->DumpVertices();
1375     }
1376   }
1377 #endif
1378 }
1379
1380 //=======================================================================
1381 //function : _FaceSide
1382 //purpose  : copy constructor
1383 //=======================================================================
1384
1385 _FaceSide::_FaceSide(const _FaceSide& other)
1386 {
1387   myEdge = other.myEdge;
1388   myChildren = other.myChildren;
1389   myNbChildren = other.myNbChildren;
1390   myVertices.Assign( other.myVertices );
1391   myID = other.myID;
1392 }
1393
1394 //================================================================================
1395 /*!
1396  * \brief Construct a face side of one edge
1397  */
1398 //================================================================================
1399
1400 _FaceSide::_FaceSide(const TopoDS_Edge& edge):
1401   myEdge( edge ), myNbChildren(0)
1402 {
1403   if ( !edge.IsNull() )
1404     for ( TopExp_Explorer exp( edge, TopAbs_VERTEX ); exp.More(); exp.Next() )
1405       //myVertices.insert( ptr ( exp.Current() ));
1406       myVertices.Add( exp.Current() );
1407 }
1408
1409 //================================================================================
1410 /*!
1411  * \brief Construct a face side of several edges
1412  */
1413 //================================================================================
1414
1415 _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
1416   myNbChildren(0)
1417 {
1418   list<TopoDS_Edge>::const_iterator edge = edges.begin(), eEnd = edges.end();
1419   for ( ; edge != eEnd; ++edge ) {
1420     myChildren.push_back( _FaceSide( *edge ));
1421     myNbChildren++;
1422 //     myVertices.insert( myChildren.back().myVertices.begin(),
1423 //                        myChildren.back().myVertices.end() );
1424     myVertices.Add( myChildren.back().FirstVertex() );
1425     myVertices.Add( myChildren.back().LastVertex() );
1426     myChildren.back().SetID( Q_CHILD ); // not to splice them
1427   }
1428 }
1429
1430 //=======================================================================
1431 //function : GetSide
1432 //purpose  : 
1433 //=======================================================================
1434
1435 _FaceSide* _FaceSide::GetSide(const int i)
1436 {
1437   if ( i >= myNbChildren )
1438     return 0;
1439
1440   list< _FaceSide >::iterator side = myChildren.begin();
1441   if ( i )
1442     std::advance( side, i );
1443   return & (*side);
1444 }
1445
1446 //=======================================================================
1447 //function : GetSide
1448 //purpose  : 
1449 //=======================================================================
1450
1451 const _FaceSide* _FaceSide::GetSide(const int i) const
1452 {
1453   return const_cast< _FaceSide* >(this)->GetSide(i);
1454 }
1455
1456 //=======================================================================
1457 //function : NbVertices
1458 //purpose  : return nb of vertices in the side
1459 //=======================================================================
1460
1461 int _FaceSide::NbVertices() const
1462 {
1463   if ( myChildren.empty() )
1464     return myVertices.Extent();
1465
1466   return myNbChildren + 1;
1467 }
1468
1469 //=======================================================================
1470 //function : FirstVertex
1471 //purpose  : 
1472 //=======================================================================
1473
1474 TopoDS_Vertex _FaceSide::FirstVertex() const
1475 {
1476   if ( myChildren.empty() )
1477     return TopExp::FirstVertex( myEdge, Standard_True );
1478
1479   return myChildren.front().FirstVertex();
1480 }
1481
1482 //=======================================================================
1483 //function : LastVertex
1484 //purpose  : 
1485 //=======================================================================
1486
1487 TopoDS_Vertex _FaceSide::LastVertex() const
1488 {
1489   if ( myChildren.empty() )
1490     return TopExp::LastVertex( myEdge, Standard_True );
1491
1492   return myChildren.back().LastVertex();
1493 }
1494
1495 //=======================================================================
1496 //function : Vertex
1497 //purpose  : 
1498 //=======================================================================
1499
1500 TopoDS_Vertex _FaceSide::Vertex(int i) const
1501 {
1502   if ( myChildren.empty() )
1503     return i ? LastVertex() : FirstVertex();
1504       
1505   if ( i >= myNbChildren )
1506     return myChildren.back().LastVertex();
1507   
1508   return GetSide(i)->FirstVertex();
1509 }
1510
1511 //================================================================================
1512 /*!
1513  * \brief Return i-the zero-based edge of the side
1514  */
1515 //================================================================================
1516
1517 TopoDS_Edge _FaceSide::Edge(int i) const
1518 {
1519   if ( i == 0 && !myEdge.IsNull() )
1520     return myEdge;
1521
1522   if ( const _FaceSide* iSide = GetSide( i ))
1523     return iSide->myEdge;
1524
1525   return TopoDS_Edge();
1526 }
1527
1528 //=======================================================================
1529 //function : Contain
1530 //purpose  : 
1531 //=======================================================================
1532
1533 bool _FaceSide::Contain( const _FaceSide& side, int* which ) const
1534 {
1535   if ( !which || myChildren.empty() )
1536   {
1537     if ( which )
1538       *which = 0;
1539     int nbCommon = 0;
1540     TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1541     for ( ; vIt.More(); vIt.Next() )
1542       nbCommon += ( myVertices.Contains( vIt.Key() ));
1543     return (nbCommon > 1);
1544   }
1545   list< _FaceSide >::const_iterator mySide = myChildren.begin(), sideEnd = myChildren.end();
1546   for ( int i = 0; mySide != sideEnd; ++mySide, ++i ) {
1547     if ( mySide->Contain( side )) {
1548       *which = i;
1549       return true;
1550     }
1551   }
1552   return false;
1553 }
1554
1555 //=======================================================================
1556 //function : Contain
1557 //purpose  : 
1558 //=======================================================================
1559
1560 bool _FaceSide::Contain( const TopoDS_Vertex& vertex ) const
1561 {
1562   return myVertices.Contains( vertex );
1563 }
1564
1565 //=======================================================================
1566 //function : AppendSide
1567 //purpose  : 
1568 //=======================================================================
1569
1570 void _FaceSide::AppendSide( const _FaceSide& side )
1571 {
1572   if ( !myEdge.IsNull() )
1573   {
1574     myChildren.push_back( *this );
1575     myNbChildren = 1;
1576     myEdge.Nullify();
1577   }
1578   myChildren.push_back( side );
1579   myNbChildren++;
1580   TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1581   for ( ; vIt.More(); vIt.Next() )
1582     myVertices.Add( vIt.Key() );
1583
1584   myID = Q_PARENT;
1585   myChildren.back().SetID( EQuadSides( myNbChildren-1 ));
1586 }
1587
1588 //=======================================================================
1589 //function : SetBottomSide
1590 //purpose  : 
1591 //=======================================================================
1592
1593 void _FaceSide::SetBottomSide( int i )
1594 {
1595   if ( i > 0 && myID == Q_PARENT ) {
1596     list< _FaceSide >::iterator sideEnd, side = myChildren.begin();
1597     std::advance( side, i );
1598     myChildren.splice( myChildren.begin(), myChildren, side, myChildren.end() );
1599
1600     side = myChildren.begin(), sideEnd = myChildren.end();
1601     for ( int i = 0; side != sideEnd; ++side, ++i ) {
1602       side->SetID( EQuadSides(i) );
1603       side->SetBottomSide(i);
1604     }
1605   }
1606 }
1607
1608 //=======================================================================
1609 //function : GetNbSegments
1610 //purpose  : 
1611 //=======================================================================
1612
1613 int _FaceSide::GetNbSegments(SMESH_Mesh& mesh) const
1614 {
1615   int nb = 0;
1616   if ( myChildren.empty() )
1617   {
1618     nb = mesh.GetSubMesh(myEdge)->GetSubMeshDS()->NbElements();
1619   }
1620   else
1621   {
1622     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1623     for ( ; side != sideEnd; ++side )
1624       nb += side->GetNbSegments(mesh);
1625   }
1626   return nb;
1627 }
1628
1629 //=======================================================================
1630 //function : StoreNodes
1631 //purpose  : 
1632 //=======================================================================
1633
1634 bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
1635                            vector<const SMDS_MeshNode*>& myGrid,
1636                            bool                          reverse )
1637 {
1638   list< TopoDS_Edge > edges;
1639   if ( myChildren.empty() )
1640   {
1641     edges.push_back( myEdge );
1642   }
1643   else
1644   {
1645     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1646     for ( ; side != sideEnd; ++side )
1647       if ( reverse )
1648         edges.push_front( side->myEdge );
1649       else
1650         edges.push_back ( side->myEdge );
1651   }
1652   int nbNodes = 0;
1653   list< TopoDS_Edge >::iterator edge = edges.begin(), eEnd = edges.end();
1654   for ( ; edge != eEnd; ++edge )
1655   {
1656     map< double, const SMDS_MeshNode* > nodes;
1657     bool ok = SMESH_Algo::GetSortedNodesOnEdge( mesh.GetMeshDS(),
1658                                                 *edge,
1659                                                 /*ignoreMediumNodes=*/true,
1660                                                 nodes);
1661     if ( !ok ) return false;
1662
1663     bool forward = ( edge->Orientation() == TopAbs_FORWARD );
1664     if ( reverse ) forward = !forward;
1665     if ( forward )
1666     {
1667       map< double, const SMDS_MeshNode* >::iterator u_node, nEnd = nodes.end();
1668       for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
1669         myGrid[ nbNodes++ ] = u_node->second;
1670     }
1671     else 
1672     {
1673       map< double, const SMDS_MeshNode* >::reverse_iterator u_node, nEnd = nodes.rend();
1674       for ( u_node = nodes.rbegin(); u_node != nEnd; ++u_node )
1675         myGrid[ nbNodes++ ] = u_node->second;
1676     }
1677     nbNodes--; // node on vertex present in two adjacent edges
1678   }
1679   return nbNodes > 0;
1680 }
1681
1682 //=======================================================================
1683 //function : Dump
1684 //purpose  : dump end vertices
1685 //=======================================================================
1686
1687 void _FaceSide::Dump() const
1688 {
1689   if ( myChildren.empty() )
1690   {
1691     const char* sideNames[] = { "Q_BOTTOM", "Q_RIGHT", "Q_TOP", "Q_LEFT", "Q_CHILD", "Q_PARENT" };
1692     if ( myID >= Q_BOTTOM && myID < Q_PARENT )
1693       cout << sideNames[ myID ] << endl;
1694     else
1695       cout << "<UNDEFINED ID>" << endl;
1696     TopoDS_Vertex f = FirstVertex();
1697     TopoDS_Vertex l = LastVertex();
1698     gp_Pnt pf = BRep_Tool::Pnt(f);
1699     gp_Pnt pl = BRep_Tool::Pnt(l);
1700     cout << "\t ( "<< ptr( f ) << " - " << ptr( l )<< " )"
1701          << "\t ( "<< pf.X()<<", "<<pf.Y()<<", "<<pf.Z()<<" ) - "
1702          << " ( "<< pl.X()<<", "<<pl.Y()<<", "<<pl.Z()<<" )"<<endl;
1703   }
1704   else
1705   {
1706     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1707     for ( ; side != sideEnd; ++side ) {
1708       side->Dump();
1709       cout << "\t";
1710     }
1711   }
1712 }