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