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