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