Salome HOME
Join modifications from BR_Dev_For_4_0 tag V4_1_1.
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 //  SMESH SMESH : implementaion of SMESH idl descriptions
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 // File      : StdMeshers_Prism_3D.cxx
25 // Module    : SMESH
26 // Created   : Fri Oct 20 11:37:07 2006
27 // Author    : Edward AGAPOV (eap)
28
29
30 #include "StdMeshers_Prism_3D.hxx"
31
32 #include "StdMeshers_ProjectionUtils.hxx"
33 #include "SMESH_MeshEditor.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMDS_VolumeOfNodes.hxx"
36 #include "SMDS_EdgePosition.hxx"
37 #include "SMESH_Comment.hxx"
38
39 #include "utilities.h"
40
41 #include <BRep_Tool.hxx>
42 #include <Geom2dAdaptor_Curve.hxx>
43 #include <Geom2d_Line.hxx>
44 #include <TopExp.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
47 #include <TopoDS.hxx>
48
49 using namespace std;
50
51 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
52 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
53 #define SHOWYXZ(msg, xyz) // {\
54 // gp_Pnt p (xyz); \
55 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
56 // }
57
58 typedef StdMeshers_ProjectionUtils TAssocTool;
59 typedef SMESH_Comment              TCom;
60
61 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
62        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
63        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
64        NB_WALL_FACES = 4 }; //
65
66 namespace {
67
68   //================================================================================
69   /*!
70    * \brief Return iterator pointing to node column for the given parameter
71    * \param columnsMap - node column map
72    * \param parameter - parameter
73    * \retval TParam2ColumnMap::iterator - result
74    *
75    * it returns closest left column
76    */
77   //================================================================================
78
79   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
80                              const double            parameter )
81   {
82     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
83     if ( u_col != columnsMap->begin() )
84       --u_col;
85     return u_col; // return left column
86   }
87
88   //================================================================================
89   /*!
90    * \brief Return nodes around given parameter and a ratio
91    * \param column - node column
92    * \param param - parameter
93    * \param node1 - lower node
94    * \param node2 - upper node
95    * \retval double - ratio
96    */
97   //================================================================================
98
99   double getRAndNodes( const TNodeColumn*     column,
100                        const double           param,
101                        const SMDS_MeshNode* & node1,
102                        const SMDS_MeshNode* & node2)
103   {
104     if ( param >= 1.0 || column->size() == 1) {
105       node1 = node2 = column->back();
106       return 0;
107     }
108
109     int i = int( param * ( column->size() - 1 ));
110     double u0 = double( i )/ double( column->size() - 1 );
111     double r = ( param - u0 ) * ( column->size() - 1 );
112
113     node1 = (*column)[ i ];
114     node2 = (*column)[ i + 1];
115     return r;
116   }
117
118   //================================================================================
119   /*!
120    * \brief Compute boundary parameters of face parts
121     * \param nbParts - nb of parts to split columns into
122     * \param columnsMap - node columns of the face to split
123     * \param params - computed parameters
124    */
125   //================================================================================
126
127   void splitParams( const int               nbParts,
128                     const TParam2ColumnMap* columnsMap,
129                     vector< double > &      params)
130   {
131     params.clear();
132     params.reserve( nbParts + 1 );
133     TParam2ColumnIt last_par_col = --columnsMap->end();
134     double par = columnsMap->begin()->first; // 0.
135     double parLast = last_par_col->first;
136     params.push_back( par );
137     for ( int i = 0; i < nbParts - 1; ++ i )
138     {
139       double partSize = ( parLast - par ) / double ( nbParts - i );
140       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
141       if ( par_col->first == par ) {
142         ++par_col;
143         if ( par_col == last_par_col ) {
144           while ( i < nbParts - 1 )
145             params.push_back( par + partSize * i++ );
146           break;
147         }
148       }
149       par = par_col->first;
150       params.push_back( par );
151     }
152     params.push_back( parLast ); // 1.
153   }
154 }
155
156 //=======================================================================
157 //function : StdMeshers_Prism_3D
158 //purpose  : 
159 //=======================================================================
160
161 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
162   :SMESH_3D_Algo(hypId, studyId, gen)
163 {
164   _name = "Prism_3D";
165   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);       // 1 bit per shape type
166   myProjectTriangles = false;
167 }
168
169 //================================================================================
170 /*!
171  * \brief Destructor
172  */
173 //================================================================================
174
175 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
176 {}
177
178 //=======================================================================
179 //function : CheckHypothesis
180 //purpose  : 
181 //=======================================================================
182
183 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
184                                           const TopoDS_Shape&                  aShape,
185                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
186 {
187   // Check shape geometry
188 /*  PAL16229
189   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
190
191   // find not quadrangle faces
192   list< TopoDS_Shape > notQuadFaces;
193   int nbEdge, nbWire, nbFace = 0;
194   TopExp_Explorer exp( aShape, TopAbs_FACE );
195   for ( ; exp.More(); exp.Next() ) {
196     ++nbFace;
197     const TopoDS_Shape& face = exp.Current();
198     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
199     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
200     if (  nbEdge!= 4 || nbWire!= 1 ) {
201       if ( !notQuadFaces.empty() ) {
202         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
203              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
204           RETURN_BAD_RESULT("Different not quad faces");
205       }
206       notQuadFaces.push_back( face );
207     }
208   }
209   if ( !notQuadFaces.empty() )
210   {
211     if ( notQuadFaces.size() != 2 )
212       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
213
214     // check total nb faces
215     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
216     if ( nbFace != nbEdge + 2 )
217       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
218   }
219 */
220   // no hypothesis
221   aStatus = SMESH_Hypothesis::HYP_OK;
222   return true;
223 }
224
225 //=======================================================================
226 //function : Compute
227 //purpose  : 
228 //=======================================================================
229
230 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
231 {
232   SMESH_MesherHelper helper( theMesh );
233   myHelper = &helper;
234
235   myHelper->IsQuadraticSubMesh( theShape );
236
237   // Analyse mesh and geomerty to find block subshapes and submeshes
238   if ( !myBlock.Init( myHelper, theShape ))
239     return error( myBlock.GetError());
240
241   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
242
243   int volumeID = meshDS->ShapeToIndex( theShape );
244
245
246   // To compute coordinates of a node inside a block, it is necessary to know
247   // 1. normalized parameters of the node by which
248   // 2. coordinates of node projections on all block sub-shapes are computed
249
250   // So we fill projections on vertices at once as they are same for all nodes
251   myShapeXYZ.resize( myBlock.NbSubShapes() );
252   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
253     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
254     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
255   }
256
257   // Projections on the top and bottom faces are taken from nodes existing
258   // on these faces; find correspondence between bottom and top nodes
259   myBotToColumnMap.clear();
260   if ( !assocOrProjBottom2Top() ) // it also fill myBotToColumnMap
261     return false;
262
263
264   // Create nodes inside the block
265
266   // loop on nodes inside the bottom face
267   TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
268   for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
269   {
270     const TNode& tBotNode = bot_column->first; // bottom TNode
271     if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
272       continue; // node is not inside face 
273
274     // column nodes; middle part of the column are zero pointers
275     TNodeColumn& column = bot_column->second;
276
277     // bottom node parameters and coords
278     myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
279     gp_XYZ botParams          = tBotNode.GetParams();
280
281     // compute top node parameters
282     myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
283     gp_XYZ topParams = botParams;
284     topParams.SetZ( 1 );
285     if ( column.size() > 2 ) {
286       gp_Pnt topCoords = myShapeXYZ[ ID_TOP_FACE ];
287       if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
288         return error(TCom("Can't compute normalized parameters ")
289                      << "for node " << column.back()->GetID()
290                      << " on the face #"<< column.back()->GetPosition()->GetShapeId() );
291     }
292
293     // vertical loop
294     TNodeColumn::iterator columnNodes = column.begin();
295     for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
296     {
297       const SMDS_MeshNode* & node = *columnNodes;
298       if ( node ) continue; // skip bottom or top node
299
300       // params of a node to create
301       double rz = (double) z / (double) ( column.size() - 1 );
302       gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
303
304       // set coords on all faces and nodes
305       const int nbSideFaces = 4;
306       int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
307                                        SMESH_Block::ID_Fx1z,
308                                        SMESH_Block::ID_F0yz,
309                                        SMESH_Block::ID_F1yz };
310       for ( int iF = 0; iF < nbSideFaces; ++iF )
311         if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
312           return false;
313
314       // compute coords for a new node
315       gp_XYZ coords;
316       if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
317         return error("Can't compute coordinates by normalized parameters");
318
319       SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
320       SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
321       SHOWYXZ("ShellPoint ",coords);
322
323       // create a node
324       node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
325       meshDS->SetNodeInVolume( node, volumeID );
326     }
327   } // loop on bottom nodes
328
329
330   // Create volumes
331
332   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
333   if ( !smDS ) return error(COMPERR_BAD_INPUT_MESH, "Null submesh");
334
335   // loop on bottom mesh faces
336   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
337   while ( faceIt->more() )
338   {
339     const SMDS_MeshElement* face = faceIt->next();
340     if ( !face || face->GetType() != SMDSAbs_Face )
341       continue;
342     int nbNodes = face->NbNodes();
343     if ( face->IsQuadratic() )
344       nbNodes /= 2;
345
346     // find node columns for each node
347     vector< const TNodeColumn* > columns( nbNodes );
348     for ( int i = 0; i < nbNodes; ++i )
349     {
350       const SMDS_MeshNode* n = face->GetNode( i );
351       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
352         bot_column = myBotToColumnMap.find( n );
353         if ( bot_column == myBotToColumnMap.end() )
354           return error(TCom("No nodes found above node ") << n->GetID() );
355         columns[ i ] = & bot_column->second;
356       }
357       else {
358         columns[ i ] = myBlock.GetNodeColumn( n );
359         if ( !columns[ i ] )
360           return error(TCom("No side nodes found above node ") << n->GetID() );
361       }
362     }
363     // create prisms
364     AddPrisms( columns, myHelper );
365
366   } // loop on bottom mesh faces
367         
368   return true;
369 }
370
371 //================================================================================
372 /*!
373  * \brief Create prisms
374  * \param columns - columns of nodes generated from nodes of a mesh face
375  * \param helper - helper initialized by mesh and shape to add prisms to
376  */
377 //================================================================================
378
379 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
380                                      SMESH_MesherHelper*          helper)
381 {
382   SMESHDS_Mesh * meshDS = helper->GetMeshDS();
383   int shapeID = helper->GetSubShapeID();
384
385   int nbNodes = columns.size();
386   int nbZ     = columns[0]->size();
387   if ( nbZ < 2 ) return;
388
389   // find out orientation
390   bool isForward = true;
391   SMDS_VolumeTool vTool;
392   int z = 1;
393   switch ( nbNodes ) {
394   case 3: {
395     const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
396                                          (*columns[1])[z-1],
397                                          (*columns[2])[z-1] };
398     const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
399                                          (*columns[1])[z],
400                                          (*columns[2])[z] };
401     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2],
402                                 topNodes[0], topNodes[1], topNodes[2]);
403     vTool.Set( &tmpVol );
404     isForward  = vTool.IsForward();
405     break;
406   }
407   case 4: {
408     const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
409                                          (*columns[2])[z-1], (*columns[3])[z-1] };
410     const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
411                                          (*columns[2])[z], (*columns[3])[z] };
412     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
413                                 topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
414     vTool.Set( &tmpVol );
415     isForward  = vTool.IsForward();
416     break;
417   }
418   }
419
420   // vertical loop on columns
421   for ( z = 1; z < nbZ; ++z )
422   {
423     SMDS_MeshElement* vol = 0;
424     switch ( nbNodes ) {
425
426     case 3: {
427       const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
428                                            (*columns[1])[z-1],
429                                            (*columns[2])[z-1] };
430       const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
431                                            (*columns[1])[z],
432                                            (*columns[2])[z] };
433       if ( isForward )
434         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2],
435                                  topNodes[0], topNodes[1], topNodes[2]);
436       else
437         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2],
438                                  botNodes[0], botNodes[1], botNodes[2]);
439       break;
440       }
441     case 4: {
442       const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
443                                            (*columns[2])[z-1], (*columns[3])[z-1] };
444       const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
445                                            (*columns[2])[z], (*columns[3])[z] };
446       if ( isForward )
447         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
448                                  topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
449       else
450         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2], topNodes[3],
451                                  botNodes[0], botNodes[1], botNodes[2], botNodes[3]);
452       break;
453       }
454     default:
455       // polyhedron
456       vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
457       vector<int> quantities( 2 + nbNodes, 4 );
458       quantities[0] = quantities[1] = nbNodes;
459       columns.resize( nbNodes + 1 );
460       columns[ nbNodes ] = columns[ 0 ];
461       for ( int i = 0; i < nbNodes; ++i ) {
462         nodes[ i         ] = (*columns[ i ])[z-1]; // bottom
463         nodes[ i+nbNodes ] = (*columns[ i ])[z  ]; // top
464         // side
465         int di = 2*nbNodes + 4*i - 1;
466         nodes[ di   ] = (*columns[i  ])[z-1];
467         nodes[ di+1 ] = (*columns[i+1])[z-1];
468         nodes[ di+2 ] = (*columns[i+1])[z  ];
469         nodes[ di+3 ] = (*columns[i  ])[z  ];
470       }
471       vol = meshDS->AddPolyhedralVolume( nodes, quantities );
472     }
473     if ( vol && shapeID > 0 )
474       meshDS->SetMeshElementOnShape( vol, shapeID );
475   }
476 }
477
478 //================================================================================
479 /*!
480  * \brief Find correspondence between bottom and top nodes
481  *  If elements on the bottom and top faces are topologically different,
482  *  and projection is possible and allowed, perform the projection
483  *  \retval bool - is a success or not
484  */
485 //================================================================================
486
487 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
488 {
489   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
490   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
491
492   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
493   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
494
495   if ( !botSMDS || botSMDS->NbElements() == 0 )
496     return error(TCom("No elememts on face #") << botSM->GetId());
497
498   bool needProject = false;
499   if ( !topSMDS || 
500        botSMDS->NbElements() != topSMDS->NbElements() ||
501        botSMDS->NbNodes()    != topSMDS->NbNodes())
502   {
503     if ( myBlock.HasNotQuadElemOnTop() )
504       return error(TCom("Mesh on faces #") << botSM->GetId()
505                    <<" and #"<< topSM->GetId() << " seems different" );
506     needProject = true;
507   }
508
509   if ( 0/*needProject && !myProjectTriangles*/ )
510     return error(TCom("Mesh on faces #") << botSM->GetId()
511                  <<" and #"<< topSM->GetId() << " seems different" );
512   ///RETURN_BAD_RESULT("Need to project but not allowed");
513
514   if ( needProject )
515   {
516     return projectBottomToTop();
517   }
518
519   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
520   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
521   // associate top and bottom faces
522   TAssocTool::TShapeShapeMap shape2ShapeMap;
523   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
524                                              topFace, myBlock.Mesh(),
525                                              shape2ShapeMap) )
526     return error(TCom("Topology of faces #") << botSM->GetId()
527                  <<" and #"<< topSM->GetId() << " seems different" );
528
529   // Find matching nodes of top and bottom faces
530   TNodeNodeMap n2nMap;
531   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
532                                                topFace, myBlock.Mesh(),
533                                                shape2ShapeMap, n2nMap ))
534     return error(TCom("Mesh on faces #") << botSM->GetId()
535                  <<" and #"<< topSM->GetId() << " seems different" );
536
537   // Fill myBotToColumnMap
538
539   int zSize = myBlock.VerticalSize();
540   TNode prevTNode;
541   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
542   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
543   {
544     const SMDS_MeshNode* botNode = bN_tN->first;
545     const SMDS_MeshNode* topNode = bN_tN->second;
546     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
547       continue; // wall columns are contained in myBlock
548     // compute bottom node params
549     TNode bN( botNode );
550     if ( zSize > 2 ) {
551       gp_XYZ paramHint(-1,-1,-1);
552       if ( prevTNode.IsNeighbor( bN ))
553         paramHint = prevTNode.GetParams();
554       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
555                                        ID_BOT_FACE, paramHint ))
556         return error(TCom("Can't compute normalized parameters for node ")
557                      << botNode->GetID() << " on the face #"<< botSM->GetId() );
558       prevTNode = bN;
559     }
560     // create node column
561     TNode2ColumnMap::iterator bN_col = 
562       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
563     TNodeColumn & column = bN_col->second;
564     column.resize( zSize );
565     column.front() = botNode;
566     column.back()  = topNode;
567   }
568   return true;
569 }
570
571 //================================================================================
572 /*!
573  * \brief Remove quadrangles from the top face and
574  * create triangles there by projection from the bottom
575  * \retval bool - a success or not
576  */
577 //================================================================================
578
579 bool StdMeshers_Prism_3D::projectBottomToTop()
580 {
581   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
582   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
583
584   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
585   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
586
587   if ( topSMDS )
588     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
589
590   SMESHDS_Mesh* meshDS = myBlock.MeshDS();
591   int shapeID = myHelper->GetSubShapeID();
592   int topFaceID = meshDS->ShapeToIndex( topSM->GetSubShape() );
593
594   // Fill myBotToColumnMap
595
596   int zSize = myBlock.VerticalSize();
597   TNode prevTNode;
598   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
599   while ( nIt->more() )
600   {
601     const SMDS_MeshNode* botNode = nIt->next();
602     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
603       continue; // strange
604     // compute bottom node params
605     TNode bN( botNode );
606     gp_XYZ paramHint(-1,-1,-1);
607     if ( prevTNode.IsNeighbor( bN ))
608       paramHint = prevTNode.GetParams();
609     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
610                                      ID_BOT_FACE, paramHint ))
611       return error(TCom("Can't compute normalized parameters for node ")
612                    << botNode->GetID() << " on the face #"<< botSM->GetId() );
613     prevTNode = bN;
614     // compute top node coords
615     gp_XYZ topXYZ; gp_XY topUV;
616     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
617          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
618       return error(TCom("Can't compute coordinates "
619                         "by normalized parameters on the face #")<< topSM->GetId() );
620     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
621     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
622     // create node column
623     TNode2ColumnMap::iterator bN_col = 
624       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
625     TNodeColumn & column = bN_col->second;
626     column.resize( zSize );
627     column.front() = botNode;
628     column.back()  = topNode;
629   }
630
631   // Create top faces
632
633   // loop on bottom mesh faces
634   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
635   while ( faceIt->more() )
636   {
637     const SMDS_MeshElement* face = faceIt->next();
638     if ( !face || face->GetType() != SMDSAbs_Face )
639       continue;
640     int nbNodes = face->NbNodes();
641     if ( face->IsQuadratic() )
642       nbNodes /= 2;
643
644     // find top node in columns for each bottom node
645     vector< const SMDS_MeshNode* > nodes( nbNodes );
646     for ( int i = 0; i < nbNodes; ++i )
647     {
648       const SMDS_MeshNode* n = face->GetNode( nbNodes - i - 1 );
649       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
650         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
651         if ( bot_column == myBotToColumnMap.end() )
652           return error(TCom("No nodes found above node ") << n->GetID() );
653         nodes[ i ] = bot_column->second.back();
654       }
655       else {
656         const TNodeColumn* column = myBlock.GetNodeColumn( n );
657         if ( !column )
658           return error(TCom("No side nodes found above node ") << n->GetID() );
659         nodes[ i ] = column->back();
660       }
661     }
662     // create a face, with reversed orientation
663     SMDS_MeshElement* newFace = 0;
664     switch ( nbNodes ) {
665
666     case 3: {
667       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
668       break;
669       }
670     case 4: {
671       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
672       break;
673       }
674     default:
675       newFace = meshDS->AddPolygonalFace( nodes );
676     }
677     if ( newFace && shapeID > 0 )
678       meshDS->SetMeshElementOnShape( newFace, shapeID );
679   }
680
681   return true;
682 }
683
684 //================================================================================
685 /*!
686  * \brief Set projection coordinates of a node to a face and it's subshapes
687  * \param faceID - the face given by in-block ID
688  * \param params - node normalized parameters
689  * \retval bool - is a success
690  */
691 //================================================================================
692
693 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
694 {
695   // find base and top edges of the face
696   enum { BASE = 0, TOP, LEFT, RIGHT };
697   vector< int > edgeVec; // 0-base, 1-top
698   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
699
700   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
701   myBlock.EdgePoint( edgeVec[ TOP ], params, myShapeXYZ[ edgeVec[ TOP ]]);
702
703   SHOWYXZ("\nparams ", params);
704   SHOWYXZ("TOP is "<<edgeVec[ TOP], myShapeXYZ[ edgeVec[ TOP]]);
705   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
706
707   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
708   {
709     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
710     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
711
712     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
713     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
714   }
715   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
716   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
717
718   return true;
719 }
720
721 //================================================================================
722 /*!
723  * \brief Return true if this node and other one belong to one face
724  */
725 //================================================================================
726
727 bool TNode::IsNeighbor( const TNode& other ) const
728 {
729   if ( !other.myNode || !myNode ) return false;
730
731   SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
732   while ( fIt->more() )
733     if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
734       return true;
735   return false;
736 }
737
738 //================================================================================
739 /*!
740  * \brief Constructor. Initialization is needed
741  */
742 //================================================================================
743
744 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
745 {
746   mySide = 0;
747 }
748
749 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
750 {
751   if ( mySide ) {
752     delete mySide; mySide = 0;
753   }
754 }
755
756 //================================================================================
757 /*!
758  * \brief Initialization.
759  * \param helper - helper loaded with mesh and 3D shape
760  * \param shape3D - a closed shell or solid
761  * \retval bool - false if a mesh or a shape are KO
762  */
763 //================================================================================
764
765 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper* helper,
766                                    const TopoDS_Shape& shape3D)
767 {
768   if ( mySide ) {
769     delete mySide; mySide = 0;
770   }
771   vector< TSideFace* > sideFaces( NB_WALL_FACES, 0 );
772   vector< pair< double, double> > params ( NB_WALL_FACES );
773   mySide = new TSideFace( sideFaces, params );
774
775   myHelper = helper;
776   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
777
778   SMESH_Block::init();
779   myShapeIDMap.Clear();
780   myShapeIndex2ColumnMap.clear();
781   
782   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
783     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
784     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
785   };
786
787   myError = SMESH_ComputeError::New();
788
789   // -------------------------------------------------------------
790   // Look for top and bottom faces: not quadrangle ones or meshed
791   // with not quadrangle elements
792   // -------------------------------------------------------------
793
794   list< SMESH_subMesh* > notQuadGeomSubMesh;
795   list< SMESH_subMesh* > notQuadElemSubMesh;
796   int nbFaces = 0;
797   //
798   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
799   if ( !mainSubMesh ) return error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D");
800
801   // analyse face submeshes
802   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,false);
803   while ( smIt->more() )
804   {
805     SMESH_subMesh* sm = smIt->next();
806     const TopoDS_Shape& face = sm->GetSubShape();
807     if ( face.ShapeType() != TopAbs_FACE )
808       continue;
809     nbFaces++;
810
811     // is quadrangle face?
812     list< TopoDS_Edge > orderedEdges;
813     list< int >         nbEdgesInWires;
814     TopoDS_Vertex       V000;
815     int nbWires = GetOrderedEdges( TopoDS::Face( face ),
816                                    V000, orderedEdges, nbEdgesInWires );
817     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
818       notQuadGeomSubMesh.push_back( sm );
819
820     // look for not quadrangle mesh elements
821     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() ) {
822       bool hasNotQuad = false;
823       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
824       while ( eIt->more() && !hasNotQuad ) {
825         const SMDS_MeshElement* elem = eIt->next();
826         if ( elem->GetType() == SMDSAbs_Face ) {
827           int nbNodes = elem->NbNodes();
828           if ( elem->IsQuadratic() )
829             nbNodes /= 2;
830           hasNotQuad = ( nbNodes != 4 );
831         }
832       }
833       if ( hasNotQuad )
834         notQuadElemSubMesh.push_back( sm );
835     }
836     else {
837       return error(COMPERR_BAD_INPUT_MESH,TCom("Not meshed face #")<<sm->GetId());
838     }
839     // check if a quadrangle face is meshed with a quadranglar grid
840     if ( notQuadGeomSubMesh.back() != sm &&
841          notQuadElemSubMesh.back() != sm )
842     {
843       // count nb edges on face sides
844       vector< int > nbEdges;
845       nbEdges.reserve( nbEdgesInWires.front() );
846       for ( list< TopoDS_Edge >::iterator edge = orderedEdges.begin();
847             edge != orderedEdges.end(); ++edge )
848       {
849         if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edge ))
850           nbEdges.push_back ( smDS->NbElements() );
851         else
852           nbEdges.push_back ( 0 );
853       }
854       int nbQuads = sm->GetSubMeshDS()->NbElements();
855       if ( nbEdges[0] *  nbEdges[1] != nbQuads ||
856            nbEdges[0] != nbEdges[2] ||
857            nbEdges[1] != nbEdges[3] )
858         notQuadElemSubMesh.push_back( sm );
859     }
860   }
861
862   // ----------------------------------------------------------------------
863   // Analyse faces mesh and topology: choose the bottom submesh.
864   // If there are not quadrangle geom faces, they are top and bottom ones.
865   // Not quadrangle geom faces must be only on top and bottom.
866   // ----------------------------------------------------------------------
867
868   SMESH_subMesh * botSM = 0;
869   SMESH_subMesh * topSM = 0;
870
871   int nbNotQuad       = notQuadGeomSubMesh.size();
872   int nbNotQuadMeshed = notQuadElemSubMesh.size();
873   bool hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
874
875   // detect bad cases
876   if ( nbNotQuad > 0 && nbNotQuad != 2 )
877     return error(COMPERR_BAD_SHAPE,
878                  TCom("More than 2 not quadrilateral faces: ")
879                  <<nbNotQuad);
880   if ( nbNotQuadMeshed > 2 )
881     return error(COMPERR_BAD_INPUT_MESH,
882                  TCom("More than 2 faces with not quadrangle elements: ")
883                  <<nbNotQuadMeshed);
884
885   // get found submeshes
886   if ( hasNotQuad )
887   {
888     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
889     else                       botSM = notQuadGeomSubMesh.front();
890     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
891     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
892   }
893   // detect other bad cases
894   if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
895     bool ok = false;
896     if ( nbNotQuadMeshed == 1 )
897       ok = ( find( notQuadGeomSubMesh.begin(),
898                    notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
899     else
900       ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
901     if ( !ok )
902       return error(COMPERR_BAD_INPUT_MESH, "Side face meshed with not quadrangle elements");
903   }
904
905   myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
906  
907   // ----------------------------------------------------------
908
909   if ( nbNotQuad == 0 ) // Standard block of 6 quadrangle faces ?
910   {
911     // SMESH_Block will perform geometry analysis, we need just to find 2
912     // connected vertices on top and bottom
913
914     TopoDS_Vertex Vbot, Vtop;
915     if ( nbNotQuadMeshed > 0 ) // Look for vertices
916     {
917       TopTools_IndexedMapOfShape edgeMap;
918       TopExp::MapShapes( botSM->GetSubShape(), TopAbs_EDGE, edgeMap );
919       // vertex 1 is any vertex of the bottom face
920       Vbot = TopExp::FirstVertex( TopoDS::Edge( edgeMap( 1 )));
921       // vertex 2 is end vertex of edge sharing Vbot and not belonging to the bottom face
922       TopTools_ListIteratorOfListOfShape ancestIt = Mesh()->GetAncestors( Vbot );
923       for ( ; Vtop.IsNull() && ancestIt.More(); ancestIt.Next() )
924       {
925         const TopoDS_Shape & ancestor = ancestIt.Value();
926         if ( ancestor.ShapeType() == TopAbs_EDGE && !edgeMap.FindIndex( ancestor ))
927         {
928           TopoDS_Vertex V1, V2;
929           TopExp::Vertices( TopoDS::Edge( ancestor ), V1, V2);
930           if      ( Vbot.IsSame ( V1 )) Vtop = V2;
931           else if ( Vbot.IsSame ( V2 )) Vtop = V1;
932           // check that Vtop belongs to shape3D
933           TopExp_Explorer exp( shape3D, TopAbs_VERTEX );
934           for ( ; exp.More(); exp.Next() )
935             if ( Vtop.IsSame( exp.Current() ))
936               break;
937           if ( !exp.More() )
938             Vtop.Nullify();
939         }
940       }
941     }
942     // get shell from shape3D
943     TopoDS_Shell shell;
944     TopExp_Explorer exp( shape3D, TopAbs_SHELL );
945     int nbShell = 0;
946     for ( ; exp.More(); exp.Next(), ++nbShell )
947       shell = TopoDS::Shell( exp.Current() );
948 //     if ( nbShell != 1 )
949 //       RETURN_BAD_RESULT("There must be 1 shell in the block");
950
951     // Load geometry in SMESH_Block
952     if ( !SMESH_Block::FindBlockShapes( shell, Vbot, Vtop, myShapeIDMap )) {
953       if ( !hasNotQuad )
954         return error(COMPERR_BAD_SHAPE, "Can't detect top and bottom of a prism");
955     }
956     else {
957       if ( !botSM ) botSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_BOT_FACE ));
958       if ( !topSM ) topSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_TOP_FACE ));
959     }
960
961   } // end  Standard block of 6 quadrangle faces
962   // --------------------------------------------------------
963
964   // Here the top and bottom faces are found
965   if ( nbNotQuadMeshed == 2 ) // roughly check correspondence of horiz meshes
966   {
967 //     SMESHDS_SubMesh* topSMDS = topSM->GetSubMeshDS();
968 //     SMESHDS_SubMesh* botSMDS = botSM->GetSubMeshDS();
969 //     if ( topSMDS->NbNodes() != botSMDS->NbNodes() ||
970 //          topSMDS->NbElements() != botSMDS->NbElements() )
971 //       RETURN_BAD_RESULT("Top mesh doesn't correspond to bottom one");
972   }
973
974   // ---------------------------------------------------------
975   // If there are not quadrangle geom faces, we emulate
976   // a block of 6 quadrangle faces.
977   // Load SMESH_Block with faces and edges geometry
978   // ---------------------------------------------------------
979
980   
981   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
982   TopoDS_Vertex V000;
983   double minVal = DBL_MAX, minX, val;
984   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
985         exp.More(); exp.Next() )
986   {
987     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
988     gp_Pnt P = BRep_Tool::Pnt( v );
989     val = P.X() + P.Y() + P.Z();
990     if ( val < minVal || ( val == minVal && P.X() < minX )) {
991       V000 = v;
992       minVal = val;
993       minX = P.X();
994     }
995   }
996
997   // Get ordered bottom edges
998   list< TopoDS_Edge > orderedEdges;
999   list< int >         nbVertexInWires;
1000   SMESH_Block::GetOrderedEdges( TopoDS::Face( botSM->GetSubShape().Reversed() ),
1001                                 V000, orderedEdges, nbVertexInWires );
1002 //   if ( nbVertexInWires.size() != 1 )
1003 //     RETURN_BAD_RESULT("Wrong prism geometry");
1004
1005   // Get Wall faces corresponding to the ordered bottom edges
1006   list< TopoDS_Face > wallFaces;
1007   if ( !GetWallFaces( Mesh(), shape3D, botSM->GetSubShape(), orderedEdges, wallFaces))
1008     return error(COMPERR_BAD_SHAPE, "Can't find side faces");
1009
1010   // Find columns of wall nodes and calculate edges' lengths
1011   // --------------------------------------------------------
1012
1013   myParam2ColumnMaps.clear();
1014   myParam2ColumnMaps.resize( orderedEdges.size() ); // total nb edges
1015
1016   int iE, nbEdges = nbVertexInWires.front(); // nb outer edges
1017   vector< double > edgeLength( nbEdges );
1018   map< double, int > len2edgeMap;
1019
1020   list< TopoDS_Edge >::iterator edgeIt = orderedEdges.begin();
1021   list< TopoDS_Face >::iterator faceIt = wallFaces.begin();
1022   for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1023   {
1024     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1025     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1026       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1027                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1028
1029     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1030     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1031     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1032
1033     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
1034
1035     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
1036     {
1037       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
1038       if ( !smDS )
1039         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
1040                      << MeshDS()->ShapeToIndex( *edgeIt ));
1041       // assure length uniqueness
1042       edgeLength[ iE ] *= smDS->NbNodes() + edgeLength[ iE ] / ( 1000 + iE );
1043       len2edgeMap[ edgeLength[ iE ]] = iE;
1044     }
1045     ++iE;
1046   }
1047   // Load columns of internal edges (forming holes)
1048   // and fill map ShapeIndex to TParam2ColumnMap for them
1049   for ( ; edgeIt != orderedEdges.end() ; ++edgeIt, ++faceIt )
1050   {
1051     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1052     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1053       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1054                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1055     // edge columns
1056     int id = MeshDS()->ShapeToIndex( *edgeIt );
1057     bool isForward = true; // meaningless for intenal wires
1058     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1059     // columns for vertices
1060     // 1
1061     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
1062     id = n0->GetPosition()->GetShapeId();
1063     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1064     // 2
1065     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
1066     id = n1->GetPosition()->GetShapeId();
1067     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1068 //     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1069 //     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1070 //     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1071     ++iE;
1072   }
1073
1074   // Create 4 wall faces of a block
1075   // -------------------------------
1076
1077   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
1078   {
1079     map< int, int > iE2nbSplit;
1080     if ( nbEdges != NB_WALL_FACES ) // define how to split
1081     {
1082       if ( len2edgeMap.size() != nbEdges )
1083         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
1084       map< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
1085       map< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
1086       double maxLen = maxLen_i->first;
1087       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
1088       switch ( nbEdges ) {
1089       case 1: // 0-th edge is split into 4 parts
1090         iE2nbSplit.insert( make_pair( 0, 4 )); break;
1091       case 2: // either the longest edge is split into 3 parts, or both edges into halves
1092         if ( maxLen / 3 > midLen / 2 ) {
1093           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
1094         }
1095         else {
1096           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1097           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
1098         }
1099         break;
1100       case 3:
1101         // split longest into halves
1102         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1103       }
1104     }
1105     // Create TSideFace's
1106     faceIt = wallFaces.begin();
1107     edgeIt = orderedEdges.begin();
1108     int iSide = 0;
1109     for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1110     {
1111      // split?
1112       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
1113       if ( i_nb != iE2nbSplit.end() ) {
1114         // split!
1115         int nbSplit = i_nb->second;
1116         vector< double > params;
1117         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
1118         bool isForward = ( edgeIt->Orientation() == TopAbs_FORWARD );
1119         for ( int i = 0; i < nbSplit; ++i ) {
1120           double f = ( isForward ? params[ i ] : params[ nbSplit - i-1 ]);
1121           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
1122           TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1123                                            *faceIt, *edgeIt,
1124                                            &myParam2ColumnMaps[ iE ], f, l );
1125           mySide->SetComponent( iSide++, comp );
1126         }
1127       }
1128       else {
1129         TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1130                                          *faceIt, *edgeIt,
1131                                          &myParam2ColumnMaps[ iE ]);
1132         mySide->SetComponent( iSide++, comp );
1133       }
1134       ++iE;
1135     }
1136   }
1137   else { // **************************** Unite faces
1138
1139     // unite first faces
1140     int nbExraFaces = nbEdges - 3;
1141     int iSide = 0, iE;
1142     double u0 = 0, sumLen = 0;
1143     for ( iE = 0; iE < nbExraFaces; ++iE )
1144       sumLen += edgeLength[ iE ];
1145
1146     vector< TSideFace* > components( nbExraFaces );
1147     vector< pair< double, double> > params( nbExraFaces );
1148     faceIt = wallFaces.begin();
1149     edgeIt = orderedEdges.begin();
1150     for ( iE = 0; iE < nbExraFaces; ++edgeIt, ++faceIt )
1151     {
1152       components[ iE ] = new TSideFace( myHelper, wallFaceIds[ iSide ],
1153                                         *faceIt, *edgeIt,
1154                                         &myParam2ColumnMaps[ iE ]);
1155       double u1 = u0 + edgeLength[ iE ] / sumLen;
1156       params[ iE ] = make_pair( u0 , u1 );
1157       u0 = u1;
1158       ++iE;
1159     }
1160     mySide->SetComponent( iSide++, new TSideFace( components, params ));
1161
1162     // fill the rest faces
1163     for ( ; iE < nbEdges; ++faceIt, ++edgeIt )
1164     {
1165       TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1166                                        *faceIt, *edgeIt,
1167                                        &myParam2ColumnMaps[ iE ]);
1168       mySide->SetComponent( iSide++, comp );
1169       ++iE;
1170     }
1171   }
1172
1173
1174   // Fill geometry fields of SMESH_Block
1175   // ------------------------------------
1176
1177   TopoDS_Face botF = TopoDS::Face( botSM->GetSubShape() );
1178   TopoDS_Face topF = TopoDS::Face( topSM->GetSubShape() );
1179
1180   vector< int > botEdgeIdVec;
1181   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
1182
1183   bool isForward[NB_WALL_FACES] = { true, true, true, true };
1184   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
1185   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
1186
1187   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
1188   {
1189     TSideFace * sideFace = mySide->GetComponent( iF );
1190     if ( !sideFace )
1191       RETURN_BAD_RESULT("NULL TSideFace");
1192     int fID = sideFace->FaceID();
1193
1194     // fill myShapeIDMap
1195     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
1196          !sideFace->IsComplex())
1197       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
1198
1199     // side faces geometry
1200     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
1201     if ( !sideFace->GetPCurves( pcurves ))
1202       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
1203
1204     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
1205     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
1206
1207     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
1208     // edges 3D geometry
1209     vector< int > edgeIdVec;
1210     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
1211     for ( int isMax = 0; isMax < 2; ++isMax ) {
1212       {
1213         int eID = edgeIdVec[ isMax ];
1214         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
1215         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
1216         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
1217         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
1218       }
1219       {
1220         int eID = edgeIdVec[ isMax+2 ];
1221         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
1222         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
1223         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
1224         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
1225
1226         // corner points
1227         vector< int > vertexIdVec;
1228         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
1229         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
1230         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
1231       }
1232     }
1233     // pcurves on horizontal faces
1234     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
1235       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
1236         botPcurves[ iE ] = sideFace->HorizPCurve( false, botF );
1237         topPcurves[ iE ] = sideFace->HorizPCurve( true,  topF );
1238         break;
1239       }
1240     }
1241   }
1242   // horizontal faces geometry
1243   {
1244     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
1245     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( botF ), botPcurves, isForward );
1246     SMESH_Block::Insert( botF, ID_BOT_FACE, myShapeIDMap );
1247   }
1248   {
1249     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
1250     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( topF ), topPcurves, isForward );
1251     SMESH_Block::Insert( topF, ID_TOP_FACE, myShapeIDMap );
1252   }
1253
1254   // Fill map ShapeIndex to TParam2ColumnMap
1255   // ----------------------------------------
1256
1257   list< TSideFace* > fList;
1258   list< TSideFace* >::iterator fListIt;
1259   fList.push_back( mySide );
1260   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
1261   {
1262     int nb = (*fListIt)->NbComponents();
1263     for ( int i = 0; i < nb; ++i ) {
1264       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
1265         fList.push_back( comp );
1266     }
1267     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
1268       // columns for a base edge
1269       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
1270       bool isForward = (*fListIt)->IsForward();
1271       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1272
1273       // columns for vertices
1274       const SMDS_MeshNode* n0 = cols->begin()->second.front();
1275       id = n0->GetPosition()->GetShapeId();
1276       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1277
1278       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
1279       id = n1->GetPosition()->GetShapeId();
1280       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
1281     }
1282   }
1283
1284 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
1285 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
1286 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
1287 //   SHOWYXZ("IN TEST PARAM" , testPar);
1288 //   SHOWYXZ("OUT TEST CORD" , testCoord);
1289 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
1290 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
1291 //   SHOWYXZ("OUT TEST PARAM" , testPar);
1292
1293   return true;
1294 }
1295
1296 //================================================================================
1297 /*!
1298  * \brief Return pointer to column of nodes
1299  * \param node - bottom node from which the returned column goes up
1300  * \retval const TNodeColumn* - the found column
1301  */
1302 //================================================================================
1303
1304 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
1305 {
1306   int sID = node->GetPosition()->GetShapeId();
1307
1308   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
1309     myShapeIndex2ColumnMap.find( sID );
1310   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
1311     const TParam2ColumnMap* cols = col_frw->second.first;
1312     TParam2ColumnIt u_col = cols->begin();
1313     for ( ; u_col != cols->end(); ++u_col )
1314       if ( u_col->second[ 0 ] == node )
1315         return & u_col->second;
1316   }
1317   return 0;
1318 }
1319
1320 //================================================================================
1321 /*!
1322  * \brief Check curve orientation of a bootom edge
1323   * \param meshDS - mesh DS
1324   * \param columnsMap - node columns map of side face
1325   * \param bottomEdge - the bootom edge
1326   * \param sideFaceID - side face in-block ID
1327   * \retval bool - true if orientation coinside with in-block froward orientation
1328  */
1329 //================================================================================
1330
1331 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
1332                                             const TParam2ColumnMap& columnsMap,
1333                                             const TopoDS_Edge &     bottomEdge,
1334                                             const int               sideFaceID)
1335 {
1336   bool isForward = false;
1337   if ( TAssocTool::IsClosedEdge( bottomEdge ))
1338   {
1339     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
1340   }
1341   else
1342   {
1343     const TNodeColumn& firstCol = columnsMap.begin()->second;
1344     const SMDS_MeshNode* bottomNode = firstCol[0];
1345     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
1346     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
1347   }
1348   // on 2 of 4 sides first vertex is end
1349   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
1350     isForward = !isForward;
1351   return isForward;
1352 }
1353
1354 //================================================================================
1355   /*!
1356    * \brief Find wall faces by bottom edges
1357     * \param mesh - the mesh
1358     * \param mainShape - the prism
1359     * \param bottomFace - the bottom face
1360     * \param bottomEdges - edges bounding the bottom face
1361     * \param wallFaces - faces list to fill in
1362    */
1363 //================================================================================
1364
1365 bool StdMeshers_PrismAsBlock::GetWallFaces( SMESH_Mesh*                     mesh,
1366                                             const TopoDS_Shape &            mainShape,
1367                                             const TopoDS_Shape &            bottomFace,
1368                                             const std::list< TopoDS_Edge >& bottomEdges,
1369                                             std::list< TopoDS_Face >&       wallFaces)
1370 {
1371   wallFaces.clear();
1372
1373   TopTools_IndexedMapOfShape faceMap;
1374   TopExp::MapShapes( mainShape, TopAbs_FACE, faceMap );
1375
1376   list< TopoDS_Edge >::const_iterator edge = bottomEdges.begin();
1377   for ( ; edge != bottomEdges.end(); ++edge )
1378   {
1379     TopTools_ListIteratorOfListOfShape ancestIt = mesh->GetAncestors( *edge );
1380     for ( ; ancestIt.More(); ancestIt.Next() )
1381     {
1382       const TopoDS_Shape& ancestor = ancestIt.Value();
1383       if ( ancestor.ShapeType() == TopAbs_FACE && // face
1384            !bottomFace.IsSame( ancestor ) &&      // not bottom
1385            faceMap.FindIndex( ancestor ))         // belongs to the prism
1386       {
1387         wallFaces.push_back( TopoDS::Face( ancestor ));
1388         break;
1389       }
1390     }
1391   }
1392   return ( wallFaces.size() == bottomEdges.size() );
1393 }
1394
1395 //================================================================================
1396 /*!
1397  * \brief Constructor
1398   * \param faceID - in-block ID
1399   * \param face - geom face
1400   * \param columnsMap - map of node columns
1401   * \param first - first normalized param
1402   * \param last - last normalized param
1403  */
1404 //================================================================================
1405
1406 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_MesherHelper* helper,
1407                                               const int           faceID,
1408                                               const TopoDS_Face&  face,
1409                                               const TopoDS_Edge&  baseEdge,
1410                                               TParam2ColumnMap*   columnsMap,
1411                                               const double        first,
1412                                               const double        last):
1413   myID( faceID ),
1414   myParamToColumnMap( columnsMap ),
1415   myBaseEdge( baseEdge ),
1416   myHelper( helper )
1417 {
1418   mySurface.Initialize( face );
1419   myParams.resize( 1 );
1420   myParams[ 0 ] = make_pair( first, last );
1421   myIsForward = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
1422                                                         *myParamToColumnMap,
1423                                                         myBaseEdge, myID );
1424 }
1425
1426 //================================================================================
1427 /*!
1428  * \brief Constructor of complex side face
1429  */
1430 //================================================================================
1431
1432 StdMeshers_PrismAsBlock::TSideFace::
1433 TSideFace(const vector< TSideFace* >&             components,
1434           const vector< pair< double, double> > & params)
1435   :myID( components[0] ? components[0]->myID : 0 ),
1436    myParamToColumnMap( 0 ),
1437    myParams( params ),
1438    myIsForward( true ),
1439    myComponents( components ),
1440    myHelper( components[0] ? components[0]->myHelper : 0 )
1441 {}
1442 //================================================================================
1443 /*!
1444  * \brief Copy constructor
1445   * \param other - other side
1446  */
1447 //================================================================================
1448
1449 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other )
1450 {
1451   myID               = other.myID;
1452   mySurface          = other.mySurface;
1453   myBaseEdge         = other.myBaseEdge;
1454   myParams           = other.myParams;
1455   myIsForward        = other.myIsForward;
1456   myHelper           = other.myHelper;
1457   myParamToColumnMap = other.myParamToColumnMap;
1458
1459   myComponents.resize( other.myComponents.size());
1460   for (int i = 0 ; i < myComponents.size(); ++i )
1461     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
1462 }
1463
1464 //================================================================================
1465 /*!
1466  * \brief Deletes myComponents
1467  */
1468 //================================================================================
1469
1470 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
1471 {
1472   for (int i = 0 ; i < myComponents.size(); ++i )
1473     if ( myComponents[ i ] )
1474       delete myComponents[ i ];
1475 }
1476
1477 //================================================================================
1478 /*!
1479  * \brief Return geometry of the vertical curve
1480   * \param isMax - true means curve located closer to (1,1,1) block point
1481   * \retval Adaptor3d_Curve* - curve adaptor
1482  */
1483 //================================================================================
1484
1485 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
1486 {
1487   if ( !myComponents.empty() ) {
1488     if ( isMax )
1489       return myComponents.back()->VertiCurve(isMax);
1490     else
1491       return myComponents.front()->VertiCurve(isMax);
1492   }
1493   double f = myParams[0].first, l = myParams[0].second;
1494   if ( !myIsForward ) std::swap( f, l );
1495   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
1496 }
1497
1498 //================================================================================
1499 /*!
1500  * \brief Return geometry of the top or bottom curve
1501   * \param isTop - 
1502   * \retval Adaptor3d_Curve* - 
1503  */
1504 //================================================================================
1505
1506 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
1507 {
1508   return new THorizontalEdgeAdaptor( this, isTop );
1509 }
1510
1511 //================================================================================
1512 /*!
1513  * \brief Return pcurves
1514   * \param pcurv - array of 4 pcurves
1515   * \retval bool - is a success
1516  */
1517 //================================================================================
1518
1519 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
1520 {
1521   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
1522
1523   for ( int i = 0 ; i < 4 ; ++i ) {
1524     Handle(Geom2d_Line) line;
1525     switch ( iEdge[ i ] ) {
1526     case TOP_EDGE:
1527       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
1528     case BOTTOM_EDGE:
1529       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
1530     case V0_EDGE:
1531       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
1532     case V1_EDGE:
1533       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
1534     }
1535     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
1536   }
1537   return true;
1538 }
1539
1540 //================================================================================
1541 /*!
1542  * \brief Returns geometry of pcurve on a horizontal face
1543   * \param isTop - is top or bottom face
1544   * \param horFace - a horizontal face
1545   * \retval Adaptor2d_Curve2d* - curve adaptor
1546  */
1547 //================================================================================
1548
1549 Adaptor2d_Curve2d*
1550 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
1551                                                 const TopoDS_Face& horFace) const
1552 {
1553   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
1554 }
1555
1556 //================================================================================
1557 /*!
1558  * \brief Return a component corresponding to parameter
1559   * \param U - parameter along a horizontal size
1560   * \param localU - parameter along a horizontal size of a component
1561   * \retval TSideFace* - found component
1562  */
1563 //================================================================================
1564
1565 StdMeshers_PrismAsBlock::TSideFace*
1566 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
1567 {
1568   localU = U;
1569   if ( myComponents.empty() )
1570     return const_cast<TSideFace*>( this );
1571
1572   int i;
1573   for ( i = 0; i < myComponents.size(); ++i )
1574     if ( U < myParams[ i ].second )
1575       break;
1576   if ( i >= myComponents.size() )
1577     i = myComponents.size() - 1;
1578
1579   double f = myParams[ i ].first, l = myParams[ i ].second;
1580   localU = ( U - f ) / ( l - f );
1581   return myComponents[ i ];
1582 }
1583
1584 //================================================================================
1585 /*!
1586  * \brief Find node columns for a parameter
1587   * \param U - parameter along a horizontal edge
1588   * \param col1 - the 1st found column
1589   * \param col2 - the 2nd found column
1590   * \retval r - normalized position of U between the found columns
1591  */
1592 //================================================================================
1593
1594 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
1595                                                       TParam2ColumnIt & col1,
1596                                                       TParam2ColumnIt & col2) const
1597 {
1598   double u = U, r = 0;
1599   if ( !myComponents.empty() ) {
1600     TSideFace * comp = GetComponent(U,u);
1601     return comp->GetColumns( u, col1, col2 );
1602   }
1603
1604   if ( !myIsForward )
1605     u = 1 - u;
1606   double f = myParams[0].first, l = myParams[0].second;
1607   u = f + u * ( l - f );
1608
1609   col1 = col2 = getColumn( myParamToColumnMap, u );
1610   if ( ++col2 == myParamToColumnMap->end() ) {
1611     --col2;
1612     r = 0.5;
1613   }
1614   else {
1615 //     if ( !myIsForward )
1616 //       std::swap( col1, col2 );
1617     double uf = col1->first;
1618     double ul = col2->first;
1619     r = ( u - uf ) / ( ul - uf );
1620   }
1621   return r;
1622 }
1623
1624 //================================================================================
1625 /*!
1626  * \brief Return coordinates by normalized params
1627   * \param U - horizontal param
1628   * \param V - vertical param
1629   * \retval gp_Pnt - result point
1630  */
1631 //================================================================================
1632
1633 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
1634                                                  const Standard_Real V) const
1635 {
1636   double u;
1637   if ( !myComponents.empty() ) {
1638     TSideFace * comp = GetComponent(U,u);
1639     return comp->Value( u, V );
1640   }
1641
1642   TParam2ColumnIt u_col1, u_col2;
1643   double vR, hR = GetColumns( U, u_col1, u_col2 );
1644
1645   const SMDS_MeshNode* n1 = 0;
1646   const SMDS_MeshNode* n2 = 0;
1647   const SMDS_MeshNode* n3 = 0;
1648   const SMDS_MeshNode* n4 = 0;
1649   gp_XYZ pnt;
1650
1651   vR = getRAndNodes( & u_col1->second, V, n1, n2 );
1652   vR = getRAndNodes( & u_col2->second, V, n3, n4 );
1653   
1654   gp_XY uv1 = myHelper->GetNodeUV( mySurface.Face(), n1, n4);
1655   gp_XY uv2 = myHelper->GetNodeUV( mySurface.Face(), n2, n3);
1656   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
1657
1658   gp_XY uv3 = myHelper->GetNodeUV( mySurface.Face(), n3, n2);
1659   gp_XY uv4 = myHelper->GetNodeUV( mySurface.Face(), n4, n1);
1660   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
1661
1662   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
1663   
1664   return mySurface.Value( uv.X(), uv.Y() );
1665 }
1666
1667
1668 //================================================================================
1669 /*!
1670  * \brief Return boundary edge
1671   * \param edge - edge index
1672   * \retval TopoDS_Edge - found edge
1673  */
1674 //================================================================================
1675
1676 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
1677 {
1678   if ( !myComponents.empty() ) {
1679     switch ( iEdge ) {
1680     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
1681     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
1682     default: return TopoDS_Edge();
1683     }
1684   }
1685   TopoDS_Shape edge;
1686   const SMDS_MeshNode* node = 0;
1687   SMESHDS_Mesh * meshDS = myHelper->GetMesh()->GetMeshDS();
1688   TNodeColumn* column;
1689
1690   switch ( iEdge ) {
1691   case TOP_EDGE:
1692   case BOTTOM_EDGE:
1693     column = & (( ++myParamToColumnMap->begin())->second );
1694     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
1695     edge = myHelper->GetSubShapeByNode ( node, meshDS );
1696     if ( edge.ShapeType() == TopAbs_VERTEX ) {
1697       column = & ( myParamToColumnMap->begin()->second );
1698       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
1699     }
1700     break;
1701   case V0_EDGE:
1702   case V1_EDGE: {
1703     bool back = ( iEdge == V1_EDGE );
1704     if ( !myIsForward ) back = !back;
1705     if ( back )
1706       column = & ( myParamToColumnMap->rbegin()->second );
1707     else
1708       column = & ( myParamToColumnMap->begin()->second );
1709     if ( column->size() > 0 )
1710       edge = myHelper->GetSubShapeByNode( (*column)[ 1 ], meshDS );
1711     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
1712       node = column->front();
1713     break;
1714   }
1715   default:;
1716   }
1717   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
1718     return TopoDS::Edge( edge );
1719
1720   // find edge by 2 vertices
1721   TopoDS_Shape V1 = edge;
1722   TopoDS_Shape V2 = myHelper->GetSubShapeByNode( node, meshDS );
1723   if ( V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
1724   {
1725     TopTools_ListIteratorOfListOfShape ancestIt =
1726       myHelper->GetMesh()->GetAncestors( V1 );
1727     for ( ; ancestIt.More(); ancestIt.Next() )
1728     {
1729       const TopoDS_Shape & ancestor = ancestIt.Value();
1730       if ( ancestor.ShapeType() == TopAbs_EDGE )
1731         for ( TopExp_Explorer e( ancestor, TopAbs_VERTEX ); e.More(); e.Next() )
1732           if ( V2.IsSame( e.Current() ))
1733             return TopoDS::Edge( ancestor );
1734     }
1735   }
1736   return TopoDS_Edge();
1737 }
1738
1739 //================================================================================
1740 /*!
1741  * \brief Fill block subshapes
1742   * \param shapeMap - map to fill in
1743   * \retval int - nb inserted subshapes
1744  */
1745 //================================================================================
1746
1747 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
1748 {
1749   int nbInserted = 0;
1750
1751   // Insert edges
1752   vector< int > edgeIdVec;
1753   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
1754
1755   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
1756     TopoDS_Edge e = GetEdge( i );
1757     if ( !e.IsNull() ) {
1758       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
1759     }
1760   }
1761
1762   // Insert corner vertices
1763
1764   TParam2ColumnIt col1, col2 ;
1765   vector< int > vertIdVec;
1766
1767   // from V0 column
1768   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
1769   GetColumns(0, col1, col2 );
1770   const SMDS_MeshNode* node0 = col1->second.front();
1771   const SMDS_MeshNode* node1 = col1->second.back();
1772   TopoDS_Shape v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
1773   TopoDS_Shape v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
1774   if ( v0.ShapeType() == TopAbs_VERTEX ) {
1775     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
1776   }
1777   if ( v1.ShapeType() == TopAbs_VERTEX ) {
1778     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
1779   }
1780   
1781   // from V1 column
1782   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
1783   GetColumns(1, col1, col2 );
1784   node0 = col2->second.front();
1785   node1 = col2->second.back();
1786   v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
1787   v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
1788   if ( v0.ShapeType() == TopAbs_VERTEX ) {
1789     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
1790   }
1791   if ( v1.ShapeType() == TopAbs_VERTEX ) {
1792     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
1793   }
1794
1795 //   TopoDS_Vertex V0, V1, Vcom;
1796 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
1797 //   if ( !myIsForward ) std::swap( V0, V1 );
1798
1799 //   // bottom vertex IDs
1800 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
1801 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
1802 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
1803
1804 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
1805 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
1806 //     return false;
1807
1808 //   // insert one side edge
1809 //   int edgeID;
1810 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
1811 //   else                    edgeID = edgeIdVec[ _v1 ];
1812 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
1813
1814 //   // top vertex of the side edge
1815 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
1816 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
1817 //   if ( Vcom.IsSame( Vtop ))
1818 //     Vtop = TopExp::LastVertex( sideEdge );
1819 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
1820
1821 //   // other side edge
1822 //   sideEdge = GetEdge( V1_EDGE );
1823 //   if ( sideEdge.IsNull() )
1824 //     return false;
1825 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
1826 //   else                            edgeID = edgeIdVec[ _v1 ];
1827 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
1828   
1829 //   // top edge
1830 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
1831 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
1832
1833 //   // top vertex of the other side edge
1834 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
1835 //     return false;
1836 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
1837 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
1838
1839   return nbInserted;
1840 }
1841
1842 //================================================================================
1843 /*!
1844  * \brief Creates TVerticalEdgeAdaptor 
1845   * \param columnsMap - node column map
1846   * \param parameter - normalized parameter
1847  */
1848 //================================================================================
1849
1850 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
1851 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
1852 {
1853   myNodeColumn = & getColumn( columnsMap, parameter )->second;
1854 }
1855
1856 //================================================================================
1857 /*!
1858  * \brief Return coordinates for the given normalized parameter
1859   * \param U - normalized parameter
1860   * \retval gp_Pnt - coordinates
1861  */
1862 //================================================================================
1863
1864 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
1865 {
1866   const SMDS_MeshNode* n1;
1867   const SMDS_MeshNode* n2;
1868   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
1869   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
1870 }
1871
1872 //================================================================================
1873 /*!
1874  * \brief Return coordinates for the given normalized parameter
1875   * \param U - normalized parameter
1876   * \retval gp_Pnt - coordinates
1877  */
1878 //================================================================================
1879
1880 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
1881 {
1882   return mySide->TSideFace::Value( U, myV );
1883 }
1884
1885 //================================================================================
1886 /*!
1887  * \brief Return UV on pcurve for the given normalized parameter
1888   * \param U - normalized parameter
1889   * \retval gp_Pnt - coordinates
1890  */
1891 //================================================================================
1892
1893 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
1894 {
1895   TParam2ColumnIt u_col1, u_col2;
1896   double r = mySide->GetColumns( U, u_col1, u_col2 );
1897   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ]);
1898   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ]);
1899   return uv1 * ( 1 - r ) + uv2 * r;
1900 }