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