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