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