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