Salome HOME
Fix regressions caused by improvements
[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   void 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;
383     TopTools_MapIteratorOfMapOfShape vIt( cornerVV );
384     for ( ; vIt.More(); vIt.Next() )
385     {
386       TopoDS_Shape V0 = vIt.Key();
387       PShapeIteratorPtr riIt = SMESH_MesherHelper::GetAncestors( V0, mesh, TopAbs_EDGE );
388       while ( const TopoDS_Shape* riE = riIt->next() )
389       {
390         if ( !subEE.Contains( *riE ) || !subChecked.Add( *riE ))
391           continue;
392         TopoDS_Edge ridgeE = TopoDS::Edge( *riE );
393         while ( !ridgeE.IsNull() )
394         {
395           TopExp::Vertices( ridgeE, VV[0], VV[1] );
396           TopoDS_Shape V1 = VV[ V0.IsSame( VV[0] )];
397           if ( cornerVV.Contains( V1 ) )
398             break; // ridgeE reached a corner VERTEX
399
400           // detect internal EDGEs among those sharing V1. There can be 2, 3 or 4 EDGEs and
401           // number of internal EDGEs is N-2
402           TopoDS_Shape nextRidgeE;
403           PShapeIteratorPtr eIt = SMESH_MesherHelper::GetAncestors( V1, mesh, TopAbs_EDGE );
404           while ( const TopoDS_Shape* E = eIt->next() )
405           {
406             if ( E->IsSame( ridgeE ) || !subEE.Contains( *E ) || !subChecked.Add( *E ))
407               continue;
408             // look for FACEs sharing E and ridgeE
409             PShapeIteratorPtr fIt = SMESH_MesherHelper::GetAncestors( *E, mesh, TopAbs_FACE );
410             while ( const TopoDS_Shape* F = fIt->next() )
411             {
412               if ( !SMESH_MesherHelper::IsSubShape( ridgeE, *F ))
413                 continue;
414               if ( isContinuousMesh( ridgeE, TopoDS::Edge( *E ), TopoDS::Face( *F ), mesh ))
415               {
416                 nextRidgeE = *E;
417               }
418               else
419               {
420                 internEE.Add( *E );
421               }
422               break;
423             }
424           }
425           // look for the next ridge EDGE
426           if ( nextRidgeE.IsNull() )
427           {
428             eIt = SMESH_MesherHelper::GetAncestors( V1, mesh, TopAbs_EDGE );
429             while ( const TopoDS_Shape* E = eIt->next() )
430               if ( !ridgeE.IsSame( *E ) && !internEE.Contains( *E ) )
431               {
432                 nextRidgeE = *E;
433                 break;
434               }
435           }
436           ridgeE = TopoDS::Edge( nextRidgeE );
437           V0 = V1;
438
439         } // check EDGEs around the last VERTEX of ridgeE 
440       } // loop on ridge EDGEs around a corner VERTEX
441     } // loop on on corner VERTEXes
442
443     return;
444   } // getInternalEdges()
445 } // namespace
446
447 //================================================================================
448 /*!
449  * \brief Tries to find 6 sides of a box
450  */
451 //================================================================================
452
453 bool StdMeshers_CompositeHexa_3D::findBoxFaces( const TopoDS_Shape&    shape,
454                                                 list< _QuadFaceGrid >& boxFaces,
455                                                 SMESH_Mesh&            mesh,
456                                                 _QuadFaceGrid * &      fBottom,
457                                                 _QuadFaceGrid * &      fTop,
458                                                 _QuadFaceGrid * &      fFront,
459                                                 _QuadFaceGrid * &      fBack,
460                                                 _QuadFaceGrid * &      fLeft,
461                                                 _QuadFaceGrid * &      fRight)
462 {
463   TopTools_MapOfShape cornerVertices;
464   getBlockCorners( mesh, shape, cornerVertices );
465   if ( cornerVertices.Extent() != 8 )
466     return false;
467   TopTools_MapOfShape internalEdges;
468   getInternalEdges( mesh, shape, cornerVertices, internalEdges );
469
470   list< _QuadFaceGrid >::iterator boxFace;
471   TopExp_Explorer exp;
472   int nbFaces = 0;
473   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next(), ++nbFaces )
474   {
475     _QuadFaceGrid f;
476     if ( !f.Init( TopoDS::Face( exp.Current() ), mesh ))
477       return error (COMPERR_BAD_SHAPE);
478
479     _QuadFaceGrid* prevContinuous = 0;
480     for ( boxFace = boxFaces.begin(); boxFace != boxFaces.end(); ++boxFace )
481     {
482       if ( prevContinuous )
483       {
484         if ( prevContinuous->AddContinuousFace( *boxFace, internalEdges ))
485           boxFace = --boxFaces.erase( boxFace );
486       }
487       else if ( boxFace->AddContinuousFace( f, internalEdges ))
488       {
489         prevContinuous = & (*boxFace);
490       }
491     }
492     if ( !prevContinuous )
493       boxFaces.push_back( f );
494   }
495   // Check what we have
496   if ( boxFaces.size() != 6 && nbFaces != 6)
497     return error
498       (COMPERR_BAD_SHAPE,
499        SMESH_Comment("Can't find 6 sides of a box. Number of found sides - ")<<boxFaces.size());
500
501   if ( boxFaces.size() != 6 && nbFaces == 6 ) { // strange ordinary box with continuous faces
502     boxFaces.resize( 6 );
503     boxFace = boxFaces.begin();
504     for ( exp.Init( shape, TopAbs_FACE); exp.More(); exp.Next(), ++boxFace )
505       boxFace->Init( TopoDS::Face( exp.Current() ), mesh );
506   }
507   // ----------------------------------------
508   // Find out position of faces within a box
509   // ----------------------------------------
510   // start from a bottom face
511   fBottom = &boxFaces.front();
512   fBottom->SetID( B_BOTTOM );
513   // find vertical faces
514   fFront = fBottom->FindAdjacentForSide( Q_BOTTOM, boxFaces, B_FRONT );
515   fLeft  = fBottom->FindAdjacentForSide( Q_RIGHT,  boxFaces, B_LEFT  );
516   fBack  = fBottom->FindAdjacentForSide( Q_TOP,    boxFaces, B_BACK  );
517   fRight = fBottom->FindAdjacentForSide( Q_LEFT,   boxFaces, B_RIGHT );
518   // check the found
519   if ( !fFront || !fBack || !fLeft || !fRight )
520     return error(COMPERR_BAD_SHAPE);
521   // find a top face
522   fTop = 0;
523   for ( boxFace = ++boxFaces.begin(); boxFace != boxFaces.end() && !fTop; ++boxFace )
524   {
525     fTop = & (*boxFace);
526     fTop->SetID( B_TOP );
527     if ( fTop==fFront || fTop==fLeft || fTop==fBack || fTop==fRight )
528       fTop = 0;
529   }
530   // set bottom of the top side
531   if ( !fTop->SetBottomSide( fFront->GetSide( Q_TOP ) )) {
532     if ( !fFront->IsComplex() )
533       return error( ERR_LI("Error in StdMeshers_CompositeHexa_3D::Compute()"));
534     else {
535       _QuadFaceGrid::TChildIterator chIt = fFront->GetChildren();
536       while ( chIt.more() ) {
537         const _QuadFaceGrid& frontChild = chIt.next();
538         if ( fTop->SetBottomSide( frontChild.GetSide( Q_TOP )))
539           break;
540       }
541     }
542   }
543   if ( !fTop )
544     return error(COMPERR_BAD_SHAPE);
545
546   // orient bottom egde of faces along axes of the unit box
547   fBottom->ReverseEdges();
548   fBack  ->ReverseEdges();
549   fLeft  ->ReverseEdges();
550
551   return true;
552 }
553
554 //================================================================================
555 /*!
556  * \brief Computes hexahedral mesh on a box with composite sides
557  *  \param aMesh - mesh to compute
558  *  \param aShape - shape to mesh
559  *  \retval bool - succes sign
560  */
561 //================================================================================
562
563 bool StdMeshers_CompositeHexa_3D::Compute(SMESH_Mesh&         theMesh,
564                                           const TopoDS_Shape& theShape)
565 {
566   SMESH_MesherHelper helper( theMesh );
567   _quadraticMesh = helper.IsQuadraticSubMesh( theShape );
568   helper.SetElementsOnShape( true );
569
570   // -------------------------
571   // Try to find 6 side faces
572   // -------------------------
573   list< _QuadFaceGrid > boxFaceContainer;
574   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
575   if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh,
576                        fBottom, fTop, fFront, fBack, fLeft, fRight))
577     return false;
578
579   // ------------------------------------------
580   // Fill columns of nodes with existing nodes
581   // ------------------------------------------
582
583   // let faces load their grids
584   if ( !fBottom->LoadGrid( theMesh )) return error( fBottom->GetError() );
585   if ( !fBack  ->LoadGrid( theMesh )) return error( fBack  ->GetError() );
586   if ( !fLeft  ->LoadGrid( theMesh )) return error( fLeft  ->GetError() );
587   if ( !fFront ->LoadGrid( theMesh )) return error( fFront ->GetError() );
588   if ( !fRight ->LoadGrid( theMesh )) return error( fRight ->GetError() );
589   if ( !fTop   ->LoadGrid( theMesh )) return error( fTop   ->GetError() );
590
591   int x, xSize = fBottom->GetNbHoriSegments(theMesh) + 1, X = xSize - 1;
592   int y, ySize = fBottom->GetNbVertSegments(theMesh) + 1, Y = ySize - 1;
593   int z, zSize = fFront ->GetNbVertSegments(theMesh) + 1, Z = zSize - 1;
594   _Indexer colIndex( xSize, ySize );
595   vector< vector< const SMDS_MeshNode* > > columns( colIndex.size() );
596
597   // fill node columns by front and back box sides
598   for ( x = 0; x < xSize; ++x ) {
599     vector< const SMDS_MeshNode* >& column0 = columns[ colIndex( x, 0 )];
600     vector< const SMDS_MeshNode* >& column1 = columns[ colIndex( x, Y )];
601     column0.resize( zSize );
602     column1.resize( zSize );
603     for ( z = 0; z < zSize; ++z ) {
604       column0[ z ] = fFront->GetNode( x, z );
605       column1[ z ] = fBack ->GetNode( x, z );
606     }
607   }
608   // fill node columns by left and right box sides
609   for ( y = 1; y < ySize-1; ++y ) {
610     vector< const SMDS_MeshNode* >& column0 = columns[ colIndex( 0, y )];
611     vector< const SMDS_MeshNode* >& column1 = columns[ colIndex( X, y )];
612     column0.resize( zSize );
613     column1.resize( zSize );
614     for ( z = 0; z < zSize; ++z ) {
615       column0[ z ] = fLeft ->GetNode( y, z );
616       column1[ z ] = fRight->GetNode( y, z );
617     }
618   }
619   // get nodes from top and bottom box sides
620   for ( x = 1; x < xSize-1; ++x ) {
621     for ( y = 1; y < ySize-1; ++y ) {
622       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
623       column.resize( zSize );
624       column.front() = fBottom->GetNode( x, y );
625       column.back()  = fTop   ->GetNode( x, y );
626     }
627   }
628
629   // ----------------------------
630   // Add internal nodes of a box
631   // ----------------------------
632   // projection points of internal nodes on box sub-shapes by which
633   // coordinates of internal nodes are computed
634   vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
635
636   // projections on vertices are constant
637   pointsOnShapes[ SMESH_Block::ID_V000 ] = fBottom->GetXYZ( 0, 0 );
638   pointsOnShapes[ SMESH_Block::ID_V100 ] = fBottom->GetXYZ( X, 0 );
639   pointsOnShapes[ SMESH_Block::ID_V010 ] = fBottom->GetXYZ( 0, Y );
640   pointsOnShapes[ SMESH_Block::ID_V110 ] = fBottom->GetXYZ( X, Y );
641   pointsOnShapes[ SMESH_Block::ID_V001 ] = fTop->GetXYZ( 0, 0 );
642   pointsOnShapes[ SMESH_Block::ID_V101 ] = fTop->GetXYZ( X, 0 );
643   pointsOnShapes[ SMESH_Block::ID_V011 ] = fTop->GetXYZ( 0, Y );
644   pointsOnShapes[ SMESH_Block::ID_V111 ] = fTop->GetXYZ( X, Y );
645
646   for ( x = 1; x < xSize-1; ++x )
647   {
648     gp_XYZ params; // normalized parameters of internal node within a unit box
649     params.SetCoord( 1, x / double(X) );
650     for ( y = 1; y < ySize-1; ++y )
651     {
652       params.SetCoord( 2, y / double(Y) );
653       // column to fill during z loop
654       vector< const SMDS_MeshNode* >& column = columns[ colIndex( x, y )];
655       // points projections on horizontal edges
656       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = fBottom->GetXYZ( x, 0 );
657       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = fBottom->GetXYZ( x, Y );
658       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = fBottom->GetXYZ( 0, y );
659       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = fBottom->GetXYZ( X, y );
660       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = fTop->GetXYZ( x, 0 );
661       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = fTop->GetXYZ( x, Y );
662       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = fTop->GetXYZ( 0, y );
663       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = fTop->GetXYZ( X, y );
664       // points projections on horizontal faces
665       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = fBottom->GetXYZ( x, y );
666       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = fTop   ->GetXYZ( x, y );
667       for ( z = 1; z < zSize-1; ++z ) // z loop
668       {
669         params.SetCoord( 3, z / double(Z) );
670         // point projections on vertical edges
671         pointsOnShapes[ SMESH_Block::ID_E00z ] = fFront->GetXYZ( 0, z );    
672         pointsOnShapes[ SMESH_Block::ID_E10z ] = fFront->GetXYZ( X, z );    
673         pointsOnShapes[ SMESH_Block::ID_E01z ] = fBack->GetXYZ( 0, z );    
674         pointsOnShapes[ SMESH_Block::ID_E11z ] = fBack->GetXYZ( X, z );
675         // point projections on vertical faces
676         pointsOnShapes[ SMESH_Block::ID_Fx0z ] = fFront->GetXYZ( x, z );    
677         pointsOnShapes[ SMESH_Block::ID_Fx1z ] = fBack ->GetXYZ( x, z );    
678         pointsOnShapes[ SMESH_Block::ID_F0yz ] = fLeft ->GetXYZ( y, z );    
679         pointsOnShapes[ SMESH_Block::ID_F1yz ] = fRight->GetXYZ( y, z );
680
681         // compute internal node coordinates
682         gp_XYZ coords;
683         SMESH_Block::ShellPoint( params, pointsOnShapes, coords );
684         column[ z ] = helper.AddNode( coords.X(), coords.Y(), coords.Z() );
685
686 #ifdef DEB_GRID
687         // debug
688         //cout << "----------------------------------------------------------------------"<<endl;
689         //for ( int id = SMESH_Block::ID_V000; id < SMESH_Block::ID_Shell; ++id)
690         //{
691         //  gp_XYZ p = pointsOnShapes[ id ];
692         //  SMESH_Block::DumpShapeID( id,cout)<<" ( "<<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;
693         //}
694         //cout << "Params: ( "<< params.X()<<", "<<params.Y()<<", "<<params.Z()<<" )"<<endl;
695         //cout << "coords: ( "<< coords.X()<<", "<<coords.Y()<<", "<<coords.Z()<<" )"<<endl;
696 #endif
697       }
698     }
699   }
700   // faces no more needed, free memory
701   boxFaceContainer.clear();
702
703   // ----------------
704   // Add hexahedrons
705   // ----------------
706   for ( x = 0; x < xSize-1; ++x ) {
707     for ( y = 0; y < ySize-1; ++y ) {
708       vector< const SMDS_MeshNode* >& col00 = columns[ colIndex( x, y )];
709       vector< const SMDS_MeshNode* >& col10 = columns[ colIndex( x+1, y )];
710       vector< const SMDS_MeshNode* >& col01 = columns[ colIndex( x, y+1 )];
711       vector< const SMDS_MeshNode* >& col11 = columns[ colIndex( x+1, y+1 )];
712       for ( z = 0; z < zSize-1; ++z )
713       {
714         // bottom face normal of a hexa mush point outside the volume
715         helper.AddVolume(col00[z],   col01[z],   col11[z],   col10[z],
716                          col00[z+1], col01[z+1], col11[z+1], col10[z+1]);
717       }
718     }
719   }
720   return true;
721 }
722
723 //================================================================================
724 /*!
725  *  Evaluate
726  */
727 //================================================================================
728
729 bool StdMeshers_CompositeHexa_3D::Evaluate(SMESH_Mesh&         theMesh,
730                                            const TopoDS_Shape& theShape,
731                                            MapShapeNbElems&    aResMap)
732 {
733   // -------------------------
734   // Try to find 6 side faces
735   // -------------------------
736   list< _QuadFaceGrid > boxFaceContainer;
737   _QuadFaceGrid *fBottom, *fTop, *fFront, *fBack, *fLeft, *fRight;
738   if ( ! findBoxFaces( theShape, boxFaceContainer, theMesh,
739                        fBottom, fTop, fFront, fBack, fLeft, fRight))
740     return false;
741
742   // Find a less complex side
743   _QuadFaceGrid * lessComplexSide = & boxFaceContainer.front();
744   list< _QuadFaceGrid >::iterator face = boxFaceContainer.begin();
745   for ( ++face; face != boxFaceContainer.end() && lessComplexSide->IsComplex(); ++face )
746     if ( face->NbChildren() < lessComplexSide->NbChildren() )
747       lessComplexSide = & *face;
748
749   // Get an 1D size of lessComplexSide
750   int nbSeg1 = 0;
751   vector<TopoDS_Edge> edges;
752   if ( !lessComplexSide->GetHoriEdges(edges) )
753     return false;
754   for ( size_t i = 0; i < edges.size(); ++i )
755   {
756     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( edges[i] )];
757     if ( !nbElems.empty() )
758       nbSeg1 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
759   }
760
761   // Get an 1D size of a box side ortogonal to lessComplexSide
762   int nbSeg2 = 0;
763   _QuadFaceGrid* ortoSide =
764     lessComplexSide->FindAdjacentForSide( Q_LEFT, boxFaceContainer, B_UNDEFINED );
765   edges.clear();
766   if ( !ortoSide || !ortoSide->GetHoriEdges(edges) ) return false;
767   for ( size_t i = 0; i < edges.size(); ++i )
768   {
769     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( edges[i] )];
770     if ( !nbElems.empty() )
771       nbSeg2 += Max( nbElems[ SMDSEntity_Edge ], nbElems[ SMDSEntity_Quad_Edge ]);
772   }
773
774   // Get an 2D size of a box side ortogonal to lessComplexSide
775   int nbFaces = 0, nbQuadFace = 0;
776   list< TopoDS_Face > sideFaces;
777   if ( ortoSide->IsComplex() )
778     for ( _QuadFaceGrid::TChildIterator child = ortoSide->GetChildren(); child.more(); )
779       sideFaces.push_back( child.next().GetFace() );
780   else
781     sideFaces.push_back( ortoSide->GetFace() );
782   //
783   list< TopoDS_Face >::iterator f = sideFaces.begin();
784   for ( ; f != sideFaces.end(); ++f )
785   {
786     const vector<int>& nbElems = aResMap[ theMesh.GetSubMesh( *f )];
787     if ( !nbElems.empty() )
788     {
789       nbFaces    = nbElems[ SMDSEntity_Quadrangle ];
790       nbQuadFace = nbElems[ SMDSEntity_Quad_Quadrangle ];
791     }
792   }
793
794   // Fill nb of elements
795   vector<int> aResVec(SMDSEntity_Last,0);
796   int nbSeg3 = ( nbFaces + nbQuadFace ) / nbSeg2;
797   aResVec[SMDSEntity_Node]       = (nbSeg1-1) * (nbSeg2-1) * (nbSeg3-1);
798   aResVec[SMDSEntity_Hexa]       = nbSeg1 * nbFaces;
799   aResVec[SMDSEntity_Quad_Hexa]  = nbSeg1 * nbQuadFace;
800
801   aResMap.insert( make_pair( theMesh.GetSubMesh(theShape), aResVec ));
802
803   return true;
804 }
805
806
807 //================================================================================
808 /*!
809  * \brief constructor of non-initialized _QuadFaceGrid
810  */
811 //================================================================================
812
813 _QuadFaceGrid::_QuadFaceGrid():
814   myReverse(false), myRightBrother(0), myUpBrother(0), myIndexer(0,0), myID(B_UNDEFINED)
815 {
816 }
817
818 //================================================================================
819 /*!
820  * \brief Initialization
821  */
822 //================================================================================
823
824 bool _QuadFaceGrid::Init(const TopoDS_Face& f, SMESH_Mesh& mesh)
825 {
826   myFace         = f;
827   mySides        = _FaceSide();
828   myReverse      = false;
829   myLeftBottomChild = myRightBrother = myUpBrother = 0;
830   myChildren.clear();
831   myGrid.clear();
832   //if ( myFace.Orientation() != TopAbs_FORWARD )
833     //myFace.Reverse();
834
835   list< TopoDS_Edge > edges;
836   list< int > nbEdgesInWire;
837   int nbWire = SMESH_Block::GetOrderedEdges (myFace, edges, nbEdgesInWire);
838   if ( nbWire != 1 )
839     return false;
840
841   list< TopoDS_Edge >::iterator edgeIt = edges.begin();
842   if ( nbEdgesInWire.front() == 4 ) // exactly 4 edges
843   {
844     for ( ; edgeIt != edges.end(); ++edgeIt )
845       mySides.AppendSide( _FaceSide( *edgeIt ));
846   }
847   else if ( nbEdgesInWire.front() > 4 ) { // more than 4 edges - try to unite some
848     list< TopoDS_Edge > sideEdges;
849     while ( !edges.empty()) {
850       sideEdges.clear();
851       sideEdges.splice( sideEdges.end(), edges, edges.begin());// edges.front()->sideEdges.back()
852       while ( !edges.empty() ) {
853         if ( SMESH_Algo::IsContinuous( sideEdges.back(), edges.front() )) {
854           sideEdges.splice( sideEdges.end(), edges, edges.begin());
855         }
856         else if ( SMESH_Algo::IsContinuous( sideEdges.front(), edges.back() )) {
857           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
858         }
859         else if ( isContinuousMesh( sideEdges.back(), edges.front(), f, mesh )) {
860           sideEdges.splice( sideEdges.end(), edges, edges.begin());
861         }
862         else if ( isContinuousMesh( sideEdges.front(), edges.back(), f, mesh )) {
863           sideEdges.splice( sideEdges.begin(), edges, --edges.end());
864         }
865         else {
866           break;
867         }
868       }
869       mySides.AppendSide( _FaceSide( sideEdges ));
870     }
871   }
872   if (mySides.size() != 4)
873     return false;
874
875 #ifdef _DEBUG_
876   mySides.GetSide( Q_BOTTOM )->SetID( Q_BOTTOM );
877   mySides.GetSide( Q_RIGHT  )->SetID( Q_RIGHT );
878   mySides.GetSide( Q_TOP    )->SetID( Q_TOP );
879   mySides.GetSide( Q_LEFT   )->SetID( Q_LEFT );
880 #endif
881
882   return true;
883 }
884
885 //================================================================================
886 /*!
887  * \brief Try to unite self with other ordinary face
888  */
889 //================================================================================
890
891 bool _QuadFaceGrid::AddContinuousFace( const _QuadFaceGrid&       other,
892                                        const TopTools_MapOfShape& internalEdges)
893 {
894   for ( int i = 0; i < 4; ++i )
895   {
896     const _FaceSide& otherSide = other.GetSide( i );
897     int iMyCommon;
898     if ( mySides.Contain( otherSide, &iMyCommon ) )
899     {
900       if ( internalEdges.Contains( otherSide.Edge( 0 )))
901       {
902         DUMP_VERT("Cont 1", mySides.GetSide(iMyCommon)->FirstVertex());
903         DUMP_VERT("Cont 2", mySides.GetSide(iMyCommon)->LastVertex());
904         DUMP_VERT("Cont 3", otherSide.FirstVertex());
905         DUMP_VERT("Cont 4", otherSide.LastVertex());
906         if ( myChildren.empty() ) {
907           myChildren.push_back( *this );
908           myFace.Nullify();
909         }
910
911         // orient new children equally
912         int otherBottomIndex = ( 4 + i - iMyCommon + 2 ) % 4;
913         if ( other.IsComplex() )
914           for ( TChildIterator children = other.GetChildren(); children.more(); ) {
915             myChildren.push_back( children.next() );
916             myChildren.back().SetBottomSide( myChildren.back().GetSide( otherBottomIndex ));
917           }
918         else {
919           myChildren.push_back( other );
920           myChildren.back().SetBottomSide( myChildren.back().GetSide( otherBottomIndex ));
921         }
922
923         myLeftBottomChild = 0;
924
925         // collect vertices in mySides
926         if ( other.IsComplex() )
927           for ( TChildIterator children = other.GetChildren(); children.more(); )
928           {
929             const _QuadFaceGrid& child =  children.next();
930             for ( int i = 0; i < 4; ++i )
931               mySides.AppendSide( child.GetSide(i) );
932           }
933         else
934           for ( int i = 0; i < 4; ++i )
935             mySides.AppendSide( other.GetSide(i) );
936
937         return true;
938       }
939     }
940   }
941   return false;
942 }
943
944 //================================================================================
945 /*!
946  * \brief Try to set the side as bottom hirizontal side
947  */
948 //================================================================================
949
950 bool _QuadFaceGrid::SetBottomSide(const _FaceSide& bottom, int* sideIndex)
951 {
952   myLeftBottomChild = myRightBrother = myUpBrother = 0;
953
954   int myBottomIndex;
955   if ( myChildren.empty() )
956   {
957     if ( mySides.Contain( bottom, &myBottomIndex )) {
958       mySides.SetBottomSide( myBottomIndex );
959       if ( sideIndex )
960         *sideIndex = myBottomIndex;
961       return true;
962     }
963   }
964   else
965   {
966     TChildren::iterator childFace = myChildren.begin(), childEnd = myChildren.end();
967     for ( ; childFace != childEnd; ++childFace )
968     {
969       if ( childFace->SetBottomSide( bottom, &myBottomIndex ))
970       {
971         TChildren::iterator orientedCild = childFace;
972         for ( childFace = myChildren.begin(); childFace != childEnd; ++childFace ) {
973           if ( childFace != orientedCild )
974             childFace->SetBottomSide( childFace->GetSide( myBottomIndex ));
975         }
976         if ( sideIndex )
977           *sideIndex = myBottomIndex;
978         return true;
979       }
980     }
981   }
982   return false;
983 }
984
985 //================================================================================
986 /*!
987  * \brief Return face adjacent to i-th side of this face, (0<i<4)
988  */
989 //================================================================================
990
991 _QuadFaceGrid* _QuadFaceGrid::FindAdjacentForSide(int                  i,
992                                                   list<_QuadFaceGrid>& faces,
993                                                   EBoxSides            id) const
994 {
995   const _FaceSide & iSide = GetSide( i );
996   list< _QuadFaceGrid >::iterator boxFace = faces.begin();
997   for ( ; boxFace != faces.end(); ++boxFace )
998   {
999     _QuadFaceGrid* f  = & (*boxFace);
1000     if ( f != this && f->SetBottomSide( iSide ))
1001       return f->SetID( id ), f;
1002   }
1003   return (_QuadFaceGrid*) 0;
1004 }
1005
1006 //================================================================================
1007 /*!
1008  * \brief Return i-th side
1009  */
1010 //================================================================================
1011
1012 const _FaceSide& _QuadFaceGrid::GetSide(int i) const
1013 {
1014   if ( myChildren.empty() )
1015     return *mySides.GetSide(i);
1016
1017   _QuadFaceGrid* me = const_cast<_QuadFaceGrid*>(this);
1018   if ( !me->locateChildren() || !myLeftBottomChild )
1019     return *mySides.GetSide(i);
1020
1021   const _QuadFaceGrid* child = myLeftBottomChild;
1022   switch ( i ){
1023   case Q_BOTTOM:
1024   case Q_LEFT:
1025     break;
1026   case Q_RIGHT:
1027     while ( child->myRightBrother )
1028       child = child->myRightBrother;
1029     break;
1030   case Q_TOP:
1031     while ( child->myUpBrother )
1032       child = child->myUpBrother;
1033     break;
1034   default: ;
1035   }
1036   return child->GetSide( i );
1037 }
1038
1039 //================================================================================
1040 /*!
1041  * \brief Reverse edges in order to have them oriented along axes of the unit box
1042  */
1043 //================================================================================
1044
1045 void _QuadFaceGrid::ReverseEdges(/*int e1, int e2*/)
1046 {
1047   myReverse = !myReverse;
1048
1049 // #ifdef DEB_FACES
1050 //   if ( !myFace.IsNull() )
1051 //     TopAbs::Print(myFace.Orientation(), cout);
1052 // #endif
1053
1054   if ( myChildren.empty() )
1055   {
1056 //     mySides.GetSide( e1 )->Reverse();
1057 //     mySides.GetSide( e2 )->Reverse();
1058     DumpVertices();
1059   }
1060   else
1061   {
1062     DumpVertices();
1063     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1064     for ( ; child != childEnd; ++child )
1065       child->ReverseEdges( /*e1, e2*/ );
1066   }
1067 }
1068
1069 //================================================================================
1070 /*!
1071  * \brief Load nodes of a mesh
1072  */
1073 //================================================================================
1074
1075 bool _QuadFaceGrid::LoadGrid( SMESH_Mesh& mesh )
1076 {
1077   if ( !myChildren.empty() )
1078   {
1079     // Let child faces load their grids
1080     TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1081     for ( ; child != childEnd; ++child ) {
1082       child->SetID( myID );
1083       if ( !child->LoadGrid( mesh ) )
1084         return error( child->GetError() );
1085     }
1086     // Fill myGrid with nodes of patches
1087     return loadCompositeGrid( mesh );
1088   }
1089
1090   // ---------------------------------------
1091   // Fill myGrid with nodes bound to myFace
1092   // ---------------------------------------
1093
1094   if ( !myGrid.empty() )
1095     return true;
1096
1097   SMESHDS_SubMesh* faceSubMesh = mesh.GetSubMesh( myFace )->GetSubMeshDS();
1098   // check that all faces are quadrangular
1099   SMDS_ElemIteratorPtr fIt = faceSubMesh->GetElements();
1100   while ( fIt->more() )
1101     if ( fIt->next()->NbNodes() % 4 > 0 )
1102       return error("Non-quadrangular mesh faces are not allowed on sides of a composite block");
1103   
1104   myIndexer._xSize = 1 + mySides.GetSide( Q_BOTTOM )->GetNbSegments( mesh );
1105   myIndexer._ySize = 1 + mySides.GetSide( Q_LEFT   )->GetNbSegments( mesh );
1106
1107   myGrid.resize( myIndexer.size() );
1108
1109   // strore nodes bound to the bottom edge
1110   mySides.GetSide( Q_BOTTOM )->StoreNodes( mesh, myGrid, myReverse );
1111
1112   // store the rest nodes row by row
1113
1114   const SMDS_MeshNode* dummy = mesh.GetMeshDS()->AddNode(0,0,0);
1115   const SMDS_MeshElement* firstQuad = dummy; // most left face above the last row of found nodes
1116   
1117   int nbFoundNodes = myIndexer._xSize;
1118   while ( nbFoundNodes != myGrid.size() )
1119   {
1120     // first and last nodes of the last filled row of nodes
1121     const SMDS_MeshNode* n1down = myGrid[ nbFoundNodes - myIndexer._xSize ];
1122     const SMDS_MeshNode* n2down = myGrid[ nbFoundNodes - myIndexer._xSize + 1];
1123     const SMDS_MeshNode* n1downLast = myGrid[ nbFoundNodes-1 ];
1124
1125     // find the first face above the row by the first two left nodes
1126     //
1127     // n1up     n2up
1128     //     o---o
1129     //     |   |
1130     //     o---o  o  o  o  o
1131     //n1down    n2down
1132     //
1133     TIDSortedElemSet emptySet, avoidSet;
1134     avoidSet.insert( firstQuad );
1135     firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
1136     while ( firstQuad && !faceSubMesh->Contains( firstQuad )) {
1137       avoidSet.insert( firstQuad );
1138       firstQuad = SMESH_MeshAlgos::FindFaceInSet( n1down, n2down, emptySet, avoidSet);
1139     }
1140     if ( !firstQuad || !faceSubMesh->Contains( firstQuad ))
1141       return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
1142
1143     // find the node of quad bound to the left geom edge
1144     int i2down = firstQuad->GetNodeIndex( n2down );
1145     const SMDS_MeshNode* n1up = firstQuad->GetNode(( i2down+2 ) % 4 );
1146     myGrid[ nbFoundNodes++ ] = n1up;
1147     // the 4-the node of the first quad
1148     int i1down = firstQuad->GetNodeIndex( n1down );
1149     const SMDS_MeshNode* n2up = firstQuad->GetNode(( i1down+2 ) % 4 );
1150     myGrid[ nbFoundNodes++ ] = n2up;
1151
1152     n1down = n2down;
1153     n1up   = n2up;
1154     const SMDS_MeshElement* quad = firstQuad;
1155
1156     // find the rest nodes by remaining faces above the row
1157     //
1158     //             n1up
1159     //     o---o--o
1160     //     |   |  | ->
1161     //     o---o--o  o  o  o
1162     //                      n1downLast
1163     //
1164     while ( n1down != n1downLast )
1165     {
1166       // next face
1167       avoidSet.clear(); avoidSet.insert( quad );
1168       quad = SMESH_MeshAlgos::FindFaceInSet( n1down, n1up, emptySet, avoidSet );
1169       if ( !quad || quad->NbNodes() % 4 > 0)
1170         return error(ERR_LI("Error in _QuadFaceGrid::LoadGrid()"));
1171
1172       // next node
1173       if ( quad->GetNode( i1down ) != n1down ) // check already found index
1174         i1down = quad->GetNodeIndex( n1down );
1175       n2up = quad->GetNode(( i1down+2 ) % 4 );
1176       myGrid[ nbFoundNodes++ ] = n2up;
1177
1178       n1down = myGrid[ nbFoundNodes - myIndexer._xSize - 1 ];
1179       n1up   = n2up;
1180     }
1181   }
1182   mesh.GetMeshDS()->RemoveNode(dummy);
1183   DumpGrid(); // debug
1184
1185   return true;
1186 }
1187
1188 //================================================================================
1189 /*!
1190  * \brief Find out mutual location of children: find their right and up brothers
1191  */
1192 //================================================================================
1193
1194 bool _QuadFaceGrid::locateChildren()
1195 {
1196   if ( myLeftBottomChild )
1197     return true;
1198
1199   TChildren::iterator child = myChildren.begin(), childEnd = myChildren.end();
1200
1201   // find a child sharing it's first bottom vertex with no other brother
1202   myLeftBottomChild = 0;
1203   for ( ; !myLeftBottomChild && child != childEnd; ++child )
1204   {
1205     TopoDS_Vertex leftVertex = child->GetSide( Q_BOTTOM ).FirstVertex();
1206     bool sharedVertex = false;
1207     TChildren::iterator otherChild = myChildren.begin();
1208     for ( ; otherChild != childEnd && !sharedVertex; ++otherChild )
1209       if ( otherChild != child )
1210         sharedVertex = otherChild->mySides.Contain( leftVertex );
1211     if ( !sharedVertex ) {
1212       myLeftBottomChild = & (*child);
1213       DUMP_VERT("0 left bottom Vertex: ",leftVertex );
1214     }
1215   }
1216   if (!myLeftBottomChild)
1217     return error(ERR_LI("Error in locateChildren()"));
1218
1219   set< _QuadFaceGrid* > notLocatedChilren;
1220   for (child = myChildren.begin() ; child != childEnd; ++child )
1221     notLocatedChilren.insert( & (*child));
1222
1223   // connect myLeftBottomChild to it's right and upper brothers
1224   notLocatedChilren.erase( myLeftBottomChild );
1225   myLeftBottomChild->setBrothers( notLocatedChilren );
1226   if ( !notLocatedChilren.empty() )
1227     return error(ERR_LI("Error in locateChildren()"));
1228
1229   return true;
1230 }
1231
1232 //================================================================================
1233 /*!
1234  * \brief Fill myGrid with nodes of patches
1235  */
1236 //================================================================================
1237
1238 bool _QuadFaceGrid::loadCompositeGrid(SMESH_Mesh& mesh)
1239 {
1240   // Find out mutual location of children: find their right and up brothers
1241   if ( !locateChildren() )
1242     return false;
1243
1244   // Load nodes according to mutual location of children
1245
1246   // grid size
1247   myIndexer._xSize = 1 + myLeftBottomChild->GetNbHoriSegments(mesh, /*withBrothers=*/true);
1248   myIndexer._ySize = 1 + myLeftBottomChild->GetNbVertSegments(mesh, /*withBrothers=*/true);
1249
1250   myGrid.resize( myIndexer.size() );
1251
1252   int fromX = myReverse ? myIndexer._xSize : 0;
1253   if (!myLeftBottomChild->fillGrid( mesh, myGrid, myIndexer, fromX, 0 ))
1254     return error( myLeftBottomChild->GetError() );
1255
1256   DumpGrid();
1257
1258   return true;
1259 }
1260
1261 //================================================================================
1262 /*!
1263  * \brief Find right an upper brothers among notLocatedBrothers
1264  */
1265 //================================================================================
1266
1267 void _QuadFaceGrid::setBrothers( set< _QuadFaceGrid* >& notLocatedBrothers )
1268 {
1269   if ( !notLocatedBrothers.empty() )
1270   {
1271     // find right brother
1272     TopoDS_Vertex rightVertex = GetSide( Q_BOTTOM ).LastVertex();
1273     DUMP_VERT("1 right bottom Vertex: ",rightVertex );
1274     set< _QuadFaceGrid* >::iterator brIt, brEnd = notLocatedBrothers.end();
1275     for ( brIt = notLocatedBrothers.begin(); brIt != brEnd; ++brIt )
1276     {
1277       _QuadFaceGrid* brother = *brIt;
1278       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1279       DUMP_VERT( "brother left bottom: ", brotherLeftVertex );
1280       if ( rightVertex.IsSame( brotherLeftVertex )) {
1281         myRightBrother = brother;
1282         notLocatedBrothers.erase( brIt );
1283         break;
1284       }
1285     }
1286     // find upper brother
1287     TopoDS_Vertex upVertex = GetSide( Q_LEFT ).FirstVertex();
1288     DUMP_VERT("1 left up Vertex: ",upVertex);
1289     brIt = notLocatedBrothers.begin(), brEnd = notLocatedBrothers.end();
1290     for ( ; brIt != brEnd; ++brIt )
1291     {
1292       _QuadFaceGrid* brother = *brIt;
1293       TopoDS_Vertex brotherLeftVertex = brother->GetSide( Q_BOTTOM ).FirstVertex();
1294       DUMP_VERT("brother left bottom: ", brotherLeftVertex);
1295       if ( upVertex.IsSame( brotherLeftVertex )) {
1296         myUpBrother = brother;
1297         notLocatedBrothers.erase( myUpBrother );
1298         break;
1299       }
1300     }
1301     // recursive call
1302     if ( myRightBrother )
1303       myRightBrother->setBrothers( notLocatedBrothers );
1304     if ( myUpBrother )
1305       myUpBrother->setBrothers( notLocatedBrothers );
1306   }
1307 }
1308
1309 //================================================================================
1310 /*!
1311  * \brief Store nodes of a simple face into grid starting from (x,y) position
1312  */
1313 //================================================================================
1314
1315 bool _QuadFaceGrid::fillGrid(SMESH_Mesh&                    theMesh,
1316                              vector<const SMDS_MeshNode*> & theGrid,
1317                              const _Indexer&                theIndexer,
1318                              int                            theX,
1319                              int                            theY)
1320 {
1321   if ( myGrid.empty() && !LoadGrid( theMesh ))
1322     return false;
1323
1324   // store my own grid in the global grid
1325
1326   int fromX = myReverse ? theX - myIndexer._xSize: theX;
1327
1328   for ( int i = 0, x = fromX; i < myIndexer._xSize; ++i, ++x )
1329     for ( int j = 0, y = theY; j < myIndexer._ySize; ++j, ++y )
1330       theGrid[ theIndexer( x, y )] = myGrid[ myIndexer( i, j )];
1331
1332   // store grids of my right and upper brothers
1333
1334   if ( myRightBrother )
1335   {
1336     if ( myReverse )
1337       fromX += 1;
1338     else
1339       fromX += myIndexer._xSize - 1;
1340     if ( !myRightBrother->fillGrid( theMesh, theGrid, theIndexer, fromX, theY ))
1341       return error( myRightBrother->GetError() );
1342   }
1343   if ( myUpBrother )
1344   {
1345     if ( !myUpBrother->fillGrid( theMesh, theGrid, theIndexer,
1346                                  theX, theY + myIndexer._ySize - 1))
1347       return error( myUpBrother->GetError() );
1348   }
1349   return true;
1350 }
1351
1352 //================================================================================
1353 /*!
1354  * \brief Return number of segments on the hirizontal sides
1355  */
1356 //================================================================================
1357
1358 int _QuadFaceGrid::GetNbHoriSegments(SMESH_Mesh& mesh, bool withBrothers) const
1359 {
1360   int nbSegs = 0;
1361   if ( myLeftBottomChild )
1362   {
1363     nbSegs += myLeftBottomChild->GetNbHoriSegments( mesh, true );
1364   }
1365   else
1366   {
1367     nbSegs = mySides.GetSide( Q_BOTTOM )->GetNbSegments(mesh);
1368     if ( withBrothers && myRightBrother )
1369       nbSegs += myRightBrother->GetNbHoriSegments( mesh, withBrothers );
1370   }
1371   return nbSegs;
1372 }
1373
1374 //================================================================================
1375 /*!
1376  * \brief Return number of segments on the vertical sides
1377  */
1378 //================================================================================
1379
1380 int _QuadFaceGrid::GetNbVertSegments(SMESH_Mesh& mesh, bool withBrothers) const
1381 {
1382   int nbSegs = 0;
1383   if ( myLeftBottomChild )
1384   {
1385     nbSegs += myLeftBottomChild->GetNbVertSegments( mesh, true );
1386   }
1387   else
1388   {
1389     nbSegs = mySides.GetSide( Q_LEFT )->GetNbSegments(mesh);
1390     if ( withBrothers && myUpBrother )
1391       nbSegs += myUpBrother->GetNbVertSegments( mesh, withBrothers );
1392   }
1393   return nbSegs;
1394 }
1395
1396 //================================================================================
1397 /*!
1398  * \brief Return edge on the hirizontal bottom sides
1399  */
1400 //================================================================================
1401
1402 int _QuadFaceGrid::GetHoriEdges(vector<TopoDS_Edge> & edges) const
1403 {
1404   if ( myLeftBottomChild )
1405   {
1406     return myLeftBottomChild->GetHoriEdges( edges );
1407   }
1408   else
1409   {
1410     const _FaceSide* bottom  = mySides.GetSide( Q_BOTTOM );
1411     int i = 0;
1412     while ( true ) {
1413       TopoDS_Edge e = bottom->Edge( i++ );
1414       if ( e.IsNull() )
1415         break;
1416       else
1417         edges.push_back( e );
1418     }
1419     if ( myRightBrother )
1420       myRightBrother->GetHoriEdges( edges );
1421   }
1422   return edges.size();
1423 }
1424
1425 //================================================================================
1426 /*!
1427  * \brief Return a node by its position
1428  */
1429 //================================================================================
1430
1431 const SMDS_MeshNode* _QuadFaceGrid::GetNode(int iHori, int iVert) const
1432 {
1433   return myGrid[ myIndexer( iHori, iVert )];
1434 }
1435
1436 //================================================================================
1437 /*!
1438  * \brief Return node coordinates by its position
1439  */
1440 //================================================================================
1441
1442 gp_XYZ _QuadFaceGrid::GetXYZ(int iHori, int iVert) const
1443 {
1444   const SMDS_MeshNode* n = myGrid[ myIndexer( iHori, iVert )];
1445   return gp_XYZ( n->X(), n->Y(), n->Z() );
1446 }
1447
1448 //================================================================================
1449 /*!
1450  * \brief Return normal to the face at vertex v
1451  */
1452 //================================================================================
1453
1454 bool _QuadFaceGrid::GetNormal( const TopoDS_Vertex& v, gp_Vec& n ) const
1455 {
1456   if ( myChildren.empty() )
1457   {
1458     if ( mySides.Contain( v )) {
1459       try {
1460         gp_Pnt2d uv = BRep_Tool::Parameters( v, myFace );
1461         BRepAdaptor_Surface surface( myFace );
1462         gp_Pnt p; gp_Vec d1u, d1v;
1463         surface.D1( uv.X(), uv.Y(), p, d1u, d1v );
1464         n = d1u.Crossed( d1v );
1465         return true;
1466       }
1467       catch (Standard_Failure) {
1468         return false;
1469       }
1470     }
1471   }
1472   else
1473   {
1474     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1475     for ( ; child != childEnd; ++child )
1476       if ( child->GetNormal( v, n ))
1477         return true;
1478   }
1479   return false;
1480 }
1481
1482 //================================================================================
1483 /*!
1484  * \brief Dumps coordinates of grid nodes
1485  */
1486 //================================================================================
1487
1488 void _QuadFaceGrid::DumpGrid() const
1489 {
1490 #ifdef DEB_GRID
1491   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1492   cout << "****** Face " << names[ myID ] << endl;
1493
1494   if ( myChildren.empty() || !myGrid.empty() )
1495   {
1496     cout << "x size: " << myIndexer._xSize << "; y size: " << myIndexer._ySize << endl;
1497     for ( int y = 0; y < myIndexer._ySize; ++y ) {
1498       cout << "-- row " << y << endl;
1499       for ( int x = 0; x < myIndexer._xSize; ++x ) {
1500         const SMDS_MeshNode* n = myGrid[ myIndexer( x, y ) ];
1501         cout << x << " ( " << n->X() << ", " << n->Y() << ", " << n->Z() << " )" << endl;
1502       }
1503     }
1504   }
1505   else
1506   {
1507     cout << "Nb children: " << myChildren.size() << endl;
1508     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1509     for ( int i=0; child != childEnd; ++child, ++i ) {
1510       cout << "   *** SUBFACE " << i+1 << endl;
1511       ((_QuadFaceGrid&)(*child)).SetID( myID );
1512       child->DumpGrid();
1513     }
1514   }
1515 #endif
1516 }
1517
1518 //================================================================================
1519 /*!
1520  * \brief Dump vertices
1521  */
1522 //================================================================================
1523
1524 void _QuadFaceGrid::DumpVertices() const
1525 {
1526 #ifdef DEB_FACES
1527   cout << "****** Face ";
1528   const char* names[] = { "B_BOTTOM", "B_RIGHT", "B_TOP", "B_LEFT", "B_FRONT", "B_BACK" };
1529   if ( myID >= B_BOTTOM && myID < B_BACK )
1530     cout << names[ myID ] << endl;
1531   else
1532     cout << "UNDEFINED" << endl;
1533
1534   if ( myChildren.empty() )
1535   {
1536     for ( int i = 0; i < 4; ++i )
1537     {
1538       cout << "  Side "; mySides.GetSide( i )->Dump();
1539     }
1540   }
1541   else
1542   {
1543     cout << "-- Nb children: " << myChildren.size() << endl;
1544     TChildren::const_iterator child = myChildren.begin(), childEnd = myChildren.end();
1545     for ( int i=0; child != childEnd; ++child, ++i ) {
1546       cout << "   *** SUBFACE " << i+1 << endl;
1547       ((_QuadFaceGrid&)(*child)).SetID( myID );
1548       child->DumpVertices();
1549     }
1550   }
1551 #endif
1552 }
1553
1554 //=======================================================================
1555 //function : _FaceSide
1556 //purpose  : copy constructor
1557 //=======================================================================
1558
1559 _FaceSide::_FaceSide(const _FaceSide& other)
1560 {
1561   myEdge = other.myEdge;
1562   myChildren = other.myChildren;
1563   myNbChildren = other.myNbChildren;
1564   myVertices.Assign( other.myVertices );
1565   myID = other.myID;
1566 }
1567
1568 //================================================================================
1569 /*!
1570  * \brief Construct a face side of one edge
1571  */
1572 //================================================================================
1573
1574 _FaceSide::_FaceSide(const TopoDS_Edge& edge):
1575   myEdge( edge ), myNbChildren(0)
1576 {
1577   if ( !edge.IsNull() )
1578     for ( TopExp_Explorer exp( edge, TopAbs_VERTEX ); exp.More(); exp.Next() )
1579       //myVertices.insert( ptr ( exp.Current() ));
1580       myVertices.Add( exp.Current() );
1581 }
1582
1583 //================================================================================
1584 /*!
1585  * \brief Construct a face side of several edges
1586  */
1587 //================================================================================
1588
1589 _FaceSide::_FaceSide(const list<TopoDS_Edge>& edges):
1590   myNbChildren(0)
1591 {
1592   list<TopoDS_Edge>::const_iterator edge = edges.begin(), eEnd = edges.end();
1593   for ( ; edge != eEnd; ++edge ) {
1594     myChildren.push_back( _FaceSide( *edge ));
1595     myNbChildren++;
1596 //     myVertices.insert( myChildren.back().myVertices.begin(),
1597 //                        myChildren.back().myVertices.end() );
1598     myVertices.Add( myChildren.back().FirstVertex() );
1599     myVertices.Add( myChildren.back().LastVertex() );
1600     myChildren.back().SetID( Q_CHILD ); // not to splice them
1601   }
1602 }
1603
1604 //=======================================================================
1605 //function : GetSide
1606 //purpose  : 
1607 //=======================================================================
1608
1609 _FaceSide* _FaceSide::GetSide(const int i)
1610 {
1611   if ( i >= myNbChildren )
1612     return 0;
1613
1614   list< _FaceSide >::iterator side = myChildren.begin();
1615   if ( i )
1616     std::advance( side, i );
1617   return & (*side);
1618 }
1619
1620 //=======================================================================
1621 //function : GetSide
1622 //purpose  : 
1623 //=======================================================================
1624
1625 const _FaceSide* _FaceSide::GetSide(const int i) const
1626 {
1627   return const_cast< _FaceSide* >(this)->GetSide(i);
1628 }
1629
1630 //=======================================================================
1631 //function : NbVertices
1632 //purpose  : return nb of vertices in the side
1633 //=======================================================================
1634
1635 int _FaceSide::NbVertices() const
1636 {
1637   if ( myChildren.empty() )
1638     return myVertices.Extent();
1639
1640   return myNbChildren + 1;
1641 }
1642
1643 //=======================================================================
1644 //function : NbCommonVertices
1645 //purpose  : Returns number of my vertices common with the given ones
1646 //=======================================================================
1647
1648 int _FaceSide::NbCommonVertices( const TopTools_MapOfShape& VV ) const
1649 {
1650   int nbCommon = 0;
1651   TopTools_MapIteratorOfMapOfShape vIt ( myVertices );
1652   for ( ; vIt.More(); vIt.Next() )
1653     nbCommon += ( VV.Contains( vIt.Key() ));
1654
1655   return nbCommon;
1656 }
1657
1658 //=======================================================================
1659 //function : FirstVertex
1660 //purpose  :
1661 //=======================================================================
1662
1663 TopoDS_Vertex _FaceSide::FirstVertex() const
1664 {
1665   if ( myChildren.empty() )
1666     return TopExp::FirstVertex( myEdge, Standard_True );
1667
1668   return myChildren.front().FirstVertex();
1669 }
1670
1671 //=======================================================================
1672 //function : LastVertex
1673 //purpose  : 
1674 //=======================================================================
1675
1676 TopoDS_Vertex _FaceSide::LastVertex() const
1677 {
1678   if ( myChildren.empty() )
1679     return TopExp::LastVertex( myEdge, Standard_True );
1680
1681   return myChildren.back().LastVertex();
1682 }
1683
1684 //=======================================================================
1685 //function : Vertex
1686 //purpose  : 
1687 //=======================================================================
1688
1689 TopoDS_Vertex _FaceSide::Vertex(int i) const
1690 {
1691   if ( myChildren.empty() )
1692     return i ? LastVertex() : FirstVertex();
1693       
1694   if ( i >= myNbChildren )
1695     return myChildren.back().LastVertex();
1696   
1697   return GetSide(i)->FirstVertex();
1698 }
1699
1700 //================================================================================
1701 /*!
1702  * \brief Return i-the zero-based edge of the side
1703  */
1704 //================================================================================
1705
1706 TopoDS_Edge _FaceSide::Edge(int i) const
1707 {
1708   if ( i == 0 && !myEdge.IsNull() )
1709     return myEdge;
1710
1711   if ( const _FaceSide* iSide = GetSide( i ))
1712     return iSide->myEdge;
1713
1714   return TopoDS_Edge();
1715 }
1716
1717 //=======================================================================
1718 //function : Contain
1719 //purpose  : 
1720 //=======================================================================
1721
1722 bool _FaceSide::Contain( const _FaceSide& side, int* which ) const
1723 {
1724   if ( !which || myChildren.empty() )
1725   {
1726     if ( which )
1727       *which = 0;
1728     int nbCommon = 0;
1729     TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1730     for ( ; vIt.More(); vIt.Next() )
1731       nbCommon += ( myVertices.Contains( vIt.Key() ));
1732     return (nbCommon > 1);
1733   }
1734   list< _FaceSide >::const_iterator mySide = myChildren.begin(), sideEnd = myChildren.end();
1735   for ( int i = 0; mySide != sideEnd; ++mySide, ++i ) {
1736     if ( mySide->Contain( side )) {
1737       *which = i;
1738       return true;
1739     }
1740   }
1741   return false;
1742 }
1743
1744 //=======================================================================
1745 //function : Contain
1746 //purpose  : 
1747 //=======================================================================
1748
1749 bool _FaceSide::Contain( const TopoDS_Vertex& vertex ) const
1750 {
1751   return myVertices.Contains( vertex );
1752 }
1753
1754 //=======================================================================
1755 //function : AppendSide
1756 //purpose  : 
1757 //=======================================================================
1758
1759 void _FaceSide::AppendSide( const _FaceSide& side )
1760 {
1761   if ( !myEdge.IsNull() )
1762   {
1763     myChildren.push_back( *this );
1764     myNbChildren = 1;
1765     myEdge.Nullify();
1766   }
1767   myChildren.push_back( side );
1768   myNbChildren++;
1769   TopTools_MapIteratorOfMapOfShape vIt ( side.myVertices );
1770   for ( ; vIt.More(); vIt.Next() )
1771     myVertices.Add( vIt.Key() );
1772
1773   myID = Q_PARENT;
1774   myChildren.back().SetID( EQuadSides( myNbChildren-1 ));
1775 }
1776
1777 //=======================================================================
1778 //function : SetBottomSide
1779 //purpose  : 
1780 //=======================================================================
1781
1782 void _FaceSide::SetBottomSide( int i )
1783 {
1784   if ( i > 0 && myID == Q_PARENT ) {
1785     list< _FaceSide >::iterator sideEnd, side = myChildren.begin();
1786     std::advance( side, i );
1787     myChildren.splice( myChildren.begin(), myChildren, side, myChildren.end() );
1788
1789     side = myChildren.begin(), sideEnd = myChildren.end();
1790     for ( int i = 0; side != sideEnd; ++side, ++i ) {
1791       side->SetID( EQuadSides(i) );
1792       side->SetBottomSide(i);
1793     }
1794   }
1795 }
1796
1797 //=======================================================================
1798 //function : GetNbSegments
1799 //purpose  : 
1800 //=======================================================================
1801
1802 int _FaceSide::GetNbSegments(SMESH_Mesh& mesh) const
1803 {
1804   int nb = 0;
1805   if ( myChildren.empty() )
1806   {
1807     nb = mesh.GetSubMesh(myEdge)->GetSubMeshDS()->NbElements();
1808   }
1809   else
1810   {
1811     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1812     for ( ; side != sideEnd; ++side )
1813       nb += side->GetNbSegments(mesh);
1814   }
1815   return nb;
1816 }
1817
1818 //=======================================================================
1819 //function : StoreNodes
1820 //purpose  : 
1821 //=======================================================================
1822
1823 bool _FaceSide::StoreNodes(SMESH_Mesh&                   mesh,
1824                            vector<const SMDS_MeshNode*>& myGrid,
1825                            bool                          reverse )
1826 {
1827   list< TopoDS_Edge > edges;
1828   if ( myChildren.empty() )
1829   {
1830     edges.push_back( myEdge );
1831   }
1832   else
1833   {
1834     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1835     for ( ; side != sideEnd; ++side )
1836       if ( reverse )
1837         edges.push_front( side->myEdge );
1838       else
1839         edges.push_back ( side->myEdge );
1840   }
1841   int nbNodes = 0;
1842   list< TopoDS_Edge >::iterator edge = edges.begin(), eEnd = edges.end();
1843   for ( ; edge != eEnd; ++edge )
1844   {
1845     map< double, const SMDS_MeshNode* > nodes;
1846     bool ok = SMESH_Algo::GetSortedNodesOnEdge( mesh.GetMeshDS(),
1847                                                 *edge,
1848                                                 /*ignoreMediumNodes=*/true,
1849                                                 nodes);
1850     if ( !ok ) return false;
1851
1852     bool forward = ( edge->Orientation() == TopAbs_FORWARD );
1853     if ( reverse ) forward = !forward;
1854     if ( forward )
1855     {
1856       map< double, const SMDS_MeshNode* >::iterator u_node, nEnd = nodes.end();
1857       for ( u_node = nodes.begin(); u_node != nEnd; ++u_node )
1858         myGrid[ nbNodes++ ] = u_node->second;
1859     }
1860     else 
1861     {
1862       map< double, const SMDS_MeshNode* >::reverse_iterator u_node, nEnd = nodes.rend();
1863       for ( u_node = nodes.rbegin(); u_node != nEnd; ++u_node )
1864         myGrid[ nbNodes++ ] = u_node->second;
1865     }
1866     nbNodes--; // node on vertex present in two adjacent edges
1867   }
1868   return nbNodes > 0;
1869 }
1870
1871 //=======================================================================
1872 //function : Dump
1873 //purpose  : dump end vertices
1874 //=======================================================================
1875
1876 void _FaceSide::Dump() const
1877 {
1878   if ( myChildren.empty() )
1879   {
1880     const char* sideNames[] = { "Q_BOTTOM", "Q_RIGHT", "Q_TOP", "Q_LEFT", "Q_CHILD", "Q_PARENT" };
1881     if ( myID >= Q_BOTTOM && myID < Q_PARENT )
1882       cout << sideNames[ myID ] << endl;
1883     else
1884       cout << "<UNDEFINED ID>" << endl;
1885     TopoDS_Vertex f = FirstVertex();
1886     TopoDS_Vertex l = LastVertex();
1887     gp_Pnt pf = BRep_Tool::Pnt(f);
1888     gp_Pnt pl = BRep_Tool::Pnt(l);
1889     cout << "\t ( "<< ptr( f ) << " - " << ptr( l )<< " )"
1890          << "\t ( "<< pf.X()<<", "<<pf.Y()<<", "<<pf.Z()<<" ) - "
1891          << " ( "<< pl.X()<<", "<<pl.Y()<<", "<<pl.Z()<<" )"<<endl;
1892   }
1893   else
1894   {
1895     list< _FaceSide >::const_iterator side = myChildren.begin(), sideEnd = myChildren.end();
1896     for ( ; side != sideEnd; ++side ) {
1897       side->Dump();
1898       cout << "\t";
1899     }
1900   }
1901 }