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