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