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