Salome HOME
42acee19ef87647e07c4c15b2cd38d153a9b7920
[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_MeshEditor.hxx"
37 #include "SMESH_MesherHelper.hxx"
38 #include "SMESH_subMesh.hxx"
39
40 #include <BRepAdaptor_Surface.hxx>
41 #include <BRep_Tool.hxx>
42 #include <Standard_ErrorHandler.hxx>
43 #include <Standard_Failure.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <TopTools_MapIteratorOfMapOfShape.hxx>
46 #include <TopTools_MapOfShape.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  * \brief constructor of non-initialized _QuadFaceGrid
514  */
515 //================================================================================
516
517 _QuadFaceGrid::_QuadFaceGrid():
518   myReverse(false), myRightBrother(0), myUpBrother(0), myIndexer(0,0), myID(B_UNDEFINED)
519 {
520 }
521
522 //================================================================================
523 /*!
524  * \brief Initialization
525  */
526 //================================================================================
527
528 bool _QuadFaceGrid::Init(const TopoDS_Face& f)
529 {
530   myFace         = f;
531   mySides        = _FaceSide();
532   myReverse      = false;
533   myLeftBottomChild = myRightBrother = myUpBrother = 0;
534   myChildren.clear();
535   myGrid.clear();
536   //if ( myFace.Orientation() != TopAbs_FORWARD )
537     //myFace.Reverse();
538
539   TopoDS_Vertex V;
540   list< TopoDS_Edge > edges;
541   list< int > nbEdgesInWire;
542   int nbWire = SMESH_Block::GetOrderedEdges (myFace, V, edges, nbEdgesInWire);
543   if ( nbWire != 1 )
544     return false;
545
546   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
547   if ( nbEdgesInWire.front() == 4 ) // exactly 4 edges
548   {
549     for ( ; edgeIt != edges.end(); ++edgeIt )
550       mySides.AppendSide( _FaceSide( *edgeIt ));
551   }
552   else if ( nbEdgesInWire.front() > 4 ) { // more than 4 edges - try to unite some
553     list< TopoDS_Edge > sideEdges;
554     while ( !edges.empty()) {
555       sideEdges.clear();
556       sideEdges.splice( sideEdges.end(), edges, edges.begin());// edges.front()->sideEdges.back()
557       while ( !edges.empty() ) {
558         if ( SMESH_Algo::IsContinuous( sideEdges.back(), edges.front() )) {
559           sideEdges.splice( sideEdges.end(), edges, edges.begin());
560         }
561         else if ( SMESH_Algo::IsContinuous( sideEdges.front(), edges.back() )) {
562           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
563         }
564         else {
565           break;
566         }
567       }
568       mySides.AppendSide( _FaceSide( sideEdges ));
569     }
570   }
571   if (mySides.size() != 4)
572     return false;
573
574 #ifdef _DEBUG_
575   mySides.GetSide( Q_BOTTOM )->SetID( Q_BOTTOM );
576   mySides.GetSide( Q_RIGHT  )->SetID( Q_RIGHT );
577   mySides.GetSide( Q_TOP    )->SetID( Q_TOP );
578   mySides.GetSide( Q_LEFT   )->SetID( Q_LEFT );
579 #endif
580
581   return true;
582 }
583
584 //================================================================================
585 /*!
586  * \brief Try to unite self with other ordinary face
587  */
588 //================================================================================
589
590 bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid& other )
591 {
592   for ( int i = 0; i < 4; ++i ) {
593     const _FaceSide& otherSide = other.GetSide( i );
594     int iMyCommon;
595     if ( mySides.Contain( otherSide, &iMyCommon ) ) {
596       // check if normals of two faces are collinear at all vertices of a otherSide
597       const double angleTol = PI / 180 / 2;
598       int iV, nbV = otherSide.NbVertices(), nbCollinear = 0;
599       for ( iV = 0; iV < nbV; ++iV )
600       {
601         TopoDS_Vertex v = otherSide.Vertex( iV );
602         gp_Vec n1, n2;
603         if ( !GetNormal( v, n1 ) || !other.GetNormal( v, n2 ))
604           continue;
605         if ( n1 * n2 < 0 )
606           n1.Reverse();
607         if ( n1.Angle(n2) < angleTol )
608           nbCollinear++;
609         else
610           break;
611       }
612       if ( nbCollinear > 1 ) { // this face becomes composite if not yet is
613         DUMP_VERT("Cont 1", mySides.GetSide(iMyCommon)->FirstVertex());
614         DUMP_VERT("Cont 2", mySides.GetSide(iMyCommon)->LastVertex());
615         DUMP_VERT("Cont 3", otherSide.FirstVertex());
616         DUMP_VERT("Cont 4", otherSide.LastVertex());
617         if ( myChildren.empty() ) {
618           myChildren.push_back( *this );
619           myFace.Nullify();
620         }
621         myChildren.push_back( other );
622         int otherBottomIndex = ( 4 + i - iMyCommon + 2 ) % 4;
623         myChildren.back().SetBottomSide( other.GetSide( otherBottomIndex ));
624         // collect vertices in mySides
625         mySides.AppendSide( other.GetSide(0) );
626         mySides.AppendSide( other.GetSide(1) );
627         mySides.AppendSide( other.GetSide(2) );
628         mySides.AppendSide( other.GetSide(3) );
629         return true;
630       }
631     }
632   }
633   return false;
634 }
635
636 //================================================================================
637 /*!
638  * \brief Try to set the side as bottom hirizontal side
639  */
640 //================================================================================
641
642 bool _QuadFaceGrid::SetBottomSide(const _FaceSide& bottom, int* sideIndex)
643 {
644   myLeftBottomChild = myRightBrother = myUpBrother = 0;
645
646   int myBottomIndex;
647   if ( myChildren.empty() )
648   {
649     if ( mySides.Contain( bottom, &myBottomIndex )) {
650       mySides.SetBottomSide( myBottomIndex );
651       if ( sideIndex )
652         *sideIndex = myBottomIndex;
653       return true;
654     }
655   }
656   else
657   {
658     TChildren::iterator childFace = myChildren.begin(), childEnd = myChildren.end();
659     for ( ; childFace != childEnd; ++childFace )
660     {
661       if ( childFace->SetBottomSide( bottom, &myBottomIndex ))
662       {
663         TChildren::iterator orientedCild = childFace;
664         for ( childFace = myChildren.begin(); childFace != childEnd; ++childFace ) {
665           if ( childFace != orientedCild )
666             childFace->SetBottomSide( childFace->GetSide( myBottomIndex ));
667         }
668         if ( sideIndex )
669           *sideIndex = myBottomIndex;
670         return true;
671       }
672     }
673   }
674   return false;
675 }
676
677 //================================================================================
678 /*!
679  * \brief Return face adjacent to i-th side of this face, (0<i<4)
680  */
681 //================================================================================
682
683 _QuadFaceGrid* _QuadFaceGrid::FindAdjacentForSide(int i, vector<_QuadFaceGrid>& faces) const
684 {
685   for ( int iF = 0; iF < faces.size(); ++iF ) {
686     _QuadFaceGrid* f  = &faces[ iF ];
687     if ( f != this && f->SetBottomSide( GetSide( i )))
688       return f;
689   }
690   return (_QuadFaceGrid*) 0;
691 }
692
693 //================================================================================
694 /*!
695  * \brief Return i-th side
696  */
697 //================================================================================
698
699 const _FaceSide& _QuadFaceGrid::GetSide(int i) const
700 {
701   if ( myChildren.empty() )
702     return *mySides.GetSide(i);
703
704   _QuadFaceGrid* me = const_cast<_QuadFaceGrid*>(this);
705   if ( !me->locateChildren() || !myLeftBottomChild )
706     return *mySides.GetSide(i);
707
708   const _QuadFaceGrid* child = myLeftBottomChild;
709   switch ( i ){
710   case Q_BOTTOM:
711   case Q_LEFT:
712     break;
713   case Q_RIGHT:
714     while ( child->myRightBrother )
715       child = child->myRightBrother;
716     break;
717   case Q_TOP:
718     while ( child->myUpBrother )
719       child = child->myUpBrother;
720     break;
721   default: ;
722   }
723   return child->GetSide( i );
724 }
725
726 //================================================================================
727 /*!
728  * \brief Reverse edges in order to have them oriented along axes of the unit box
729  */
730 //================================================================================
731
732 void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
733 {
734   myReverse = !myReverse;
735
736 // #ifdef DEB_FACES
737 //   if ( !myFace.IsNull() )
738 //     TopAbs::Print(myFace.Orientation(), cout);
739 // #endif
740
741   if ( myChildren.empty() )
742   {
743 //     mySides.GetSide( e1 )->Reverse();
744 //     mySides.GetSide( e2 )->Reverse();
745     DumpVertices();
746   }
747   else
748   {
749     DumpVertices();
750     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
751     for ( ; child != childEnd; ++child )
752       child->ReverseEdges( /*e1, e2*/ );
753   }
754 }
755
756 //================================================================================
757 /*!
758  * \brief Load nodes of a mesh
759  */
760 //================================================================================
761
762 bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
763 {
764   if ( !myChildren.empty() )
765   {
766     // Let child faces load their grids
767     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
768     for ( ; child != childEnd; ++child ) {
769       child->SetID( myID );
770       if ( !child->LoadGrid( mesh ) )
771         return error( child->GetError() );
772     }
773     // Fill myGrid with nodes of patches
774     return loadCompositeGrid( mesh );
775   }
776
777   // ---------------------------------------
778   // Fill myGrid with nodes bound to myFace
779   // ---------------------------------------
780
781   if ( !myGrid.empty() )
782     return true;
783
784   myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
785   myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh );
786
787   myGrid.resize( myIndexer.size() );
788
789   // strore nodes bound to the bottom edge
790   mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse );
791
792   // store the rest nodes row by row
793
794   SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace )->GetSubMeshDS();
795
796   SMDS_MeshNode dummy(0,0,0);
797   const SMDS_MeshElement* firstQuad = &dummy;// most left face above the last row of found nodes
798   
799   int nbFoundNodes = myIndexer._xSize;
800   while ( nbFoundNodes != myGrid.size() )
801   {
802     // first and last nodes of the last filled row of nodes
803     const SMDS_MeshNode* n1down = myGrid[ nbFoundNodes - myIndexer._xSize ];
804     const SMDS_MeshNode* n2down = myGrid[ nbFoundNodes - myIndexer._xSize + 1];
805     const SMDS_MeshNode* n1downLast = myGrid[ nbFoundNodes-1 ];
806
807     // find the first face above the row by the first two left nodes
808     //
809     // n1up     n2up
810     //     o---o
811     //     |   |
812     //     o---o  o  o  o  o
813     //n1down    n2down
814     //
815     TIDSortedElemSet emptySet, avoidSet;
816     avoidSet.insert( firstQuad );
817     firstQuad = SMESH_MeshEditor::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
818     if ( firstQuad && !faceSubMesh->Contains( firstQuad )) {
819       avoidSet.insert( firstQuad );
820       firstQuad = SMESH_MeshEditor::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
821     }
822     if ( !firstQuad || !faceSubMesh->Contains( firstQuad ))
823       return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
824
825     // find the node of quad bound to the left geom edge
826     int i2down = firstQuad->GetNodeIndex( n2down );
827     const SMDS_MeshNode* n1up = firstQuad->GetNode(( i2down+2 ) % 4 );
828     myGrid[ nbFoundNodes++ ] = n1up;
829     // the 4-the node of the first quad
830     int i1down = firstQuad->GetNodeIndex( n1down );
831     const SMDS_MeshNode* n2up = firstQuad->GetNode(( i1down+2 ) % 4 );
832     myGrid[ nbFoundNodes++ ] = n2up;
833
834     n1down = n2down;
835     n1up   = n2up;
836     const SMDS_MeshElement* quad = firstQuad;
837
838     // find the rest nodes by remaining faces above the row
839     //
840     //             n1up
841     //     o---o--o
842     //     |   |  | ->
843     //     o---o--o  o  o  o
844     //                      n1downLast
845     //
846     while ( n1down != n1downLast )
847     {
848       // next face
849       avoidSet.clear(); avoidSet.insert( quad );
850       quad = SMESH_MeshEditor::FindFaceInSet( n1down, n1up, emptySet, avoidSet );
851       if ( !quad || quad->NbNodes() % 4 > 0)
852         return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
853
854       // next node
855       if ( quad->GetNode( i1down ) != n1down ) // check already found index
856         i1down = quad->GetNodeIndex( n1down );
857       n2up = quad->GetNode(( i1down+2 ) % 4 );
858       myGrid[ nbFoundNodes++ ] = n2up;
859
860       n1down = myGrid[ nbFoundNodes - myIndexer._xSize - 1 ];
861       n1up   = n2up;
862     }
863   }
864
865   DumpGrid(); // debug
866
867   return true;
868 }
869
870 //================================================================================
871 /*!
872  * \brief Find out mutual location of children: find their right and up brothers
873  */
874 //================================================================================
875
876 bool _QuadFaceGrid::locateChildren()
877 {
878   if ( myLeftBottomChild )
879     return true;
880
881   TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
882
883   // find a child sharing it's first bottom vertex with no other brother
884   myLeftBottomChild = 0;
885   for ( ; !myLeftBottomChild && child != childEnd; ++child )
886   {
887     TopoDS_Vertex leftVertex = child->GetSide( Q_BOTTOM ).FirstVertex();
888     bool sharedVertex = false;
889     TChildren::iterator otherChild = myChildren.begin();
890     for ( ; otherChild != childEnd && !sharedVertex; ++otherChild )
891       if ( otherChild != child )
892         sharedVertex = otherChild->mySides.Contain( leftVertex );
893     if ( !sharedVertex ) {
894       myLeftBottomChild = & (*child);
895       DUMP_VERT("0 left bottom Vertex: ",leftVertex );
896     }
897   }
898   if (!myLeftBottomChild)
899     return error(ERR_LI("Error in locateChildren()"));
900
901   set< _QuadFaceGrid* > notLocatedChilren;
902   for (child = myChildren.begin() ; child != childEnd; ++child )
903     notLocatedChilren.insert( & (*child));
904
905   // connect myLeftBottomChild to it's right and upper brothers
906   notLocatedChilren.erase( myLeftBottomChild );
907   myLeftBottomChild->setBrothers( notLocatedChilren );
908   if ( !notLocatedChilren.empty() )
909     return error(ERR_LI("Error in locateChildren()"));
910
911   return true;
912 }
913
914 //================================================================================
915 /*!
916  * \brief Fill myGrid with nodes of patches
917  */
918 //================================================================================
919
920 bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
921 {
922   // Find out mutual location of children: find their right and up brothers
923   if ( !locateChildren() )
924     return false;
925
926   // Load nodes according to mutual location of children
927
928   // grid size
929   myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments(mesh, /*withBrothers=*/true);
930   myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments(mesh, /*withBrothers=*/true);
931
932   myGrid.resize( myIndexer.size() );
933
934   int fromX = myReverse ? myIndexer._xSize : 0;
935   if (!myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
936     return error( myLeftBottomChild->GetError() );
937
938   DumpGrid();
939
940   return true;
941 }
942
943 //================================================================================
944 /*!
945  * \brief Find right an upper brothers among notLocatedBrothers
946  */
947 //================================================================================
948
949 void _QuadFaceGrid::setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers )
950 {
951   if ( !notLocatedBrothers.empty() )
952   {
953     // find right brother
954     TopoDS_Vertex rightVertex = GetSide( Q_BOTTOM ).LastVertex();
955     DUMP_VERT("1 right bottom Vertex: ",rightVertex );
956     set< _QuadFaceGrid* >::iterator brIt, brEnd = notLocatedBrothers.end();
957     for ( brIt = notLocatedBrothers.begin(); !myRightBrother && brIt != brEnd; ++brIt )
958     {
959       _QuadFaceGrid* brother = *brIt;
960       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
961       DUMP_VERT( "brother left bottom: ", brotherLeftVertex );
962       if ( rightVertex.IsSame( brotherLeftVertex )) {
963         myRightBrother = brother;
964         notLocatedBrothers.erase( myRightBrother );
965       }
966     }
967     // find upper brother
968     TopoDS_Vertex upVertex = GetSide( Q_LEFT ).FirstVertex();
969     DUMP_VERT("1 left up Vertex: ",upVertex);
970     brIt = notLocatedBrothers.begin(), brEnd = notLocatedBrothers.end();
971     for ( ; !myUpBrother && brIt != brEnd; ++brIt )
972     {
973       _QuadFaceGrid* brother = *brIt;
974       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
975       DUMP_VERT("brother left bottom: ", brotherLeftVertex);
976       if ( upVertex.IsSame( brotherLeftVertex )) {
977         myUpBrother = brother;
978         notLocatedBrothers.erase( myUpBrother );
979       }
980     }
981     // recursive call
982     if ( myRightBrother )
983       myRightBrother->setBrothers( notLocatedBrothers );
984     if ( myUpBrother )
985       myUpBrother->setBrothers( notLocatedBrothers );
986   }
987 }
988
989 //================================================================================
990 /*!
991  * \brief Store nodes of a simple face into grid starting from (x,y) position
992  */
993 //================================================================================
994
995 bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
996                              vector<const SMDS_MeshNode*> & theGrid,
997                              const _Indexer&                theIndexer,
998                              int                            theX,
999                              int                            theY)
1000 {
1001   if ( myGrid.empty() && !LoadGrid( theMesh ))
1002     return false;
1003
1004   // store my own grid in the global grid
1005
1006   int fromX = myReverse ? theX - myIndexer._xSize: theX;
1007
1008   for ( int i = 0, x = fromX; i < myIndexer._xSize; ++i, ++x )
1009     for ( int j = 0, y = theY; j < myIndexer._ySize; ++j, ++y )
1010       theGrid[ theIndexer( x, y )] = myGrid[ myIndexer( i, j )];
1011
1012   // store grids of my right and upper brothers
1013
1014   if ( myRightBrother )
1015   {
1016     if ( myReverse )
1017       fromX += 1;
1018     else
1019       fromX += myIndexer._xSize - 1;
1020     if ( !myRightBrother->fillGrid( theMesh, theGrid, theIndexer, fromX, theY ))
1021       return error( myRightBrother->GetError() );
1022   }
1023   if ( myUpBrother )
1024   {
1025     if ( !myUpBrother->fillGrid( theMesh, theGrid, theIndexer,
1026                                  theX, theY + myIndexer._ySize - 1))
1027       return error( myUpBrother->GetError() );
1028   }
1029   return true;
1030 }
1031
1032 //================================================================================
1033 /*!
1034  * \brief Return number of segments on the hirizontal sides
1035  */
1036 //================================================================================
1037
1038 int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
1039 {
1040   int nbSegs = 0;
1041   if ( myLeftBottomChild )
1042   {
1043     nbSegs += myLeftBottomChild->GetNbHoriSegments( mesh, true );
1044   }
1045   else
1046   {
1047     nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments(mesh);
1048     if ( withBrothers && myRightBrother )
1049       nbSegs += myRightBrother->GetNbHoriSegments( mesh, withBrothers );
1050   }
1051   return nbSegs;
1052 }
1053
1054 //================================================================================
1055 /*!
1056  * \brief Return number of segments on the vertical sides
1057  */
1058 //================================================================================
1059
1060 int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
1061 {
1062   int nbSegs = 0;
1063   if ( myLeftBottomChild )
1064   {
1065     nbSegs += myLeftBottomChild->GetNbVertSegments( mesh, true );
1066   }
1067   else
1068   {
1069     nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh);
1070     if ( withBrothers && myUpBrother )
1071       nbSegs += myUpBrother->GetNbVertSegments( mesh, withBrothers );
1072   }
1073   return nbSegs;
1074 }
1075
1076 //================================================================================
1077 /*!
1078  * \brief Return a node by its position
1079  */
1080 //================================================================================
1081
1082 const SMDS_MeshNode* _QuadFaceGrid::GetNode(int iHori, int iVert) const
1083 {
1084   return myGrid[ myIndexer( iHori, iVert )];
1085 }
1086
1087 //================================================================================
1088 /*!
1089  * \brief Return node coordinates by its position
1090  */
1091 //================================================================================
1092
1093 gp_XYZ _QuadFaceGrid::GetXYZ(int iHori, int iVert) const
1094 {
1095   const SMDS_MeshNode* n = myGrid[ myIndexer( iHori, iVert )];
1096   return gp_XYZ( n->X(), n->Y(), n->Z() );
1097 }
1098
1099 //================================================================================
1100 /*!
1101  * \brief Return normal to the face at vertex v
1102  */
1103 //================================================================================
1104
1105 bool _QuadFaceGrid::GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const
1106 {
1107   if ( myChildren.empty() )
1108   {
1109     if ( mySides.Contain( v )) {
1110       try {
1111         gp_Pnt2d uv = BRep_Tool::Parameters( v, myFace );
1112         BRepAdaptor_Surface surface( myFace );
1113         gp_Pnt p; gp_Vec d1u, d1v;
1114         surface.D1( uv.X(), uv.Y(), p, d1u, d1v );
1115         n = d1u.Crossed( d1v );
1116         return true;
1117       }
1118       catch (Standard_Failure) {
1119         return false;
1120       }
1121     }
1122   }
1123   else
1124   {
1125     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1126     for ( ; child != childEnd; ++child )
1127       if ( child->GetNormal( v, n ))
1128         return true;
1129   }
1130   return false;
1131 }
1132
1133 //================================================================================
1134 /*!
1135  * \brief Dumps coordinates of grid nodes
1136  */
1137 //================================================================================
1138
1139 void _QuadFaceGrid::DumpGrid() const
1140 {
1141 #ifdef DEB_GRID
1142   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1143   cout << "****** Face " << names[ myID ] << endl;
1144
1145   if ( myChildren.empty() || !myGrid.empty() )
1146   {
1147     cout << "x size: " << myIndexer._xSize << "; y size: " << myIndexer._ySize << endl;
1148     for ( int y = 0; y < myIndexer._ySize; ++y ) {
1149       cout << "-- row " << y << endl;
1150       for ( int x = 0; x < myIndexer._xSize; ++x ) {
1151         const SMDS_MeshNode* n = myGrid[ myIndexer( x, y ) ];
1152         cout << x << " ( " << n->X() << ", " << n->Y() << ", " << n->Z() << " )" << endl;
1153       }
1154     }
1155   }
1156   else
1157   {
1158     cout << "Nb children: " << myChildren.size() << endl;
1159     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1160     for ( int i=0; child != childEnd; ++child, ++i ) {
1161       cout << "   *** SUBFACE " << i+1 << endl;
1162       ((_QuadFaceGrid&)(*child)).SetID( myID );
1163       child->DumpGrid();
1164     }
1165   }
1166 #endif
1167 }
1168
1169 //================================================================================
1170 /*!
1171  * \brief Dump vertices
1172  */
1173 //================================================================================
1174
1175 void _QuadFaceGrid::DumpVertices() const
1176 {
1177 #ifdef DEB_FACES
1178   cout << "****** Face ";
1179   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1180   if ( myID >= B_BOTTOM && myID < B_BACK )
1181     cout << names[ myID ] << endl;
1182   else
1183     cout << "UNDEFINED" << endl;
1184
1185   if ( myChildren.empty() )
1186   {
1187     for ( int i = 0; i < 4; ++i )
1188     {
1189       cout << "  Side "; mySides.GetSide( i )->Dump();
1190     }
1191   }
1192   else
1193   {
1194     cout << "-- Nb children: " << myChildren.size() << endl;
1195     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1196     for ( int i=0; child != childEnd; ++child, ++i ) {
1197       cout << "   *** SUBFACE " << i+1 << endl;
1198       ((_QuadFaceGrid&)(*child)).SetID( myID );
1199       child->DumpVertices();
1200     }
1201   }
1202 #endif
1203 }
1204
1205 //=======================================================================
1206 //function : _FaceSide
1207 //purpose  : copy constructor
1208 //=======================================================================
1209
1210 _FaceSide::_FaceSide(const _FaceSide& other)
1211 {
1212   myEdge = other.myEdge;
1213   myChildren = other.myChildren;
1214   myNbChildren = other.myNbChildren;
1215   myVertices.Assign( other.myVertices );
1216   myID = other.myID;
1217 }
1218
1219 //================================================================================
1220 /*!
1221  * \brief Construct a face side of one edge
1222  */
1223 //================================================================================
1224
1225 _FaceSide::_FaceSide(const TopoDS_Edge& edge):
1226   myEdge( edge ), myNbChildren(0)
1227 {
1228   if ( !edge.IsNull() )
1229     for ( TopExp_Explorer exp( edge, TopAbs_VERTEX ); exp.More(); exp.Next() )
1230       //myVertices.insert( ptr ( exp.Current() ));
1231       myVertices.Add( exp.Current() );
1232 }
1233
1234 //================================================================================
1235 /*!
1236  * \brief Construct a face side of several edges
1237  */
1238 //================================================================================
1239
1240 _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
1241   myNbChildren(0)
1242 {
1243   list<TopoDS_Edge>::const_iterator edge = edges.begin(), eEnd = edges.end();
1244   for ( ; edge != eEnd; ++edge ) {
1245     myChildren.push_back( _FaceSide( *edge ));
1246     myNbChildren++;
1247 //     myVertices.insert( myChildren.back().myVertices.begin(),
1248 //                        myChildren.back().myVertices.end() );
1249     myVertices.Add( myChildren.back().FirstVertex() );
1250     myVertices.Add( myChildren.back().LastVertex() );
1251     myChildren.back().SetID( Q_CHILD ); // not to splice them
1252   }
1253 }
1254
1255 //=======================================================================
1256 //function : GetSide
1257 //purpose  : 
1258 //=======================================================================
1259
1260 _FaceSide* _FaceSide::GetSide(const int i)
1261 {
1262   if ( i >= myNbChildren )
1263     return 0;
1264
1265   list< _FaceSide >::iterator side = myChildren.begin();
1266   if ( i )
1267     std::advance( side, i );
1268   return & (*side);
1269 }
1270
1271 //=======================================================================
1272 //function : GetSide
1273 //purpose  : 
1274 //=======================================================================
1275
1276 const _FaceSide* _FaceSide::GetSide(const int i) const
1277 {
1278   return const_cast< _FaceSide* >(this)->GetSide(i);
1279 }
1280
1281 //=======================================================================
1282 //function : NbVertices
1283 //purpose  : return nb of vertices in the side
1284 //=======================================================================
1285
1286 int _FaceSide::NbVertices() const
1287 {
1288   if ( myChildren.empty() )
1289     return myVertices.Extent();
1290 //     return myVertices.size();
1291
1292   return myNbChildren + 1;
1293 }
1294
1295 //=======================================================================
1296 //function : FirstVertex
1297 //purpose  : 
1298 //=======================================================================
1299
1300 TopoDS_Vertex _FaceSide::FirstVertex() const
1301 {
1302   if ( myChildren.empty() )
1303     return TopExp::FirstVertex( myEdge, Standard_True );
1304
1305   return myChildren.front().FirstVertex();
1306 }
1307
1308 //=======================================================================
1309 //function : LastVertex
1310 //purpose  : 
1311 //=======================================================================
1312
1313 TopoDS_Vertex _FaceSide::LastVertex() const
1314 {
1315   if ( myChildren.empty() )
1316     return TopExp::LastVertex( myEdge, Standard_True );
1317
1318   return myChildren.back().LastVertex();
1319 }
1320
1321 //=======================================================================
1322 //function : Vertex
1323 //purpose  : 
1324 //=======================================================================
1325
1326 TopoDS_Vertex _FaceSide::Vertex(int i) const
1327 {
1328   if ( myChildren.empty() )
1329     return i ? LastVertex() : FirstVertex();
1330       
1331   if ( i >= myNbChildren )
1332     return myChildren.back().LastVertex();
1333   
1334   return GetSide(i)->FirstVertex();
1335 }
1336
1337 //=======================================================================
1338 //function : Contain
1339 //purpose  : 
1340 //=======================================================================
1341
1342 bool _FaceSide::Contain( const _FaceSide& side, int* which ) const
1343 {
1344   if ( !which || myChildren.empty() )
1345   {
1346     if ( which )
1347       *which = 0;
1348     int nbCommon = 0;
1349 //     set<const TopoDS_TShape*>::iterator v, vEnd = side.myVertices.end();
1350 //     for ( v = side.myVertices.begin(); v != vEnd; ++v )
1351 //       nbCommon += ( myVertices.find( *v ) != myVertices.end() );
1352     TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1353     for ( ; vIt.More(); vIt.Next() )
1354       nbCommon += ( myVertices.Contains( vIt.Key() ));
1355     return (nbCommon > 1);
1356   }
1357   list< _FaceSide >::const_iterator mySide = myChildren.begin(), sideEnd = myChildren.end();
1358   for ( int i = 0; mySide != sideEnd; ++mySide, ++i ) {
1359     if ( mySide->Contain( side )) {
1360       *which = i;
1361       return true;
1362     }
1363   }
1364   return false;
1365 }
1366
1367 //=======================================================================
1368 //function : Contain
1369 //purpose  : 
1370 //=======================================================================
1371
1372 bool _FaceSide::Contain( const TopoDS_Vertex& vertex ) const
1373 {
1374   return myVertices.Contains( vertex );
1375 //   return myVertices.find( ptr( vertex )) != myVertices.end();
1376 }
1377
1378 //=======================================================================
1379 //function : AppendSide
1380 //purpose  : 
1381 //=======================================================================
1382
1383 void _FaceSide::AppendSide( const _FaceSide& side )
1384 {
1385   if ( !myEdge.IsNull() )
1386   {
1387     myChildren.push_back( *this );
1388     myNbChildren = 1;
1389     myEdge.Nullify();
1390   }
1391   myChildren.push_back( side );
1392   myNbChildren++;
1393   //myVertices.insert( side.myVertices.begin(), side.myVertices.end() );
1394   TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1395   for ( ; vIt.More(); vIt.Next() )
1396     myVertices.Add( vIt.Key() );
1397
1398   myID = Q_PARENT;
1399   myChildren.back().SetID( EQuadSides( myNbChildren-1 ));
1400 }
1401
1402 //=======================================================================
1403 //function : SetBottomSide
1404 //purpose  : 
1405 //=======================================================================
1406
1407 void _FaceSide::SetBottomSide( int i )
1408 {
1409   if ( i > 0 && myID == Q_PARENT ) {
1410     list< _FaceSide >::iterator sideEnd, side = myChildren.begin();
1411     std::advance( side, i );
1412     myChildren.splice( myChildren.begin(), myChildren, side, myChildren.end() );
1413
1414     side = myChildren.begin(), sideEnd = myChildren.end();
1415     for ( int i = 0; side != sideEnd; ++side, ++i ) {
1416       side->SetID( EQuadSides(i) );
1417       side->SetBottomSide(i);
1418     }
1419   }
1420 }
1421
1422 //=======================================================================
1423 //function : GetNbSegments
1424 //purpose  : 
1425 //=======================================================================
1426
1427 int _FaceSide::GetNbSegments(SMESH_Mesh& mesh) const
1428 {
1429   int nb = 0;
1430   if ( myChildren.empty() )
1431   {
1432     nb = mesh.GetSubMesh(myEdge)->GetSubMeshDS()->NbElements();
1433   }
1434   else
1435   {
1436     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1437     for ( ; side != sideEnd; ++side )
1438       nb += side->GetNbSegments(mesh);
1439   }
1440   return nb;
1441 }
1442
1443 //=======================================================================
1444 //function : StoreNodes
1445 //purpose  : 
1446 //=======================================================================
1447
1448 bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
1449                            vector<const SMDS_MeshNode*>& myGrid,
1450                            bool                          reverse )
1451 {
1452   list< TopoDS_Edge > edges;
1453   if ( myChildren.empty() )
1454   {
1455     edges.push_back( myEdge );
1456   }
1457   else
1458   {
1459     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1460     for ( ; side != sideEnd; ++side )
1461       if ( reverse )
1462         edges.push_front( side->myEdge );
1463       else
1464         edges.push_back ( side->myEdge );
1465   }
1466   int nbNodes = 0;
1467   list< TopoDS_Edge >::iterator edge = edges.begin(), eEnd = edges.end();
1468   for ( ; edge != eEnd; ++edge )
1469   {
1470     map< double, const SMDS_MeshNode* > nodes;
1471     bool ok = SMESH_Algo::GetSortedNodesOnEdge( mesh.GetMeshDS(),
1472                                                 *edge,
1473                                                 /*ignoreMediumNodes=*/true,
1474                                                 nodes);
1475     if ( !ok ) return false;
1476
1477     bool forward = ( edge->Orientation() == TopAbs_FORWARD );
1478     if ( reverse ) forward = !forward;
1479     if ( forward )
1480     {
1481       map< double, const SMDS_MeshNode* >::iterator u_node, nEnd = nodes.end();
1482       for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
1483         myGrid[ nbNodes++ ] = u_node->second;
1484     }
1485     else 
1486     {
1487       map< double, const SMDS_MeshNode* >::reverse_iterator u_node, nEnd = nodes.rend();
1488       for ( u_node = nodes.rbegin(); u_node != nEnd; ++u_node )
1489         myGrid[ nbNodes++ ] = u_node->second;
1490     }
1491     nbNodes--; // node on vertex present in two adjacent edges
1492   }
1493   return nbNodes > 0;
1494 }
1495
1496 //=======================================================================
1497 //function : Dump
1498 //purpose  : dump end vertices
1499 //=======================================================================
1500
1501 void _FaceSide::Dump() const
1502 {
1503   if ( myChildren.empty() )
1504   {
1505     const char* sideNames[] = { "Q_BOTTOM", "Q_RIGHT", "Q_TOP", "Q_LEFT", "Q_CHILD", "Q_PARENT" };
1506     if ( myID >= Q_BOTTOM && myID < Q_PARENT )
1507       cout << sideNames[ myID ] << endl;
1508     else
1509       cout << "<UNDEFINED ID>" << endl;
1510     TopoDS_Vertex f = FirstVertex();
1511     TopoDS_Vertex l = LastVertex();
1512     gp_Pnt pf = BRep_Tool::Pnt(f);
1513     gp_Pnt pl = BRep_Tool::Pnt(l);
1514     cout << "\t ( "<< ptr( f ) << " - " << ptr( l )<< " )"
1515          << "\t ( "<< pf.X()<<", "<<pf.Y()<<", "<<pf.Z()<<" ) - "
1516          << " ( "<< pl.X()<<", "<<pl.Y()<<", "<<pl.Z()<<" )"<<endl;
1517   }
1518   else
1519   {
1520     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1521     for ( ; side != sideEnd; ++side ) {
1522       side->Dump();
1523       cout << "\t";
1524     }
1525   }
1526 }