Salome HOME
untabify
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  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 //  SMESH SMESH : implementaion of SMESH idl descriptions
23 // File      : StdMeshers_Prism_3D.cxx
24 // Module    : SMESH
25 // Created   : Fri Oct 20 11:37:07 2006
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "StdMeshers_Prism_3D.hxx"
29
30 #include "StdMeshers_ProjectionUtils.hxx"
31 #include "SMESH_MesherHelper.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMDS_VolumeOfNodes.hxx"
34 #include "SMDS_EdgePosition.hxx"
35 #include "SMESH_Comment.hxx"
36
37 #include "utilities.h"
38
39 #include <BRep_Tool.hxx>
40 #include <Geom2dAdaptor_Curve.hxx>
41 #include <Geom2d_Line.hxx>
42 #include <TopExp.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopTools_SequenceOfShape.hxx>
46 #include <TopTools_MapOfShape.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 //function : Evaluate
374 //purpose  : 
375 //=======================================================================
376
377 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh& theMesh,
378                                    const TopoDS_Shape& theShape,
379                                    MapShapeNbElems& aResMap)
380 {
381   // find face contains only triangles
382   vector < SMESH_subMesh * >meshFaces;
383   TopTools_SequenceOfShape aFaces;
384   int NumBase = 0, i = 0, NbQFs = 0;
385   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
386     i++;
387     aFaces.Append(exp.Current());
388     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
389     meshFaces.push_back(aSubMesh);
390     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
391     if( anIt==aResMap.end() ) {
392       SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
393       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
394       return false;
395     }
396     std::vector<int> aVec = (*anIt).second;
397     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
398     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
399     if( nbtri==0 && nbqua>0 ) {
400       NbQFs++;
401     }
402     if( nbtri>0 ) {
403       NumBase = i;
404     }
405   }
406
407   if(NbQFs<4) {
408     std::vector<int> aResVec(SMDSEntity_Last);
409     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
410     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
411     aResMap.insert(std::make_pair(sm,aResVec));
412     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
413     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
414     return false;
415   }
416
417   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
418
419   // find number of 1d elems for base face
420   int nb1d = 0;
421   TopTools_MapOfShape Edges1;
422   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
423     Edges1.Add(exp.Current());
424     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
425     if( sm ) {
426       MapShapeNbElemsItr anIt = aResMap.find(sm);
427       if( anIt == aResMap.end() ) continue;
428       std::vector<int> aVec = (*anIt).second;
429       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
430     }
431   }
432   // find face opposite to base face
433   int OppNum = 0;
434   for(i=1; i<=6; i++) {
435     if(i==NumBase) continue;
436     bool IsOpposite = true;
437     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
438       if( Edges1.Contains(exp.Current()) ) {
439         IsOpposite = false;
440         break;
441       }
442     }
443     if(IsOpposite) {
444       OppNum = i;
445       break;
446     }
447   }
448   // find number of 2d elems on side faces
449   int nb2d = 0;
450   for(i=1; i<=6; i++) {
451     if( i==OppNum || i==NumBase ) continue;
452     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
453     if( anIt == aResMap.end() ) continue;
454     std::vector<int> aVec = (*anIt).second;
455     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
456   }
457   
458   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
459   std::vector<int> aVec = (*anIt).second;
460   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
461                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
462   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
463   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
464   int nb0d_face0 = aVec[SMDSEntity_Node];
465   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
466
467   std::vector<int> aResVec(SMDSEntity_Last);
468   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
469   if(IsQuadratic) {
470     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
471     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
472     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
473   }
474   else {
475     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
476     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
477     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
478   }
479   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
480   aResMap.insert(std::make_pair(sm,aResVec));
481
482   return true;
483 }
484
485
486 //================================================================================
487 /*!
488  * \brief Create prisms
489  * \param columns - columns of nodes generated from nodes of a mesh face
490  * \param helper - helper initialized by mesh and shape to add prisms to
491  */
492 //================================================================================
493
494 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
495                                      SMESH_MesherHelper*          helper)
496 {
497   SMESHDS_Mesh * meshDS = helper->GetMeshDS();
498   int shapeID = helper->GetSubShapeID();
499
500   int nbNodes = columns.size();
501   int nbZ     = columns[0]->size();
502   if ( nbZ < 2 ) return;
503
504   // find out orientation
505   bool isForward = true;
506   SMDS_VolumeTool vTool;
507   int z = 1;
508   switch ( nbNodes ) {
509   case 3: {
510     const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
511                                          (*columns[1])[z-1],
512                                          (*columns[2])[z-1] };
513     const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
514                                          (*columns[1])[z],
515                                          (*columns[2])[z] };
516     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2],
517                                 topNodes[0], topNodes[1], topNodes[2]);
518     vTool.Set( &tmpVol );
519     isForward  = vTool.IsForward();
520     break;
521   }
522   case 4: {
523     const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
524                                          (*columns[2])[z-1], (*columns[3])[z-1] };
525     const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
526                                          (*columns[2])[z], (*columns[3])[z] };
527     SMDS_VolumeOfNodes tmpVol ( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
528                                 topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
529     vTool.Set( &tmpVol );
530     isForward  = vTool.IsForward();
531     break;
532   }
533   }
534
535   // vertical loop on columns
536   for ( z = 1; z < nbZ; ++z )
537   {
538     SMDS_MeshElement* vol = 0;
539     switch ( nbNodes ) {
540
541     case 3: {
542       const SMDS_MeshNode* botNodes[3] = { (*columns[0])[z-1],
543                                            (*columns[1])[z-1],
544                                            (*columns[2])[z-1] };
545       const SMDS_MeshNode* topNodes[3] = { (*columns[0])[z],
546                                            (*columns[1])[z],
547                                            (*columns[2])[z] };
548       if ( isForward )
549         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2],
550                                  topNodes[0], topNodes[1], topNodes[2]);
551       else
552         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2],
553                                  botNodes[0], botNodes[1], botNodes[2]);
554       break;
555       }
556     case 4: {
557       const SMDS_MeshNode* botNodes[4] = { (*columns[0])[z-1], (*columns[1])[z-1],
558                                            (*columns[2])[z-1], (*columns[3])[z-1] };
559       const SMDS_MeshNode* topNodes[4] = { (*columns[0])[z], (*columns[1])[z],
560                                            (*columns[2])[z], (*columns[3])[z] };
561       if ( isForward )
562         vol = helper->AddVolume( botNodes[0], botNodes[1], botNodes[2], botNodes[3],
563                                  topNodes[0], topNodes[1], topNodes[2], topNodes[3]);
564       else
565         vol = helper->AddVolume( topNodes[0], topNodes[1], topNodes[2], topNodes[3],
566                                  botNodes[0], botNodes[1], botNodes[2], botNodes[3]);
567       break;
568       }
569     default:
570       // polyhedron
571       vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
572       vector<int> quantities( 2 + nbNodes, 4 );
573       quantities[0] = quantities[1] = nbNodes;
574       columns.resize( nbNodes + 1 );
575       columns[ nbNodes ] = columns[ 0 ];
576       for ( int i = 0; i < nbNodes; ++i ) {
577         nodes[ i         ] = (*columns[ i ])[z-1]; // bottom
578         nodes[ i+nbNodes ] = (*columns[ i ])[z  ]; // top
579         // side
580         int di = 2*nbNodes + 4*i - 1;
581         nodes[ di   ] = (*columns[i  ])[z-1];
582         nodes[ di+1 ] = (*columns[i+1])[z-1];
583         nodes[ di+2 ] = (*columns[i+1])[z  ];
584         nodes[ di+3 ] = (*columns[i  ])[z  ];
585       }
586       vol = meshDS->AddPolyhedralVolume( nodes, quantities );
587     }
588     if ( vol && shapeID > 0 )
589       meshDS->SetMeshElementOnShape( vol, shapeID );
590   }
591 }
592
593 //================================================================================
594 /*!
595  * \brief Find correspondence between bottom and top nodes
596  *  If elements on the bottom and top faces are topologically different,
597  *  and projection is possible and allowed, perform the projection
598  *  \retval bool - is a success or not
599  */
600 //================================================================================
601
602 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
603 {
604   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
605   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
606
607   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
608   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
609
610   if ( !botSMDS || botSMDS->NbElements() == 0 )
611     return error(TCom("No elememts on face #") << botSM->GetId());
612
613   bool needProject = false;
614   if ( !topSMDS || 
615        botSMDS->NbElements() != topSMDS->NbElements() ||
616        botSMDS->NbNodes()    != topSMDS->NbNodes())
617   {
618     if ( myBlock.HasNotQuadElemOnTop() )
619       return error(TCom("Mesh on faces #") << botSM->GetId()
620                    <<" and #"<< topSM->GetId() << " seems different" );
621     needProject = true;
622   }
623
624   if ( 0/*needProject && !myProjectTriangles*/ )
625     return error(TCom("Mesh on faces #") << botSM->GetId()
626                  <<" and #"<< topSM->GetId() << " seems different" );
627   ///RETURN_BAD_RESULT("Need to project but not allowed");
628
629   if ( needProject )
630   {
631     return projectBottomToTop();
632   }
633
634   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
635   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
636   // associate top and bottom faces
637   TAssocTool::TShapeShapeMap shape2ShapeMap;
638   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
639                                              topFace, myBlock.Mesh(),
640                                              shape2ShapeMap) )
641     return error(TCom("Topology of faces #") << botSM->GetId()
642                  <<" and #"<< topSM->GetId() << " seems different" );
643
644   // Find matching nodes of top and bottom faces
645   TNodeNodeMap n2nMap;
646   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
647                                                topFace, myBlock.Mesh(),
648                                                shape2ShapeMap, n2nMap ))
649     return error(TCom("Mesh on faces #") << botSM->GetId()
650                  <<" and #"<< topSM->GetId() << " seems different" );
651
652   // Fill myBotToColumnMap
653
654   int zSize = myBlock.VerticalSize();
655   TNode prevTNode;
656   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
657   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
658   {
659     const SMDS_MeshNode* botNode = bN_tN->first;
660     const SMDS_MeshNode* topNode = bN_tN->second;
661     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
662       continue; // wall columns are contained in myBlock
663     // compute bottom node params
664     TNode bN( botNode );
665     if ( zSize > 2 ) {
666       gp_XYZ paramHint(-1,-1,-1);
667       if ( prevTNode.IsNeighbor( bN ))
668         paramHint = prevTNode.GetParams();
669       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
670                                        ID_BOT_FACE, paramHint ))
671         return error(TCom("Can't compute normalized parameters for node ")
672                      << botNode->GetID() << " on the face #"<< botSM->GetId() );
673       prevTNode = bN;
674     }
675     // create node column
676     TNode2ColumnMap::iterator bN_col = 
677       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
678     TNodeColumn & column = bN_col->second;
679     column.resize( zSize );
680     column.front() = botNode;
681     column.back()  = topNode;
682   }
683   return true;
684 }
685
686 //================================================================================
687 /*!
688  * \brief Remove quadrangles from the top face and
689  * create triangles there by projection from the bottom
690  * \retval bool - a success or not
691  */
692 //================================================================================
693
694 bool StdMeshers_Prism_3D::projectBottomToTop()
695 {
696   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
697   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
698
699   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
700   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
701
702   if ( topSMDS )
703     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
704
705   SMESHDS_Mesh* meshDS = myBlock.MeshDS();
706   int shapeID = myHelper->GetSubShapeID();
707   int topFaceID = meshDS->ShapeToIndex( topSM->GetSubShape() );
708
709   // Fill myBotToColumnMap
710
711   int zSize = myBlock.VerticalSize();
712   TNode prevTNode;
713   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
714   while ( nIt->more() )
715   {
716     const SMDS_MeshNode* botNode = nIt->next();
717     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
718       continue; // strange
719     // compute bottom node params
720     TNode bN( botNode );
721     gp_XYZ paramHint(-1,-1,-1);
722     if ( prevTNode.IsNeighbor( bN ))
723       paramHint = prevTNode.GetParams();
724     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
725                                      ID_BOT_FACE, paramHint ))
726       return error(TCom("Can't compute normalized parameters for node ")
727                    << botNode->GetID() << " on the face #"<< botSM->GetId() );
728     prevTNode = bN;
729     // compute top node coords
730     gp_XYZ topXYZ; gp_XY topUV;
731     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
732          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
733       return error(TCom("Can't compute coordinates "
734                         "by normalized parameters on the face #")<< topSM->GetId() );
735     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
736     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
737     // create node column
738     TNode2ColumnMap::iterator bN_col = 
739       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
740     TNodeColumn & column = bN_col->second;
741     column.resize( zSize );
742     column.front() = botNode;
743     column.back()  = topNode;
744   }
745
746   // Create top faces
747
748   // loop on bottom mesh faces
749   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
750   while ( faceIt->more() )
751   {
752     const SMDS_MeshElement* face = faceIt->next();
753     if ( !face || face->GetType() != SMDSAbs_Face )
754       continue;
755     int nbNodes = face->NbNodes();
756     if ( face->IsQuadratic() )
757       nbNodes /= 2;
758
759     // find top node in columns for each bottom node
760     vector< const SMDS_MeshNode* > nodes( nbNodes );
761     for ( int i = 0; i < nbNodes; ++i )
762     {
763       const SMDS_MeshNode* n = face->GetNode( nbNodes - i - 1 );
764       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
765         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
766         if ( bot_column == myBotToColumnMap.end() )
767           return error(TCom("No nodes found above node ") << n->GetID() );
768         nodes[ i ] = bot_column->second.back();
769       }
770       else {
771         const TNodeColumn* column = myBlock.GetNodeColumn( n );
772         if ( !column )
773           return error(TCom("No side nodes found above node ") << n->GetID() );
774         nodes[ i ] = column->back();
775       }
776     }
777     // create a face, with reversed orientation
778     SMDS_MeshElement* newFace = 0;
779     switch ( nbNodes ) {
780
781     case 3: {
782       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
783       break;
784       }
785     case 4: {
786       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
787       break;
788       }
789     default:
790       newFace = meshDS->AddPolygonalFace( nodes );
791     }
792     if ( newFace && shapeID > 0 )
793       meshDS->SetMeshElementOnShape( newFace, shapeID );
794   }
795
796   return true;
797 }
798
799 //================================================================================
800 /*!
801  * \brief Set projection coordinates of a node to a face and it's subshapes
802  * \param faceID - the face given by in-block ID
803  * \param params - node normalized parameters
804  * \retval bool - is a success
805  */
806 //================================================================================
807
808 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
809 {
810   // find base and top edges of the face
811   enum { BASE = 0, TOP, LEFT, RIGHT };
812   vector< int > edgeVec; // 0-base, 1-top
813   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
814
815   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
816   myBlock.EdgePoint( edgeVec[ TOP ], params, myShapeXYZ[ edgeVec[ TOP ]]);
817
818   SHOWYXZ("\nparams ", params);
819   SHOWYXZ("TOP is "<<edgeVec[ TOP], myShapeXYZ[ edgeVec[ TOP]]);
820   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
821
822   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
823   {
824     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
825     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
826
827     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
828     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
829   }
830   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
831   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
832
833   return true;
834 }
835
836 //================================================================================
837 /*!
838  * \brief Return true if this node and other one belong to one face
839  */
840 //================================================================================
841
842 bool TNode::IsNeighbor( const TNode& other ) const
843 {
844   if ( !other.myNode || !myNode ) return false;
845
846   SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
847   while ( fIt->more() )
848     if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
849       return true;
850   return false;
851 }
852
853 //================================================================================
854 /*!
855  * \brief Constructor. Initialization is needed
856  */
857 //================================================================================
858
859 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
860 {
861   mySide = 0;
862 }
863
864 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
865 {
866   if ( mySide ) {
867     delete mySide; mySide = 0;
868   }
869 }
870
871 //================================================================================
872 /*!
873  * \brief Initialization.
874  * \param helper - helper loaded with mesh and 3D shape
875  * \param shape3D - a closed shell or solid
876  * \retval bool - false if a mesh or a shape are KO
877  */
878 //================================================================================
879
880 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper* helper,
881                                    const TopoDS_Shape& shape3D)
882 {
883   if ( mySide ) {
884     delete mySide; mySide = 0;
885   }
886   vector< TSideFace* > sideFaces( NB_WALL_FACES, 0 );
887   vector< pair< double, double> > params ( NB_WALL_FACES );
888   mySide = new TSideFace( sideFaces, params );
889
890   myHelper = helper;
891   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
892
893   SMESH_Block::init();
894   myShapeIDMap.Clear();
895   myShapeIndex2ColumnMap.clear();
896   
897   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
898     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
899     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
900   };
901
902   myError = SMESH_ComputeError::New();
903
904   // -------------------------------------------------------------
905   // Look for top and bottom faces: not quadrangle ones or meshed
906   // with not quadrangle elements
907   // -------------------------------------------------------------
908
909   list< SMESH_subMesh* > notQuadGeomSubMesh;
910   list< SMESH_subMesh* > notQuadElemSubMesh;
911   int nbFaces = 0;
912   //
913   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
914   if ( !mainSubMesh ) return error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D");
915
916   // analyse face submeshes
917   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,false);
918   while ( smIt->more() )
919   {
920     SMESH_subMesh* sm = smIt->next();
921     const TopoDS_Shape& face = sm->GetSubShape();
922     if ( face.ShapeType() != TopAbs_FACE )
923       continue;
924     nbFaces++;
925
926     // is quadrangle face?
927     list< TopoDS_Edge > orderedEdges;
928     list< int >         nbEdgesInWires;
929     TopoDS_Vertex       V000;
930     int nbWires = GetOrderedEdges( TopoDS::Face( face ),
931                                    V000, orderedEdges, nbEdgesInWires );
932     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
933       notQuadGeomSubMesh.push_back( sm );
934
935     // look for not quadrangle mesh elements
936     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() ) {
937       bool hasNotQuad = false;
938       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
939       while ( eIt->more() && !hasNotQuad ) {
940         const SMDS_MeshElement* elem = eIt->next();
941         if ( elem->GetType() == SMDSAbs_Face ) {
942           int nbNodes = elem->NbNodes();
943           if ( elem->IsQuadratic() )
944             nbNodes /= 2;
945           hasNotQuad = ( nbNodes != 4 );
946         }
947       }
948       if ( hasNotQuad )
949         notQuadElemSubMesh.push_back( sm );
950     }
951     else {
952       return error(COMPERR_BAD_INPUT_MESH,TCom("Not meshed face #")<<sm->GetId());
953     }
954     // check if a quadrangle face is meshed with a quadranglar grid
955     if ( notQuadGeomSubMesh.back() != sm &&
956          notQuadElemSubMesh.back() != sm )
957     {
958       // count nb edges on face sides
959       vector< int > nbEdges;
960       nbEdges.reserve( nbEdgesInWires.front() );
961       for ( list< TopoDS_Edge >::iterator edge = orderedEdges.begin();
962             edge != orderedEdges.end(); ++edge )
963       {
964         if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edge ))
965           nbEdges.push_back ( smDS->NbElements() );
966         else
967           nbEdges.push_back ( 0 );
968       }
969       int nbQuads = sm->GetSubMeshDS()->NbElements();
970       if ( nbEdges[0] *  nbEdges[1] != nbQuads ||
971            nbEdges[0] != nbEdges[2] ||
972            nbEdges[1] != nbEdges[3] )
973         notQuadElemSubMesh.push_back( sm );
974     }
975   }
976
977   // ----------------------------------------------------------------------
978   // Analyse faces mesh and topology: choose the bottom submesh.
979   // If there are not quadrangle geom faces, they are top and bottom ones.
980   // Not quadrangle geom faces must be only on top and bottom.
981   // ----------------------------------------------------------------------
982
983   SMESH_subMesh * botSM = 0;
984   SMESH_subMesh * topSM = 0;
985
986   int nbNotQuad       = notQuadGeomSubMesh.size();
987   int nbNotQuadMeshed = notQuadElemSubMesh.size();
988   bool hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
989
990   // detect bad cases
991   if ( nbNotQuad > 0 && nbNotQuad != 2 )
992     return error(COMPERR_BAD_SHAPE,
993                  TCom("More than 2 not quadrilateral faces: ")
994                  <<nbNotQuad);
995   if ( nbNotQuadMeshed > 2 )
996     return error(COMPERR_BAD_INPUT_MESH,
997                  TCom("More than 2 faces with not quadrangle elements: ")
998                  <<nbNotQuadMeshed);
999
1000   // get found submeshes
1001   if ( hasNotQuad )
1002   {
1003     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
1004     else                       botSM = notQuadGeomSubMesh.front();
1005     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
1006     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
1007   }
1008   // detect other bad cases
1009   if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
1010     bool ok = false;
1011     if ( nbNotQuadMeshed == 1 )
1012       ok = ( find( notQuadGeomSubMesh.begin(),
1013                    notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
1014     else
1015       ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
1016     if ( !ok )
1017       return error(COMPERR_BAD_INPUT_MESH, "Side face meshed with not quadrangle elements");
1018   }
1019
1020   myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
1021  
1022   // ----------------------------------------------------------
1023
1024   if ( nbNotQuad == 0 ) // Standard block of 6 quadrangle faces ?
1025   {
1026     // SMESH_Block will perform geometry analysis, we need just to find 2
1027     // connected vertices on top and bottom
1028
1029     TopoDS_Vertex Vbot, Vtop;
1030     if ( nbNotQuadMeshed > 0 ) // Look for vertices
1031     {
1032       TopTools_IndexedMapOfShape edgeMap;
1033       TopExp::MapShapes( botSM->GetSubShape(), TopAbs_EDGE, edgeMap );
1034       // vertex 1 is any vertex of the bottom face
1035       Vbot = TopExp::FirstVertex( TopoDS::Edge( edgeMap( 1 )));
1036       // vertex 2 is end vertex of edge sharing Vbot and not belonging to the bottom face
1037       TopTools_ListIteratorOfListOfShape ancestIt = Mesh()->GetAncestors( Vbot );
1038       for ( ; Vtop.IsNull() && ancestIt.More(); ancestIt.Next() )
1039       {
1040         const TopoDS_Shape & ancestor = ancestIt.Value();
1041         if ( ancestor.ShapeType() == TopAbs_EDGE && !edgeMap.FindIndex( ancestor ))
1042         {
1043           TopoDS_Vertex V1, V2;
1044           TopExp::Vertices( TopoDS::Edge( ancestor ), V1, V2);
1045           if      ( Vbot.IsSame ( V1 )) Vtop = V2;
1046           else if ( Vbot.IsSame ( V2 )) Vtop = V1;
1047           // check that Vtop belongs to shape3D
1048           TopExp_Explorer exp( shape3D, TopAbs_VERTEX );
1049           for ( ; exp.More(); exp.Next() )
1050             if ( Vtop.IsSame( exp.Current() ))
1051               break;
1052           if ( !exp.More() )
1053             Vtop.Nullify();
1054         }
1055       }
1056     }
1057     // get shell from shape3D
1058     TopoDS_Shell shell;
1059     TopExp_Explorer exp( shape3D, TopAbs_SHELL );
1060     int nbShell = 0;
1061     for ( ; exp.More(); exp.Next(), ++nbShell )
1062       shell = TopoDS::Shell( exp.Current() );
1063 //     if ( nbShell != 1 )
1064 //       RETURN_BAD_RESULT("There must be 1 shell in the block");
1065
1066     // Load geometry in SMESH_Block
1067     if ( !SMESH_Block::FindBlockShapes( shell, Vbot, Vtop, myShapeIDMap )) {
1068       if ( !hasNotQuad )
1069         return error(COMPERR_BAD_SHAPE, "Can't detect top and bottom of a prism");
1070     }
1071     else {
1072       if ( !botSM ) botSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_BOT_FACE ));
1073       if ( !topSM ) topSM = Mesh()->GetSubMeshContaining( myShapeIDMap( ID_TOP_FACE ));
1074     }
1075
1076   } // end  Standard block of 6 quadrangle faces
1077   // --------------------------------------------------------
1078
1079   // Here the top and bottom faces are found
1080   if ( nbNotQuadMeshed == 2 ) // roughly check correspondence of horiz meshes
1081   {
1082 //     SMESHDS_SubMesh* topSMDS = topSM->GetSubMeshDS();
1083 //     SMESHDS_SubMesh* botSMDS = botSM->GetSubMeshDS();
1084 //     if ( topSMDS->NbNodes() != botSMDS->NbNodes() ||
1085 //          topSMDS->NbElements() != botSMDS->NbElements() )
1086 //       RETURN_BAD_RESULT("Top mesh doesn't correspond to bottom one");
1087   }
1088
1089   // ---------------------------------------------------------
1090   // If there are not quadrangle geom faces, we emulate
1091   // a block of 6 quadrangle faces.
1092   // Load SMESH_Block with faces and edges geometry
1093   // ---------------------------------------------------------
1094
1095   
1096   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
1097   TopoDS_Vertex V000;
1098   double minVal = DBL_MAX, minX, val;
1099   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
1100         exp.More(); exp.Next() )
1101   {
1102     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
1103     gp_Pnt P = BRep_Tool::Pnt( v );
1104     val = P.X() + P.Y() + P.Z();
1105     if ( val < minVal || ( val == minVal && P.X() < minX )) {
1106       V000 = v;
1107       minVal = val;
1108       minX = P.X();
1109     }
1110   }
1111
1112   // Get ordered bottom edges
1113   list< TopoDS_Edge > orderedEdges;
1114   list< int >         nbVertexInWires;
1115   SMESH_Block::GetOrderedEdges( TopoDS::Face( botSM->GetSubShape().Reversed() ),
1116                                 V000, orderedEdges, nbVertexInWires );
1117 //   if ( nbVertexInWires.size() != 1 )
1118 //     RETURN_BAD_RESULT("Wrong prism geometry");
1119
1120   // Get Wall faces corresponding to the ordered bottom edges
1121   list< TopoDS_Face > wallFaces;
1122   if ( !GetWallFaces( Mesh(), shape3D, botSM->GetSubShape(), orderedEdges, wallFaces))
1123     return error(COMPERR_BAD_SHAPE, "Can't find side faces");
1124
1125   // Find columns of wall nodes and calculate edges' lengths
1126   // --------------------------------------------------------
1127
1128   myParam2ColumnMaps.clear();
1129   myParam2ColumnMaps.resize( orderedEdges.size() ); // total nb edges
1130
1131   int iE, nbEdges = nbVertexInWires.front(); // nb outer edges
1132   vector< double > edgeLength( nbEdges );
1133   map< double, int > len2edgeMap;
1134
1135   list< TopoDS_Edge >::iterator edgeIt = orderedEdges.begin();
1136   list< TopoDS_Face >::iterator faceIt = wallFaces.begin();
1137   for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1138   {
1139     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1140     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1141       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1142                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1143
1144     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1145     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1146     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1147
1148     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
1149
1150     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
1151     {
1152       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
1153       if ( !smDS )
1154         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
1155                      << MeshDS()->ShapeToIndex( *edgeIt ));
1156       // assure length uniqueness
1157       edgeLength[ iE ] *= smDS->NbNodes() + edgeLength[ iE ] / ( 1000 + iE );
1158       len2edgeMap[ edgeLength[ iE ]] = iE;
1159     }
1160     ++iE;
1161   }
1162   // Load columns of internal edges (forming holes)
1163   // and fill map ShapeIndex to TParam2ColumnMap for them
1164   for ( ; edgeIt != orderedEdges.end() ; ++edgeIt, ++faceIt )
1165   {
1166     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
1167     if ( !myHelper->LoadNodeColumns( faceColumns, *faceIt, *edgeIt, meshDS ))
1168       return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
1169                    << "on a side face #" << MeshDS()->ShapeToIndex( *faceIt ));
1170     // edge columns
1171     int id = MeshDS()->ShapeToIndex( *edgeIt );
1172     bool isForward = true; // meaningless for intenal wires
1173     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1174     // columns for vertices
1175     // 1
1176     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
1177     id = n0->GetPosition()->GetShapeId();
1178     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1179     // 2
1180     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
1181     id = n1->GetPosition()->GetShapeId();
1182     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
1183 //     SHOWYXZ("\np1 F "<<iE, gpXYZ(faceColumns.begin()->second.front() ));
1184 //     SHOWYXZ("p2 F "<<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
1185 //     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
1186     ++iE;
1187   }
1188
1189   // Create 4 wall faces of a block
1190   // -------------------------------
1191
1192   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
1193   {
1194     map< int, int > iE2nbSplit;
1195     if ( nbEdges != NB_WALL_FACES ) // define how to split
1196     {
1197       if ( len2edgeMap.size() != nbEdges )
1198         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
1199       map< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
1200       map< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
1201       double maxLen = maxLen_i->first;
1202       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
1203       switch ( nbEdges ) {
1204       case 1: // 0-th edge is split into 4 parts
1205         iE2nbSplit.insert( make_pair( 0, 4 )); break;
1206       case 2: // either the longest edge is split into 3 parts, or both edges into halves
1207         if ( maxLen / 3 > midLen / 2 ) {
1208           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
1209         }
1210         else {
1211           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1212           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
1213         }
1214         break;
1215       case 3:
1216         // split longest into halves
1217         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
1218       }
1219     }
1220     // Create TSideFace's
1221     faceIt = wallFaces.begin();
1222     edgeIt = orderedEdges.begin();
1223     int iSide = 0;
1224     for ( iE = 0; iE < nbEdges; ++edgeIt, ++faceIt )
1225     {
1226      // split?
1227       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
1228       if ( i_nb != iE2nbSplit.end() ) {
1229         // split!
1230         int nbSplit = i_nb->second;
1231         vector< double > params;
1232         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
1233         bool isForward = ( edgeIt->Orientation() == TopAbs_FORWARD );
1234         for ( int i = 0; i < nbSplit; ++i ) {
1235           double f = ( isForward ? params[ i ] : params[ nbSplit - i-1 ]);
1236           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
1237           TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1238                                            *faceIt, *edgeIt,
1239                                            &myParam2ColumnMaps[ iE ], f, l );
1240           mySide->SetComponent( iSide++, comp );
1241         }
1242       }
1243       else {
1244         TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1245                                          *faceIt, *edgeIt,
1246                                          &myParam2ColumnMaps[ iE ]);
1247         mySide->SetComponent( iSide++, comp );
1248       }
1249       ++iE;
1250     }
1251   }
1252   else { // **************************** Unite faces
1253
1254     // unite first faces
1255     int nbExraFaces = nbEdges - 3;
1256     int iSide = 0, iE;
1257     double u0 = 0, sumLen = 0;
1258     for ( iE = 0; iE < nbExraFaces; ++iE )
1259       sumLen += edgeLength[ iE ];
1260
1261     vector< TSideFace* > components( nbExraFaces );
1262     vector< pair< double, double> > params( nbExraFaces );
1263     faceIt = wallFaces.begin();
1264     edgeIt = orderedEdges.begin();
1265     for ( iE = 0; iE < nbExraFaces; ++edgeIt, ++faceIt )
1266     {
1267       components[ iE ] = new TSideFace( myHelper, wallFaceIds[ iSide ],
1268                                         *faceIt, *edgeIt,
1269                                         &myParam2ColumnMaps[ iE ]);
1270       double u1 = u0 + edgeLength[ iE ] / sumLen;
1271       params[ iE ] = make_pair( u0 , u1 );
1272       u0 = u1;
1273       ++iE;
1274     }
1275     mySide->SetComponent( iSide++, new TSideFace( components, params ));
1276
1277     // fill the rest faces
1278     for ( ; iE < nbEdges; ++faceIt, ++edgeIt )
1279     {
1280       TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
1281                                        *faceIt, *edgeIt,
1282                                        &myParam2ColumnMaps[ iE ]);
1283       mySide->SetComponent( iSide++, comp );
1284       ++iE;
1285     }
1286   }
1287
1288
1289   // Fill geometry fields of SMESH_Block
1290   // ------------------------------------
1291
1292   TopoDS_Face botF = TopoDS::Face( botSM->GetSubShape() );
1293   TopoDS_Face topF = TopoDS::Face( topSM->GetSubShape() );
1294
1295   vector< int > botEdgeIdVec;
1296   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
1297
1298   bool isForward[NB_WALL_FACES] = { true, true, true, true };
1299   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
1300   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
1301
1302   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
1303   {
1304     TSideFace * sideFace = mySide->GetComponent( iF );
1305     if ( !sideFace )
1306       RETURN_BAD_RESULT("NULL TSideFace");
1307     int fID = sideFace->FaceID();
1308
1309     // fill myShapeIDMap
1310     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
1311          !sideFace->IsComplex())
1312       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
1313
1314     // side faces geometry
1315     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
1316     if ( !sideFace->GetPCurves( pcurves ))
1317       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
1318
1319     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
1320     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
1321
1322     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
1323     // edges 3D geometry
1324     vector< int > edgeIdVec;
1325     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
1326     for ( int isMax = 0; isMax < 2; ++isMax ) {
1327       {
1328         int eID = edgeIdVec[ isMax ];
1329         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
1330         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
1331         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
1332         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
1333       }
1334       {
1335         int eID = edgeIdVec[ isMax+2 ];
1336         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
1337         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
1338         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
1339         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
1340
1341         // corner points
1342         vector< int > vertexIdVec;
1343         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
1344         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
1345         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
1346       }
1347     }
1348     // pcurves on horizontal faces
1349     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
1350       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
1351         botPcurves[ iE ] = sideFace->HorizPCurve( false, botF );
1352         topPcurves[ iE ] = sideFace->HorizPCurve( true,  topF );
1353         break;
1354       }
1355     }
1356   }
1357   // horizontal faces geometry
1358   {
1359     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
1360     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( botF ), botPcurves, isForward );
1361     SMESH_Block::Insert( botF, ID_BOT_FACE, myShapeIDMap );
1362   }
1363   {
1364     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
1365     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( topF ), topPcurves, isForward );
1366     SMESH_Block::Insert( topF, ID_TOP_FACE, myShapeIDMap );
1367   }
1368
1369   // Fill map ShapeIndex to TParam2ColumnMap
1370   // ----------------------------------------
1371
1372   list< TSideFace* > fList;
1373   list< TSideFace* >::iterator fListIt;
1374   fList.push_back( mySide );
1375   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
1376   {
1377     int nb = (*fListIt)->NbComponents();
1378     for ( int i = 0; i < nb; ++i ) {
1379       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
1380         fList.push_back( comp );
1381     }
1382     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
1383       // columns for a base edge
1384       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
1385       bool isForward = (*fListIt)->IsForward();
1386       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1387
1388       // columns for vertices
1389       const SMDS_MeshNode* n0 = cols->begin()->second.front();
1390       id = n0->GetPosition()->GetShapeId();
1391       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
1392
1393       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
1394       id = n1->GetPosition()->GetShapeId();
1395       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
1396     }
1397   }
1398
1399 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
1400 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
1401 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
1402 //   SHOWYXZ("IN TEST PARAM" , testPar);
1403 //   SHOWYXZ("OUT TEST CORD" , testCoord);
1404 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
1405 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
1406 //   SHOWYXZ("OUT TEST PARAM" , testPar);
1407
1408   return true;
1409 }
1410
1411 //================================================================================
1412 /*!
1413  * \brief Return pointer to column of nodes
1414  * \param node - bottom node from which the returned column goes up
1415  * \retval const TNodeColumn* - the found column
1416  */
1417 //================================================================================
1418
1419 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
1420 {
1421   int sID = node->GetPosition()->GetShapeId();
1422
1423   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
1424     myShapeIndex2ColumnMap.find( sID );
1425   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
1426     const TParam2ColumnMap* cols = col_frw->second.first;
1427     TParam2ColumnIt u_col = cols->begin();
1428     for ( ; u_col != cols->end(); ++u_col )
1429       if ( u_col->second[ 0 ] == node )
1430         return & u_col->second;
1431   }
1432   return 0;
1433 }
1434
1435 //================================================================================
1436 /*!
1437  * \brief Check curve orientation of a bootom edge
1438   * \param meshDS - mesh DS
1439   * \param columnsMap - node columns map of side face
1440   * \param bottomEdge - the bootom edge
1441   * \param sideFaceID - side face in-block ID
1442   * \retval bool - true if orientation coinside with in-block froward orientation
1443  */
1444 //================================================================================
1445
1446 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
1447                                             const TParam2ColumnMap& columnsMap,
1448                                             const TopoDS_Edge &     bottomEdge,
1449                                             const int               sideFaceID)
1450 {
1451   bool isForward = false;
1452   if ( TAssocTool::IsClosedEdge( bottomEdge ))
1453   {
1454     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
1455   }
1456   else
1457   {
1458     const TNodeColumn& firstCol = columnsMap.begin()->second;
1459     const SMDS_MeshNode* bottomNode = firstCol[0];
1460     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
1461     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
1462   }
1463   // on 2 of 4 sides first vertex is end
1464   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
1465     isForward = !isForward;
1466   return isForward;
1467 }
1468
1469 //================================================================================
1470   /*!
1471    * \brief Find wall faces by bottom edges
1472     * \param mesh - the mesh
1473     * \param mainShape - the prism
1474     * \param bottomFace - the bottom face
1475     * \param bottomEdges - edges bounding the bottom face
1476     * \param wallFaces - faces list to fill in
1477    */
1478 //================================================================================
1479
1480 bool StdMeshers_PrismAsBlock::GetWallFaces( SMESH_Mesh*                     mesh,
1481                                             const TopoDS_Shape &            mainShape,
1482                                             const TopoDS_Shape &            bottomFace,
1483                                             const std::list< TopoDS_Edge >& bottomEdges,
1484                                             std::list< TopoDS_Face >&       wallFaces)
1485 {
1486   wallFaces.clear();
1487
1488   TopTools_IndexedMapOfShape faceMap;
1489   TopExp::MapShapes( mainShape, TopAbs_FACE, faceMap );
1490
1491   list< TopoDS_Edge >::const_iterator edge = bottomEdges.begin();
1492   for ( ; edge != bottomEdges.end(); ++edge )
1493   {
1494     TopTools_ListIteratorOfListOfShape ancestIt = mesh->GetAncestors( *edge );
1495     for ( ; ancestIt.More(); ancestIt.Next() )
1496     {
1497       const TopoDS_Shape& ancestor = ancestIt.Value();
1498       if ( ancestor.ShapeType() == TopAbs_FACE && // face
1499            !bottomFace.IsSame( ancestor ) &&      // not bottom
1500            faceMap.FindIndex( ancestor ))         // belongs to the prism
1501       {
1502         wallFaces.push_back( TopoDS::Face( ancestor ));
1503         break;
1504       }
1505     }
1506   }
1507   return ( wallFaces.size() == bottomEdges.size() );
1508 }
1509
1510 //================================================================================
1511 /*!
1512  * \brief Constructor
1513   * \param faceID - in-block ID
1514   * \param face - geom face
1515   * \param columnsMap - map of node columns
1516   * \param first - first normalized param
1517   * \param last - last normalized param
1518  */
1519 //================================================================================
1520
1521 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_MesherHelper* helper,
1522                                               const int           faceID,
1523                                               const TopoDS_Face&  face,
1524                                               const TopoDS_Edge&  baseEdge,
1525                                               TParam2ColumnMap*   columnsMap,
1526                                               const double        first,
1527                                               const double        last):
1528   myID( faceID ),
1529   myParamToColumnMap( columnsMap ),
1530   myBaseEdge( baseEdge ),
1531   myHelper( helper )
1532 {
1533   mySurface.Initialize( face );
1534   myParams.resize( 1 );
1535   myParams[ 0 ] = make_pair( first, last );
1536   myIsForward = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
1537                                                         *myParamToColumnMap,
1538                                                         myBaseEdge, myID );
1539 }
1540
1541 //================================================================================
1542 /*!
1543  * \brief Constructor of complex side face
1544  */
1545 //================================================================================
1546
1547 StdMeshers_PrismAsBlock::TSideFace::
1548 TSideFace(const vector< TSideFace* >&             components,
1549           const vector< pair< double, double> > & params)
1550   :myID( components[0] ? components[0]->myID : 0 ),
1551    myParamToColumnMap( 0 ),
1552    myParams( params ),
1553    myIsForward( true ),
1554    myComponents( components ),
1555    myHelper( components[0] ? components[0]->myHelper : 0 )
1556 {}
1557 //================================================================================
1558 /*!
1559  * \brief Copy constructor
1560   * \param other - other side
1561  */
1562 //================================================================================
1563
1564 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other )
1565 {
1566   myID               = other.myID;
1567   mySurface          = other.mySurface;
1568   myBaseEdge         = other.myBaseEdge;
1569   myParams           = other.myParams;
1570   myIsForward        = other.myIsForward;
1571   myHelper           = other.myHelper;
1572   myParamToColumnMap = other.myParamToColumnMap;
1573
1574   myComponents.resize( other.myComponents.size());
1575   for (int i = 0 ; i < myComponents.size(); ++i )
1576     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
1577 }
1578
1579 //================================================================================
1580 /*!
1581  * \brief Deletes myComponents
1582  */
1583 //================================================================================
1584
1585 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
1586 {
1587   for (int i = 0 ; i < myComponents.size(); ++i )
1588     if ( myComponents[ i ] )
1589       delete myComponents[ i ];
1590 }
1591
1592 //================================================================================
1593 /*!
1594  * \brief Return geometry of the vertical curve
1595   * \param isMax - true means curve located closer to (1,1,1) block point
1596   * \retval Adaptor3d_Curve* - curve adaptor
1597  */
1598 //================================================================================
1599
1600 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
1601 {
1602   if ( !myComponents.empty() ) {
1603     if ( isMax )
1604       return myComponents.back()->VertiCurve(isMax);
1605     else
1606       return myComponents.front()->VertiCurve(isMax);
1607   }
1608   double f = myParams[0].first, l = myParams[0].second;
1609   if ( !myIsForward ) std::swap( f, l );
1610   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
1611 }
1612
1613 //================================================================================
1614 /*!
1615  * \brief Return geometry of the top or bottom curve
1616   * \param isTop - 
1617   * \retval Adaptor3d_Curve* - 
1618  */
1619 //================================================================================
1620
1621 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
1622 {
1623   return new THorizontalEdgeAdaptor( this, isTop );
1624 }
1625
1626 //================================================================================
1627 /*!
1628  * \brief Return pcurves
1629   * \param pcurv - array of 4 pcurves
1630   * \retval bool - is a success
1631  */
1632 //================================================================================
1633
1634 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
1635 {
1636   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
1637
1638   for ( int i = 0 ; i < 4 ; ++i ) {
1639     Handle(Geom2d_Line) line;
1640     switch ( iEdge[ i ] ) {
1641     case TOP_EDGE:
1642       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
1643     case BOTTOM_EDGE:
1644       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
1645     case V0_EDGE:
1646       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
1647     case V1_EDGE:
1648       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
1649     }
1650     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
1651   }
1652   return true;
1653 }
1654
1655 //================================================================================
1656 /*!
1657  * \brief Returns geometry of pcurve on a horizontal face
1658   * \param isTop - is top or bottom face
1659   * \param horFace - a horizontal face
1660   * \retval Adaptor2d_Curve2d* - curve adaptor
1661  */
1662 //================================================================================
1663
1664 Adaptor2d_Curve2d*
1665 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
1666                                                 const TopoDS_Face& horFace) const
1667 {
1668   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
1669 }
1670
1671 //================================================================================
1672 /*!
1673  * \brief Return a component corresponding to parameter
1674   * \param U - parameter along a horizontal size
1675   * \param localU - parameter along a horizontal size of a component
1676   * \retval TSideFace* - found component
1677  */
1678 //================================================================================
1679
1680 StdMeshers_PrismAsBlock::TSideFace*
1681 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
1682 {
1683   localU = U;
1684   if ( myComponents.empty() )
1685     return const_cast<TSideFace*>( this );
1686
1687   int i;
1688   for ( i = 0; i < myComponents.size(); ++i )
1689     if ( U < myParams[ i ].second )
1690       break;
1691   if ( i >= myComponents.size() )
1692     i = myComponents.size() - 1;
1693
1694   double f = myParams[ i ].first, l = myParams[ i ].second;
1695   localU = ( U - f ) / ( l - f );
1696   return myComponents[ i ];
1697 }
1698
1699 //================================================================================
1700 /*!
1701  * \brief Find node columns for a parameter
1702   * \param U - parameter along a horizontal edge
1703   * \param col1 - the 1st found column
1704   * \param col2 - the 2nd found column
1705   * \retval r - normalized position of U between the found columns
1706  */
1707 //================================================================================
1708
1709 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
1710                                                       TParam2ColumnIt & col1,
1711                                                       TParam2ColumnIt & col2) const
1712 {
1713   double u = U, r = 0;
1714   if ( !myComponents.empty() ) {
1715     TSideFace * comp = GetComponent(U,u);
1716     return comp->GetColumns( u, col1, col2 );
1717   }
1718
1719   if ( !myIsForward )
1720     u = 1 - u;
1721   double f = myParams[0].first, l = myParams[0].second;
1722   u = f + u * ( l - f );
1723
1724   col1 = col2 = getColumn( myParamToColumnMap, u );
1725   if ( ++col2 == myParamToColumnMap->end() ) {
1726     --col2;
1727     r = 0.5;
1728   }
1729   else {
1730 //     if ( !myIsForward )
1731 //       std::swap( col1, col2 );
1732     double uf = col1->first;
1733     double ul = col2->first;
1734     r = ( u - uf ) / ( ul - uf );
1735   }
1736   return r;
1737 }
1738
1739 //================================================================================
1740 /*!
1741  * \brief Return coordinates by normalized params
1742   * \param U - horizontal param
1743   * \param V - vertical param
1744   * \retval gp_Pnt - result point
1745  */
1746 //================================================================================
1747
1748 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
1749                                                  const Standard_Real V) const
1750 {
1751   double u;
1752   if ( !myComponents.empty() ) {
1753     TSideFace * comp = GetComponent(U,u);
1754     return comp->Value( u, V );
1755   }
1756
1757   TParam2ColumnIt u_col1, u_col2;
1758   double vR, hR = GetColumns( U, u_col1, u_col2 );
1759
1760   const SMDS_MeshNode* n1 = 0;
1761   const SMDS_MeshNode* n2 = 0;
1762   const SMDS_MeshNode* n3 = 0;
1763   const SMDS_MeshNode* n4 = 0;
1764   gp_XYZ pnt;
1765
1766   vR = getRAndNodes( & u_col1->second, V, n1, n2 );
1767   vR = getRAndNodes( & u_col2->second, V, n3, n4 );
1768   
1769   gp_XY uv1 = myHelper->GetNodeUV( mySurface.Face(), n1, n4);
1770   gp_XY uv2 = myHelper->GetNodeUV( mySurface.Face(), n2, n3);
1771   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
1772
1773   gp_XY uv3 = myHelper->GetNodeUV( mySurface.Face(), n3, n2);
1774   gp_XY uv4 = myHelper->GetNodeUV( mySurface.Face(), n4, n1);
1775   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
1776
1777   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
1778   
1779   return mySurface.Value( uv.X(), uv.Y() );
1780 }
1781
1782
1783 //================================================================================
1784 /*!
1785  * \brief Return boundary edge
1786   * \param edge - edge index
1787   * \retval TopoDS_Edge - found edge
1788  */
1789 //================================================================================
1790
1791 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
1792 {
1793   if ( !myComponents.empty() ) {
1794     switch ( iEdge ) {
1795     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
1796     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
1797     default: return TopoDS_Edge();
1798     }
1799   }
1800   TopoDS_Shape edge;
1801   const SMDS_MeshNode* node = 0;
1802   SMESHDS_Mesh * meshDS = myHelper->GetMesh()->GetMeshDS();
1803   TNodeColumn* column;
1804
1805   switch ( iEdge ) {
1806   case TOP_EDGE:
1807   case BOTTOM_EDGE:
1808     column = & (( ++myParamToColumnMap->begin())->second );
1809     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
1810     edge = myHelper->GetSubShapeByNode ( node, meshDS );
1811     if ( edge.ShapeType() == TopAbs_VERTEX ) {
1812       column = & ( myParamToColumnMap->begin()->second );
1813       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
1814     }
1815     break;
1816   case V0_EDGE:
1817   case V1_EDGE: {
1818     bool back = ( iEdge == V1_EDGE );
1819     if ( !myIsForward ) back = !back;
1820     if ( back )
1821       column = & ( myParamToColumnMap->rbegin()->second );
1822     else
1823       column = & ( myParamToColumnMap->begin()->second );
1824     if ( column->size() > 0 )
1825       edge = myHelper->GetSubShapeByNode( (*column)[ 1 ], meshDS );
1826     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
1827       node = column->front();
1828     break;
1829   }
1830   default:;
1831   }
1832   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
1833     return TopoDS::Edge( edge );
1834
1835   // find edge by 2 vertices
1836   TopoDS_Shape V1 = edge;
1837   TopoDS_Shape V2 = myHelper->GetSubShapeByNode( node, meshDS );
1838   if ( V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
1839   {
1840     TopTools_ListIteratorOfListOfShape ancestIt =
1841       myHelper->GetMesh()->GetAncestors( V1 );
1842     for ( ; ancestIt.More(); ancestIt.Next() )
1843     {
1844       const TopoDS_Shape & ancestor = ancestIt.Value();
1845       if ( ancestor.ShapeType() == TopAbs_EDGE )
1846         for ( TopExp_Explorer e( ancestor, TopAbs_VERTEX ); e.More(); e.Next() )
1847           if ( V2.IsSame( e.Current() ))
1848             return TopoDS::Edge( ancestor );
1849     }
1850   }
1851   return TopoDS_Edge();
1852 }
1853
1854 //================================================================================
1855 /*!
1856  * \brief Fill block subshapes
1857   * \param shapeMap - map to fill in
1858   * \retval int - nb inserted subshapes
1859  */
1860 //================================================================================
1861
1862 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
1863 {
1864   int nbInserted = 0;
1865
1866   // Insert edges
1867   vector< int > edgeIdVec;
1868   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
1869
1870   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
1871     TopoDS_Edge e = GetEdge( i );
1872     if ( !e.IsNull() ) {
1873       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
1874     }
1875   }
1876
1877   // Insert corner vertices
1878
1879   TParam2ColumnIt col1, col2 ;
1880   vector< int > vertIdVec;
1881
1882   // from V0 column
1883   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
1884   GetColumns(0, col1, col2 );
1885   const SMDS_MeshNode* node0 = col1->second.front();
1886   const SMDS_MeshNode* node1 = col1->second.back();
1887   TopoDS_Shape v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
1888   TopoDS_Shape v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
1889   if ( v0.ShapeType() == TopAbs_VERTEX ) {
1890     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
1891   }
1892   if ( v1.ShapeType() == TopAbs_VERTEX ) {
1893     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
1894   }
1895   
1896   // from V1 column
1897   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
1898   GetColumns(1, col1, col2 );
1899   node0 = col2->second.front();
1900   node1 = col2->second.back();
1901   v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
1902   v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
1903   if ( v0.ShapeType() == TopAbs_VERTEX ) {
1904     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
1905   }
1906   if ( v1.ShapeType() == TopAbs_VERTEX ) {
1907     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
1908   }
1909
1910 //   TopoDS_Vertex V0, V1, Vcom;
1911 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
1912 //   if ( !myIsForward ) std::swap( V0, V1 );
1913
1914 //   // bottom vertex IDs
1915 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
1916 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
1917 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
1918
1919 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
1920 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
1921 //     return false;
1922
1923 //   // insert one side edge
1924 //   int edgeID;
1925 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
1926 //   else                    edgeID = edgeIdVec[ _v1 ];
1927 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
1928
1929 //   // top vertex of the side edge
1930 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
1931 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
1932 //   if ( Vcom.IsSame( Vtop ))
1933 //     Vtop = TopExp::LastVertex( sideEdge );
1934 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
1935
1936 //   // other side edge
1937 //   sideEdge = GetEdge( V1_EDGE );
1938 //   if ( sideEdge.IsNull() )
1939 //     return false;
1940 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
1941 //   else                            edgeID = edgeIdVec[ _v1 ];
1942 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
1943   
1944 //   // top edge
1945 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
1946 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
1947
1948 //   // top vertex of the other side edge
1949 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
1950 //     return false;
1951 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
1952 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
1953
1954   return nbInserted;
1955 }
1956
1957 //================================================================================
1958 /*!
1959  * \brief Creates TVerticalEdgeAdaptor 
1960   * \param columnsMap - node column map
1961   * \param parameter - normalized parameter
1962  */
1963 //================================================================================
1964
1965 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
1966 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
1967 {
1968   myNodeColumn = & getColumn( columnsMap, parameter )->second;
1969 }
1970
1971 //================================================================================
1972 /*!
1973  * \brief Return coordinates for the given normalized parameter
1974   * \param U - normalized parameter
1975   * \retval gp_Pnt - coordinates
1976  */
1977 //================================================================================
1978
1979 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
1980 {
1981   const SMDS_MeshNode* n1;
1982   const SMDS_MeshNode* n2;
1983   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
1984   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
1985 }
1986
1987 //================================================================================
1988 /*!
1989  * \brief Return coordinates for the given normalized parameter
1990   * \param U - normalized parameter
1991   * \retval gp_Pnt - coordinates
1992  */
1993 //================================================================================
1994
1995 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
1996 {
1997   return mySide->TSideFace::Value( U, myV );
1998 }
1999
2000 //================================================================================
2001 /*!
2002  * \brief Return UV on pcurve for the given normalized parameter
2003   * \param U - normalized parameter
2004   * \retval gp_Pnt - coordinates
2005  */
2006 //================================================================================
2007
2008 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
2009 {
2010   TParam2ColumnIt u_col1, u_col2;
2011   double r = mySide->GetColumns( U, u_col1, u_col2 );
2012   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ]);
2013   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ]);
2014   return uv1 * ( 1 - r ) + uv2 * r;
2015 }