Salome HOME
SALOME_TESTS/Grids/smesh/mesh_Projection_2D_00/A0
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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 // 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 "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_ProjectionSource1D.hxx"
39 #include "StdMeshers_ProjectionSource2D.hxx"
40 #include "StdMeshers_ProjectionUtils.hxx"
41 #include "StdMeshers_Projection_1D.hxx"
42 #include "StdMeshers_Projection_1D2D.hxx"
43 #include "StdMeshers_Quadrangle_2D.hxx"
44
45 #include "utilities.h"
46
47 #include <BRepAdaptor_CompCurve.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B3d.hxx>
50 #include <Geom2dAdaptor_Curve.hxx>
51 #include <Geom2d_Line.hxx>
52 #include <Geom_Curve.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopTools_MapOfShape.hxx>
58 #include <TopTools_SequenceOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <gp_Ax2.hxx>
61 #include <gp_Ax3.hxx>
62
63 #include <limits>
64
65 using namespace std;
66
67 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
68 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
69 #define SHOWYXZ(msg, xyz) // {\
70 // gp_Pnt p (xyz); \
71 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
72 // }
73 #ifdef _DEBUG_
74 #define DBGOUT(msg) //cout << msg << endl;
75 #else
76 #define DBGOUT(msg)
77 #endif
78
79 namespace TAssocTool = StdMeshers_ProjectionUtils;
80
81 typedef SMESH_Comment TCom;
82
83 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
84        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
85        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
86        NB_WALL_FACES = 4 }; //
87
88 namespace {
89
90   //=======================================================================
91   /*!
92    * \brief Quadrangle algorithm
93    */
94   struct TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
95   {
96     TQuadrangleAlgo(int studyId, SMESH_Gen* gen)
97       : StdMeshers_Quadrangle_2D( gen->GetANewId(), studyId, gen)
98     {
99     }
100     static StdMeshers_Quadrangle_2D* instance( SMESH_Algo*         fatherAlgo,
101                                                SMESH_MesherHelper* helper=0)
102     {
103       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetStudyId(),
104                                                           fatherAlgo->GetGen() );
105       if ( helper &&
106            algo->myProxyMesh &&
107            algo->myProxyMesh->GetMesh() != helper->GetMesh() )
108         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *helper->GetMesh() ));
109
110       algo->myQuadList.clear();
111
112       if ( helper )
113         algo->_quadraticMesh = helper->GetIsQuadratic();
114
115       return algo;
116     }
117   };
118   //=======================================================================
119   /*!
120    * \brief Algorithm projecting 1D mesh
121    */
122   struct TProjction1dAlgo : public StdMeshers_Projection_1D
123   {
124     StdMeshers_ProjectionSource1D myHyp;
125
126     TProjction1dAlgo(int studyId, SMESH_Gen* gen)
127       : StdMeshers_Projection_1D( gen->GetANewId(), studyId, gen),
128         myHyp( gen->GetANewId(), studyId, gen)
129     {
130       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
131     }
132     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
133     {
134       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetStudyId(),
135                                                             fatherAlgo->GetGen() );
136       return algo;
137     }
138   };
139   //=======================================================================
140   /*!
141    * \brief Algorithm projecting 2D mesh
142    */
143   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
144   {
145     StdMeshers_ProjectionSource2D myHyp;
146
147     TProjction2dAlgo(int studyId, SMESH_Gen* gen)
148       : StdMeshers_Projection_1D2D( gen->GetANewId(), studyId, gen),
149         myHyp( gen->GetANewId(), studyId, gen)
150     {
151       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
152     }
153     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
154     {
155       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetStudyId(),
156                                                             fatherAlgo->GetGen() );
157       return algo;
158     }
159   };
160   //=======================================================================
161   /*!
162    * \brief Returns already computed EDGEs
163    */
164   void getPrecomputedEdges( SMESH_MesherHelper&    theHelper,
165                             const TopoDS_Shape&    theShape,
166                             vector< TopoDS_Edge >& theEdges)
167   {
168     theEdges.clear();
169
170     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
171     SMESHDS_SubMesh* sm;
172
173     TopTools_IndexedMapOfShape edges;
174     TopExp::MapShapes( theShape, TopAbs_EDGE, edges );
175     for ( int iE = 1; iE <= edges.Extent(); ++iE )
176     {
177       const TopoDS_Shape edge = edges( iE );
178       if (( ! ( sm = meshDS->MeshElements( edge ))) ||
179           ( sm->NbElements() == 0 ))
180         continue;
181
182       // there must not be FACEs meshed with triangles and sharing a computed EDGE
183       // as the precomputed EDGEs are used for propagation other to 'vertical' EDGEs
184       bool faceFound = false;
185       PShapeIteratorPtr faceIt =
186         theHelper.GetAncestors( edge, *theHelper.GetMesh(), TopAbs_FACE );
187       while ( const TopoDS_Shape* face = faceIt->next() )
188
189         if (( sm = meshDS->MeshElements( *face )) &&
190             ( sm->NbElements() > 0 ) &&
191             ( !theHelper.IsSameElemGeometry( sm, SMDSGeom_QUADRANGLE ) ))
192         {
193           faceFound;
194           break;
195         }
196       if ( !faceFound )
197         theEdges.push_back( TopoDS::Edge( edge ));
198     }
199   }
200
201   //================================================================================
202   /*!
203    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
204    *        Return false if the BOTTOM_SIDE is composite
205    */
206   //================================================================================
207
208   bool setBottomEdge( const TopoDS_Edge&   botE,
209                       FaceQuadStruct::Ptr& quad,
210                       const TopoDS_Shape&  face)
211   {
212     quad->side[ QUAD_TOP_SIDE  ].grid->Reverse();
213     quad->side[ QUAD_LEFT_SIDE ].grid->Reverse();
214     int edgeIndex = 0;
215     for ( size_t i = 0; i < quad->side.size(); ++i )
216     {
217       StdMeshers_FaceSidePtr quadSide = quad->side[i];
218       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
219         if ( botE.IsSame( quadSide->Edge( iE )))
220         {
221           if ( quadSide->NbEdges() > 1 )
222             return false;
223           edgeIndex = i;
224           i = quad->side.size(); // to quit from the outer loop
225           break;
226         }
227     }
228     if ( edgeIndex != QUAD_BOTTOM_SIDE )
229       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
230
231     quad->face = TopoDS::Face( face );
232
233     return true;
234   }
235
236   //================================================================================
237   /*!
238    * \brief Return iterator pointing to node column for the given parameter
239    * \param columnsMap - node column map
240    * \param parameter - parameter
241    * \retval TParam2ColumnMap::iterator - result
242    *
243    * it returns closest left column
244    */
245   //================================================================================
246
247   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
248                              const double            parameter )
249   {
250     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
251     if ( u_col != columnsMap->begin() )
252       --u_col;
253     return u_col; // return left column
254   }
255
256   //================================================================================
257   /*!
258    * \brief Return nodes around given parameter and a ratio
259    * \param column - node column
260    * \param param - parameter
261    * \param node1 - lower node
262    * \param node2 - upper node
263    * \retval double - ratio
264    */
265   //================================================================================
266
267   double getRAndNodes( const TNodeColumn*     column,
268                        const double           param,
269                        const SMDS_MeshNode* & node1,
270                        const SMDS_MeshNode* & node2)
271   {
272     if ( param >= 1.0 || column->size() == 1) {
273       node1 = node2 = column->back();
274       return 0;
275     }
276
277     int i = int( param * ( column->size() - 1 ));
278     double u0 = double( i )/ double( column->size() - 1 );
279     double r = ( param - u0 ) * ( column->size() - 1 );
280
281     node1 = (*column)[ i ];
282     node2 = (*column)[ i + 1];
283     return r;
284   }
285
286   //================================================================================
287   /*!
288    * \brief Compute boundary parameters of face parts
289     * \param nbParts - nb of parts to split columns into
290     * \param columnsMap - node columns of the face to split
291     * \param params - computed parameters
292    */
293   //================================================================================
294
295   void splitParams( const int               nbParts,
296                     const TParam2ColumnMap* columnsMap,
297                     vector< double > &      params)
298   {
299     params.clear();
300     params.reserve( nbParts + 1 );
301     TParam2ColumnIt last_par_col = --columnsMap->end();
302     double par = columnsMap->begin()->first; // 0.
303     double parLast = last_par_col->first;
304     params.push_back( par );
305     for ( int i = 0; i < nbParts - 1; ++ i )
306     {
307       double partSize = ( parLast - par ) / double ( nbParts - i );
308       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
309       if ( par_col->first == par ) {
310         ++par_col;
311         if ( par_col == last_par_col ) {
312           while ( i < nbParts - 1 )
313             params.push_back( par + partSize * i++ );
314           break;
315         }
316       }
317       par = par_col->first;
318       params.push_back( par );
319     }
320     params.push_back( parLast ); // 1.
321   }
322
323   //================================================================================
324   /*!
325    * \brief Return coordinate system for z-th layer of nodes
326    */
327   //================================================================================
328
329   gp_Ax2 getLayerCoordSys(const int                           z,
330                           const vector< const TNodeColumn* >& columns,
331                           int&                                xColumn)
332   {
333     // gravity center of a layer
334     gp_XYZ O(0,0,0);
335     int vertexCol = -1;
336     for ( int i = 0; i < columns.size(); ++i )
337     {
338       O += gpXYZ( (*columns[ i ])[ z ]);
339       if ( vertexCol < 0 &&
340            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
341         vertexCol = i;
342     }
343     O /= columns.size();
344
345     // Z axis
346     gp_Vec Z(0,0,0);
347     int iPrev = columns.size()-1;
348     for ( int i = 0; i < columns.size(); ++i )
349     {
350       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
351       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
352       Z += v1 ^ v2;
353       iPrev = i;
354     }
355
356     if ( vertexCol >= 0 )
357     {
358       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
359     }
360     if ( xColumn < 0 || xColumn >= columns.size() )
361     {
362       // select a column for X dir
363       double maxDist = 0;
364       for ( int i = 0; i < columns.size(); ++i )
365       {
366         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
367         if ( dist > maxDist )
368         {
369           xColumn = i;
370           maxDist = dist;
371         }
372       }
373     }
374
375     // X axis
376     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
377
378     return gp_Ax2( O, Z, X);
379   }
380
381   //================================================================================
382   /*!
383    * \brief Removes submeshes that are or can be meshed with regular grid from given list
384    *  \retval int - nb of removed submeshes
385    */
386   //================================================================================
387
388   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
389                        SMESH_MesherHelper*       helper,
390                        StdMeshers_Quadrangle_2D* quadAlgo)
391   {
392     int nbRemoved = 0;
393     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
394     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
395     while ( smIt != notQuadSubMesh.end() )
396     {
397       SMESH_subMesh* faceSm = *smIt;
398       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
399       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
400       bool toRemove;
401       if ( nbQuads > 0 )
402         toRemove = helper->IsStructured( faceSm );
403       else
404         toRemove = quadAlgo->CheckNbEdges( *helper->GetMesh(),
405                                            faceSm->GetSubShape() );
406       nbRemoved += toRemove;
407       if ( toRemove )
408         smIt = notQuadSubMesh.erase( smIt );
409       else
410         ++smIt;
411     }
412
413     return nbRemoved;
414   }
415
416   //================================================================================
417   /*!
418    * \brief Return and angle between two EDGEs
419    *  \return double - the angle normalized so that
420    * >~ 0  -> 2.0
421    *  PI/2 -> 1.0
422    *  PI   -> 0.0
423    * -PI/2 -> -1.0
424    * <~ 0  -> -2.0
425    */
426   //================================================================================
427
428   double normAngle(const TopoDS_Edge & E1, const TopoDS_Edge & E2, const TopoDS_Face & F)
429   {
430     return SMESH_MesherHelper::GetAngle( E1, E2, F ) / ( 0.5 * M_PI );
431   }
432
433   //================================================================================
434   /*!
435    * Consider continuous straight EDGES as one side - mark them to unite
436    */
437   //================================================================================
438
439   int countNbSides( const Prism_3D::TPrismTopo & thePrism,
440                     vector<int> &                nbUnitePerEdge,
441                     vector< double > &           edgeLength)
442   {
443     int nbEdges = thePrism.myNbEdgesInWires.front();  // nb outer edges
444     int nbSides = nbEdges;
445
446     
447     list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
448     std::advance( edgeIt, nbEdges-1 );
449     TopoDS_Edge   prevE = *edgeIt;
450     // bool isPrevStraight = SMESH_Algo::IsStraight( prevE );
451     int           iPrev = nbEdges - 1;
452
453     int iUnite = -1; // the first of united EDGEs
454
455     // analyse angles between EDGEs
456     int nbCorners = 0;
457     vector< bool > isCorner( nbEdges );
458     edgeIt = thePrism.myBottomEdges.begin();
459     for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
460     {
461       const TopoDS_Edge&  curE = *edgeIt;
462       edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
463
464       // double normAngle = normAngle( prevE, curE, thePrism.myBottom );
465       // isCorner[ iE ] = false;
466       // if ( normAngle < 2.0 )
467       // {
468       //   if ( normAngle < 0.001 ) // straight or obtuse angle
469       //   {
470       //     // unite EDGEs in order not to put a corner of the unit quadrangle at this VERTEX
471       //     if ( iUnite < 0 )
472       //       iUnite = iPrev;
473       //     nbUnitePerEdge[ iUnite ]++;
474       //     nbUnitePerEdge[ iE ] = -1;
475       //     --nbSides;
476       //   }
477       //   else
478       //   {
479       //     isCorner[ iE ] = true;
480       //     nbCorners++;
481       //     iUnite = -1;
482       //   }
483       // }
484       // prevE = curE;
485     }
486
487     if ( nbCorners > 4 )
488     {
489       // define which of corners to put on a side of the unit quadrangle
490     }
491     // edgeIt = thePrism.myBottomEdges.begin();
492     // for ( int iE = 0; iE < nbEdges; ++iE, ++edgeIt )
493     // {
494     //   const TopoDS_Edge&  curE = *edgeIt;
495     //   edgeLength[ iE ] = SMESH_Algo::EdgeLength( curE );
496
497     //   const bool isCurStraight = SMESH_Algo::IsStraight( curE );
498     //   if ( isPrevStraight && isCurStraight && SMESH_Algo::IsContinuous( prevE, curE ))
499     //   {
500     //     if ( iUnite < 0 )
501     //       iUnite = iPrev;
502     //     nbUnitePerEdge[ iUnite ]++;
503     //     nbUnitePerEdge[ iE ] = -1;
504     //     --nbSides;
505     //   }
506     //   else
507     //   {
508     //     iUnite = -1;
509     //   }
510     //   prevE          = curE;
511     //   isPrevStraight = isCurStraight;
512     //   iPrev = iE;
513     // }
514     
515     return nbSides;
516   }
517
518   void pointsToPython(const std::vector<gp_XYZ>& p)
519   {
520 #ifdef _DEBUG_
521     for ( int i = SMESH_Block::ID_V000; i < p.size(); ++i )
522     {
523       cout << "mesh.AddNode( " << p[i].X() << ", "<< p[i].Y() << ", "<< p[i].Z() << ") # " << i <<" " ;
524       SMESH_Block::DumpShapeID( i, cout ) << endl;
525     }
526 #endif
527   }
528 } // namespace
529
530 //=======================================================================
531 //function : StdMeshers_Prism_3D
532 //purpose  : 
533 //=======================================================================
534
535 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
536   :SMESH_3D_Algo(hypId, studyId, gen)
537 {
538   _name                    = "Prism_3D";
539   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
540   _onlyUnaryInput          = false; // accept all SOLIDs at once
541   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
542   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
543   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
544   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
545
546   //myProjectTriangles       = false;
547   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
548 }
549
550 //================================================================================
551 /*!
552  * \brief Destructor
553  */
554 //================================================================================
555
556 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
557 {}
558
559 //=======================================================================
560 //function : CheckHypothesis
561 //purpose  : 
562 //=======================================================================
563
564 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
565                                           const TopoDS_Shape&                  aShape,
566                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
567 {
568   // Check shape geometry
569 /*  PAL16229
570   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
571
572   // find not quadrangle faces
573   list< TopoDS_Shape > notQuadFaces;
574   int nbEdge, nbWire, nbFace = 0;
575   TopExp_Explorer exp( aShape, TopAbs_FACE );
576   for ( ; exp.More(); exp.Next() ) {
577     ++nbFace;
578     const TopoDS_Shape& face = exp.Current();
579     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
580     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
581     if (  nbEdge!= 4 || nbWire!= 1 ) {
582       if ( !notQuadFaces.empty() ) {
583         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
584              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
585           RETURN_BAD_RESULT("Different not quad faces");
586       }
587       notQuadFaces.push_back( face );
588     }
589   }
590   if ( !notQuadFaces.empty() )
591   {
592     if ( notQuadFaces.size() != 2 )
593       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
594
595     // check total nb faces
596     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
597     if ( nbFace != nbEdge + 2 )
598       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
599   }
600 */
601   // no hypothesis
602   aStatus = SMESH_Hypothesis::HYP_OK;
603   return true;
604 }
605
606 //=======================================================================
607 //function : Compute
608 //purpose  : Compute mesh on a COMPOUND of SOLIDs
609 //=======================================================================
610
611 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
612 {
613   SMESH_MesherHelper helper( theMesh );
614   myHelper = &helper;
615
616   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
617   if ( nbSolids < 1 )
618     return true;
619
620   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
621   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
622
623   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
624   list< TopoDS_Face > meshedFaces, notQuadMeshedFaces, notQuadFaces;
625   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
626   //StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this );
627   for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
628   {
629     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
630     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
631     if ( !faceSM->IsEmpty() )
632     {
633       if ( !meshHasQuads ||
634            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
635            !helper.IsStructured( faceSM )
636            )
637         notQuadMeshedFaces.push_front( face );
638       else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
639         meshedFaces.push_front( face );
640       else
641         meshedFaces.push_back( face );
642     }
643     // not add not quadrilateral FACE as we can't compute it
644     // else if ( !quadAlgo->CheckNbEdges( theMesh, face ))
645     // // not add not quadrilateral FACE as it can be a prism side
646     // // else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
647     // {
648     //   notQuadFaces.push_back( face );
649     // }
650   }
651   // notQuadFaces are of medium priority, put them before ordinary meshed faces
652   meshedFaces.splice( meshedFaces.begin(), notQuadFaces );
653   // notQuadMeshedFaces are of highest priority, put them before notQuadFaces
654   meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
655
656   Prism_3D::TPrismTopo prism;
657
658   if ( nbSolids == 1 )
659   {
660     if ( !meshedFaces.empty() )
661       prism.myBottom = meshedFaces.front();
662     return ( initPrism( prism, TopExp_Explorer( theShape, TopAbs_SOLID ).Current() ) &&
663              compute( prism ));
664   }
665
666   // find propagation chains from already computed EDGEs
667   vector< TopoDS_Edge > computedEdges;
668   getPrecomputedEdges( helper, theShape, computedEdges );
669   myPropagChains = new TopTools_IndexedMapOfShape[ computedEdges.size() + 1 ];
670   SMESHUtils::ArrayDeleter< TopTools_IndexedMapOfShape > pcDel( myPropagChains );
671   for ( size_t i = 0, nb = 0; i < computedEdges.size(); ++i )
672   {
673     StdMeshers_ProjectionUtils::GetPropagationEdge( &theMesh, TopoDS_Edge(),
674                                                     computedEdges[i], myPropagChains + nb );
675     if ( myPropagChains[ nb ].Extent() < 2 ) // an empty map is a termination sign
676       myPropagChains[ nb ].Clear();
677     else
678       nb++;
679   }
680
681   TopTools_MapOfShape meshedSolids;
682   list< Prism_3D::TPrismTopo > meshedPrism;
683   TopTools_ListIteratorOfListOfShape solidIt;
684
685   while ( meshedSolids.Extent() < nbSolids )
686   {
687     if ( _computeCanceled )
688       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
689
690     // compute prisms having avident computed source FACE
691     while ( !meshedFaces.empty() )
692     {
693       TopoDS_Face face = meshedFaces.front();
694       meshedFaces.pop_front();
695       TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( face );
696       while ( !solidList.IsEmpty() )
697       {
698         TopoDS_Shape solid = solidList.First();
699         solidList.RemoveFirst();
700         if ( meshedSolids.Add( solid ))
701         {
702           prism.Clear();
703           prism.myBottom = face;
704           if ( !initPrism( prism, solid ) ||
705                !compute( prism ))
706             return false;
707
708           SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
709           if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
710           {
711             meshedFaces.push_front( prism.myTop );
712           }
713           meshedPrism.push_back( prism );
714         }
715       }
716     }
717     if ( meshedSolids.Extent() == nbSolids )
718       break;
719
720     // below in the loop we try to find source FACEs somehow
721
722     // project mesh from source FACEs of computed prisms to
723     // prisms sharing wall FACEs
724     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
725     for ( ; prismIt != meshedPrism.end(); ++prismIt )
726     {
727       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
728       {
729         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
730         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
731         {
732           const TopoDS_Face& wFace = (*wQuad)->face;
733           TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( wFace );
734           solidIt.Initialize( solidList );
735           while ( solidIt.More() )
736           {
737             const TopoDS_Shape& solid = solidIt.Value();
738             if ( meshedSolids.Contains( solid )) {
739               solidList.Remove( solidIt );
740               continue; // already computed prism
741             }
742             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
743             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ].grid->Edge(0);
744             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
745                                                                TopAbs_FACE);
746             while ( const TopoDS_Shape* f = faceIt->next() )
747             {
748               const TopoDS_Face& candidateF = TopoDS::Face( *f );
749               prism.Clear();
750               prism.myBottom  = candidateF;
751               mySetErrorToSM = false;
752               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
753                    myHelper->IsSubShape( candidateF, solid ) &&
754                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
755                    initPrism( prism, solid ) &&
756                    project2dMesh( prismIt->myBottom, candidateF))
757               {
758                 mySetErrorToSM = true;
759                 if ( !compute( prism ))
760                   return false;
761                 SMESHDS_SubMesh* smDS = theMesh.GetMeshDS()->MeshElements( prism.myTop );
762                 if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
763                 {
764                   meshedFaces.push_front( prism.myTop );
765                   meshedFaces.push_front( prism.myBottom );
766                 }
767                 meshedPrism.push_back( prism );
768                 meshedSolids.Add( solid );
769               }
770               InitComputeError();
771             }
772             mySetErrorToSM = true;
773             InitComputeError();
774             if ( meshedSolids.Contains( solid ))
775               solidList.Remove( solidIt );
776             else
777               solidIt.Next();
778           }
779         }
780       }
781       if ( !meshedFaces.empty() )
782         break; // to compute prisms with avident sources
783     }
784
785     // find FACEs with local 1D hyps, which has to be computed by now,
786     // or at least any computed FACEs
787     for ( int iF = 1; ( meshedFaces.empty() && iF < faceToSolids.Extent() ); ++iF )
788     {
789       const TopoDS_Face&               face = TopoDS::Face( faceToSolids.FindKey( iF ));
790       const TopTools_ListOfShape& solidList = faceToSolids.FindFromKey( face );
791       if ( solidList.IsEmpty() ) continue;
792       SMESH_subMesh*                 faceSM = theMesh.GetSubMesh( face );
793       if ( !faceSM->IsEmpty() )
794       {
795         meshedFaces.push_back( face ); // lower priority
796       }
797       else
798       {
799         bool allSubMeComputed = true;
800         SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(false,true);
801         while ( smIt->more() && allSubMeComputed )
802           allSubMeComputed = smIt->next()->IsMeshComputed();
803         if ( allSubMeComputed )
804         {
805           faceSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
806           if ( !faceSM->IsEmpty() )
807             meshedFaces.push_front( face ); // higher priority
808           else
809             faceSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
810         }
811       }
812     }
813
814
815     // TODO. there are other ways to find out the source FACE:
816     // propagation, topological similarity, ect.
817
818     // simply try to mesh all not meshed SOLIDs
819     if ( meshedFaces.empty() )
820     {
821       for ( TopExp_Explorer solid( theShape, TopAbs_SOLID ); solid.More(); solid.Next() )
822       {
823         mySetErrorToSM = false;
824         prism.Clear();
825         if ( !meshedSolids.Contains( solid.Current() ) &&
826              initPrism( prism, solid.Current() ))
827         {
828           mySetErrorToSM = true;
829           if ( !compute( prism ))
830             return false;
831           meshedFaces.push_front( prism.myTop );
832           meshedFaces.push_front( prism.myBottom );
833           meshedPrism.push_back( prism );
834           meshedSolids.Add( solid.Current() );
835         }
836         mySetErrorToSM = true;
837       }
838     }
839
840     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
841     {
842       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
843         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
844
845       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
846       TopExp_Explorer solid( theShape, TopAbs_SOLID );
847       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
848         if ( !meshedSolids.Contains( solid.Current() ))
849         {
850           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
851           sm->GetComputeError() = err;
852         }
853       return error( err );
854     }
855   }
856   return true;
857 }
858
859 //================================================================================
860 /*!
861  * \brief Find wall faces by bottom edges
862  */
863 //================================================================================
864
865 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
866                                         const int              totalNbFaces)
867 {
868   thePrism.myWallQuads.clear();
869
870   SMESH_Mesh* mesh = myHelper->GetMesh();
871
872   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
873
874   TopTools_MapOfShape faceMap;
875   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;   
876   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
877                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
878
879   // ------------------------------
880   // Get the 1st row of wall FACEs
881   // ------------------------------
882
883   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
884   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
885   int iE = 0;
886   double f,l;
887   while ( edge != thePrism.myBottomEdges.end() )
888   {
889     ++iE;
890     if ( BRep_Tool::Curve( *edge, f,l ).IsNull() )
891     {
892       edge = thePrism.myBottomEdges.erase( edge );
893       --iE;
894       --(*nbE);
895     }
896     else
897     {
898       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
899       for ( ; faceIt.More(); faceIt.Next() )
900       {
901         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
902         if ( !thePrism.myBottom.IsSame( face ))
903         {
904           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
905           if ( !quadList.back() )
906             return toSM( error(TCom("Side face #") << shapeID( face )
907                                << " not meshable with quadrangles"));
908           if ( ! setBottomEdge( *edge, quadList.back(), face ))
909             return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
910           thePrism.myWallQuads.push_back( quadList );
911           faceMap.Add( face );
912           break;
913         }
914       }
915       ++edge;
916     }
917     if ( iE == *nbE )
918     {
919       iE = 0;
920       ++nbE;
921     }
922   }
923
924   // -------------------------
925   // Find the rest wall FACEs
926   // -------------------------
927
928   // Compose a vector of indixes of right neighbour FACE for each wall FACE
929   // that is not so evident in case of several WIREs in the bottom FACE
930   thePrism.myRightQuadIndex.clear();
931   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
932     thePrism.myRightQuadIndex.push_back( i+1 );
933   list< int >::iterator nbEinW = thePrism.myNbEdgesInWires.begin();
934   for ( int iLeft = 0; nbEinW != thePrism.myNbEdgesInWires.end(); ++nbEinW )
935   {
936     thePrism.myRightQuadIndex[ iLeft + *nbEinW - 1 ] = iLeft; // 1st EDGE index of a current WIRE
937     iLeft += *nbEinW;
938   }
939
940   while ( totalNbFaces - faceMap.Extent() > 2 )
941   {
942     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
943     int nbKnownFaces;
944     do {
945       nbKnownFaces = faceMap.Extent();
946       StdMeshers_FaceSidePtr rightSide, topSide; // sides of the quad
947       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
948       {
949         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
950         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
951         {
952           const TopoDS_Edge & rightE = rightSide->Edge( iE );
953           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
954           for ( ; face.More(); face.Next() )
955             if ( faceMap.Add( face.Value() ))
956             {
957               // a new wall FACE encountered, store it in thePrism.myWallQuads
958               const int iRight = thePrism.myRightQuadIndex[i];
959               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
960               const TopoDS_Edge&   newBotE = topSide->Edge(0);
961               const TopoDS_Shape& newWallF = face.Value();
962               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
963               if ( !thePrism.myWallQuads[ iRight ].back() )
964                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
965                                    " not meshable with quadrangles"));
966               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
967                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
968             }
969         }
970       }
971     } while ( nbKnownFaces != faceMap.Extent() );
972
973     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
974     if ( totalNbFaces - faceMap.Extent() > 2 )
975     {
976       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
977       {
978         StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
979         const TopoDS_Edge &       topE = topSide->Edge( 0 );
980         if ( topSide->NbEdges() > 1 )
981           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
982                              shapeID( thePrism.myWallQuads[i].back()->face )
983                              << " has a composite top edge"));
984         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
985         for ( ; faceIt.More(); faceIt.Next() )
986           if ( faceMap.Add( faceIt.Value() ))
987           {
988             // a new wall FACE encountered, store it in wallQuads
989             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
990             if ( !thePrism.myWallQuads[ i ].back() )
991               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
992                                  " not meshable with quadrangles"));
993             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
994               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
995             if ( totalNbFaces - faceMap.Extent() == 2 )
996             {
997               i = thePrism.myWallQuads.size(); // to quit from the outer loop
998               break;
999             }
1000           }
1001       }
1002     }
1003   } // while ( totalNbFaces - faceMap.Extent() > 2 )
1004
1005   // ------------------
1006   // Find the top FACE
1007   // ------------------
1008
1009   if ( thePrism.myTop.IsNull() )
1010   {
1011     // now only top and bottom FACEs are not in the faceMap
1012     faceMap.Add( thePrism.myBottom );
1013     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE );f.More(); f.Next() )
1014       if ( !faceMap.Contains( f.Current() )) {
1015         thePrism.myTop = TopoDS::Face( f.Current() );
1016         break;
1017       }
1018     if ( thePrism.myTop.IsNull() )
1019       return toSM( error("Top face not found"));
1020   }
1021
1022   // Check that the top FACE shares all the top EDGEs
1023   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
1024   {
1025     StdMeshers_FaceSidePtr topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
1026     const TopoDS_Edge &       topE = topSide->Edge( 0 );
1027     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
1028       return toSM( error( TCom("Wrong source face (#") << shapeID( thePrism.myBottom )));
1029   }
1030
1031   return true;
1032 }
1033
1034 //=======================================================================
1035 //function : compute
1036 //purpose  : Compute mesh on a SOLID
1037 //=======================================================================
1038
1039 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
1040 {
1041   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
1042   if ( _computeCanceled )
1043     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
1044
1045   // Make all side FACEs of thePrism meshed with quads
1046   if ( !computeWalls( thePrism ))
1047     return false;
1048
1049   // Analyse mesh and geometry to find all block sub-shapes and submeshes
1050   if ( !myBlock.Init( myHelper, thePrism ))
1051     return toSM( error( myBlock.GetError()));
1052
1053   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1054
1055   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
1056
1057   // Try to get gp_Trsf to get all nodes from bottom ones
1058   vector<gp_Trsf> trsf;
1059   gp_Trsf bottomToTopTrsf;
1060   if ( !myBlock.GetLayersTransformation( trsf, thePrism ))
1061     trsf.clear();
1062   else if ( !trsf.empty() )
1063     bottomToTopTrsf = trsf.back();
1064
1065   // To compute coordinates of a node inside a block, it is necessary to know
1066   // 1. normalized parameters of the node by which
1067   // 2. coordinates of node projections on all block sub-shapes are computed
1068
1069   // So we fill projections on vertices at once as they are same for all nodes
1070   myShapeXYZ.resize( myBlock.NbSubShapes() );
1071   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
1072     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
1073     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
1074   }
1075
1076   // Projections on the top and bottom faces are taken from nodes existing
1077   // on these faces; find correspondence between bottom and top nodes
1078   myBotToColumnMap.clear();
1079   if ( !assocOrProjBottom2Top( bottomToTopTrsf ) ) // it also fills myBotToColumnMap
1080     return false;
1081
1082
1083   // Create nodes inside the block
1084
1085   // try to use transformation (issue 0020680)
1086   if ( !trsf.empty() )
1087   {
1088     // loop on nodes inside the bottom face
1089     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1090     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1091     {
1092       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1093       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
1094         continue; // node is not inside face 
1095
1096       // column nodes; middle part of the column are zero pointers
1097       TNodeColumn& column = bot_column->second;
1098       TNodeColumn::iterator columnNodes = column.begin();
1099       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1100       {
1101         const SMDS_MeshNode* & node = *columnNodes;
1102         if ( node ) continue; // skip bottom or top node
1103
1104         gp_XYZ coords = tBotNode.GetCoords();
1105         trsf[z-1].Transforms( coords );
1106         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1107         meshDS->SetNodeInVolume( node, volumeID );
1108       }
1109     } // loop on bottom nodes
1110   }
1111   else // use block approach
1112   {
1113     // loop on nodes inside the bottom face
1114     Prism_3D::TNode prevBNode;
1115     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1116     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1117     {
1118       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1119       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
1120         continue; // node is not inside the FACE 
1121
1122       // column nodes; middle part of the column are zero pointers
1123       TNodeColumn& column = bot_column->second;
1124
1125       gp_XYZ botParams, topParams;
1126       if ( !tBotNode.HasParams() )
1127       {
1128         // compute bottom node parameters
1129         gp_XYZ paramHint(-1,-1,-1);
1130         if ( prevBNode.IsNeighbor( tBotNode ))
1131           paramHint = prevBNode.GetParams();
1132         if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
1133                                          ID_BOT_FACE, paramHint ))
1134           return toSM( error(TCom("Can't compute normalized parameters for node ")
1135                              << tBotNode.myNode->GetID() << " on the face #"
1136                              << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
1137         prevBNode = tBotNode;
1138
1139         botParams = topParams = tBotNode.GetParams();
1140         topParams.SetZ( 1 );
1141
1142         // compute top node parameters
1143         if ( column.size() > 2 ) {
1144           gp_Pnt topCoords = gpXYZ( column.back() );
1145           if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
1146             return toSM( error(TCom("Can't compute normalized parameters ")
1147                                << "for node " << column.back()->GetID()
1148                                << " on the face #"<< column.back()->getshapeId() ));
1149         }
1150       }
1151       else // top nodes are created by projection using parameters
1152       {
1153         botParams = topParams = tBotNode.GetParams();
1154         topParams.SetZ( 1 );
1155       }
1156
1157       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
1158       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
1159
1160       // vertical loop
1161       TNodeColumn::iterator columnNodes = column.begin();
1162       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1163       {
1164         const SMDS_MeshNode* & node = *columnNodes;
1165         if ( node ) continue; // skip bottom or top node
1166
1167         // params of a node to create
1168         double rz = (double) z / (double) ( column.size() - 1 );
1169         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
1170
1171         // set coords on all faces and nodes
1172         const int nbSideFaces = 4;
1173         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
1174                                          SMESH_Block::ID_Fx1z,
1175                                          SMESH_Block::ID_F0yz,
1176                                          SMESH_Block::ID_F1yz };
1177         for ( int iF = 0; iF < nbSideFaces; ++iF )
1178           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
1179             return false;
1180
1181         // compute coords for a new node
1182         gp_XYZ coords;
1183         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
1184           return toSM( error("Can't compute coordinates by normalized parameters"));
1185
1186         // if ( !meshDS->MeshElements( volumeID ) ||
1187         //      meshDS->MeshElements( volumeID )->NbNodes() == 0 )
1188         //   pointsToPython(myShapeXYZ);
1189         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
1190         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
1191         SHOWYXZ("ShellPoint ",coords);
1192
1193         // create a node
1194         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1195         meshDS->SetNodeInVolume( node, volumeID );
1196       }
1197     } // loop on bottom nodes
1198   }
1199
1200   // Create volumes
1201
1202   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1203   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1204
1205   // loop on bottom mesh faces
1206   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1207   while ( faceIt->more() )
1208   {
1209     const SMDS_MeshElement* face = faceIt->next();
1210     if ( !face || face->GetType() != SMDSAbs_Face )
1211       continue;
1212
1213     // find node columns for each node
1214     int nbNodes = face->NbCornerNodes();
1215     vector< const TNodeColumn* > columns( nbNodes );
1216     for ( int i = 0; i < nbNodes; ++i )
1217     {
1218       const SMDS_MeshNode* n = face->GetNode( i );
1219       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1220         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1221         if ( bot_column == myBotToColumnMap.end() )
1222           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1223         columns[ i ] = & bot_column->second;
1224       }
1225       else {
1226         columns[ i ] = myBlock.GetNodeColumn( n );
1227         if ( !columns[ i ] )
1228           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1229       }
1230     }
1231     // create prisms
1232     AddPrisms( columns, myHelper );
1233
1234   } // loop on bottom mesh faces
1235
1236   // clear data
1237   myBotToColumnMap.clear();
1238   myBlock.Clear();
1239         
1240   return true;
1241 }
1242
1243 //=======================================================================
1244 //function : computeWalls
1245 //purpose  : Compute 2D mesh on walls FACEs of a prism
1246 //=======================================================================
1247
1248 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1249 {
1250   SMESH_Mesh*     mesh = myHelper->GetMesh();
1251   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1252   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1253
1254   TProjction1dAlgo*      projector1D = TProjction1dAlgo::instance( this );
1255   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1256
1257   SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1258   hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1259   hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1260
1261   // Discretize equally 'vertical' EDGEs
1262   // -----------------------------------
1263   // find source FACE sides for projection: either already computed ones or
1264   // the 'most composite' ones
1265   multimap< int, int > wgt2quad;
1266   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1267   {
1268     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1269     int wgt = 0; // "weight"
1270     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1271     {
1272       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1273       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1274       {
1275         ++wgt;
1276         const TopoDS_Edge& E = lftSide->Edge(i);
1277         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1278           wgt += 10;
1279         else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1280           wgt += 100;
1281       }
1282     }
1283     wgt2quad.insert( make_pair( wgt, iW ));
1284
1285     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1286     if ( myHelper->GetIsQuadratic() )
1287     {
1288       quad = thePrism.myWallQuads[iW].begin();
1289       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1290         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1291           (*quad)->side[ i ].grid->SetIgnoreMediumNodes( true );
1292     }
1293   }
1294
1295   // Project 'vertical' EDGEs, from left to right
1296   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1297   for ( ; w2q != wgt2quad.rend(); ++w2q )
1298   {
1299     const int iW = w2q->second;
1300     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1301     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1302     for ( ; quad != quads.end(); ++quad )
1303     {
1304       StdMeshers_FaceSidePtr rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1305       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1306       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1307                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1308       if ( swapLeftRight )
1309         std::swap( lftSide, rgtSide );
1310
1311       // assure that all the source (left) EDGEs are meshed
1312       int nbSrcSegments = 0;
1313       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1314       {
1315         const TopoDS_Edge& srcE = lftSide->Edge(i);
1316         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1317         if ( !srcSM->IsMeshComputed() ) {
1318           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1319           TopoDS_Edge prpgSrcE = findPropagationSource( srcE );
1320           if ( !prpgSrcE.IsNull() ) {
1321             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1322             projector1D->myHyp.SetSourceEdge( prpgSrcE );
1323             projector1D->Compute( *mesh, srcE );
1324             srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1325           }
1326           else {
1327             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1328             srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1329           }
1330           if ( !srcSM->IsMeshComputed() )
1331             return toSM( error( "Can't compute 1D mesh" ));
1332         }
1333         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1334       }
1335       // check target EDGEs
1336       int nbTgtMeshed = 0, nbTgtSegments = 0;
1337       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1338       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1339       {
1340         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1341         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1342         if (( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1343           ++nbTgtMeshed;
1344           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1345         }
1346       }
1347       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1348       {
1349         if ( nbTgtSegments != nbSrcSegments )
1350         {
1351           for ( int i = 0; i < lftSide->NbEdges(); ++i )
1352             addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1353           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1354             addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1355           return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1356                               << shapeID( lftSide->Edge(0) ) << " and #"
1357                               << shapeID( rgtSide->Edge(0) ) << ": "
1358                               << nbSrcSegments << " != " << nbTgtSegments ));
1359         }
1360         continue;
1361       }
1362       // Compute 'vertical projection'
1363       if ( nbTgtMeshed == 0 )
1364       {
1365         // compute nodes on target VERTEXes
1366         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1367         if ( srcNodeStr.size() == 0 )
1368           return toSM( error( TCom("Invalid node positions on edge #") <<
1369                               shapeID( lftSide->Edge(0) )));
1370         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1371         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1372         {
1373           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1374           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1375           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1376           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1377           newNodes[ is2ndV ? 0 : newNodes.size()-1 ] = (SMDS_MeshNode*) n;
1378         }
1379
1380         // compute nodes on target EDGEs
1381         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1382         rgtSide->Reverse(); // direct it same as the lftSide
1383         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1384         TopoDS_Edge tgtEdge;
1385         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1386         {
1387           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1388           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1389           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1390           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1391         }
1392         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1393         {
1394           // find an EDGE to set a new segment
1395           std::pair<int, TopAbs_ShapeEnum> id2type = 
1396             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1397           if ( id2type.second != TopAbs_EDGE )
1398           {
1399             // new nodes are on different EDGEs; put one of them on VERTEX
1400             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1401             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1402             const gp_Pnt           p = BRep_Tool::Pnt( rgtSide->LastVertex( edgeIndex ));
1403             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1404                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1405             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1406             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], rgtSide->LastVertex( edgeIndex ));
1407             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1408             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1409           }
1410           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1411           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1412         }
1413         myHelper->SetElementsOnShape( true );
1414         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1415         {
1416           const TopoDS_Edge& E = rgtSide->Edge( i );
1417           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1418           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1419         }
1420
1421         // to continue projection from the just computed side as a source
1422         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1423         {
1424           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1425           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1426           wgt2quad.insert( wgt2quadKeyVal );
1427           w2q = wgt2quad.rbegin();
1428         }
1429       }
1430       else
1431       {
1432         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1433         //return toSM( error("Partial projection not implemented"));
1434       }
1435     } // loop on quads of a composite wall side
1436   } // loop on the ordered wall sides
1437
1438
1439
1440   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1441   {
1442     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1443     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1444     {
1445       // Top EDGEs must be projections from the bottom ones
1446       // to compute stuctured quad mesh on wall FACEs
1447       // ---------------------------------------------------
1448       {
1449         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0);
1450         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ].grid->Edge(0);
1451         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1452         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1453         SMESH_subMesh*    srcSM = botSM;
1454         SMESH_subMesh*    tgtSM = topSM;
1455         if ( !srcSM->IsMeshComputed() && tgtSM->IsMeshComputed() )
1456           std::swap( srcSM, tgtSM );
1457
1458         if ( !srcSM->IsMeshComputed() )
1459         {
1460           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1461           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1462           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1463         }
1464         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1465
1466         if ( tgtSM->IsMeshComputed() &&
1467              tgtSM->GetSubMeshDS()->NbNodes() != srcSM->GetSubMeshDS()->NbNodes() )
1468         {
1469           // the top EDGE is computed differently than the bottom one,
1470           // try to clear a wrong mesh
1471           bool isAdjFaceMeshed = false;
1472           PShapeIteratorPtr fIt = myHelper->GetAncestors( tgtSM->GetSubShape(),
1473                                                           *mesh, TopAbs_FACE );
1474           while ( const TopoDS_Shape* f = fIt->next() )
1475             if (( isAdjFaceMeshed = mesh->GetSubMesh( *f )->IsMeshComputed() ))
1476               break;
1477           if ( isAdjFaceMeshed )
1478             return toSM( error( TCom("Different nb of segment on logically horizontal edges #")
1479                                 << shapeID( botE ) << " and #"
1480                                 << shapeID( topE ) << ": "
1481                                 << tgtSM->GetSubMeshDS()->NbElements() << " != "
1482                                 << srcSM->GetSubMeshDS()->NbElements() ));
1483           tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1484         }
1485         if ( !tgtSM->IsMeshComputed() )
1486         {
1487           // compute nodes on VERTEXes
1488           SMESH_subMeshIteratorPtr smIt = tgtSM->getDependsOnIterator(/*includeSelf=*/false);
1489           while ( smIt->more() )
1490             smIt->next()->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1491           // project segments
1492           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1493           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1494           projector1D->InitComputeError();
1495           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1496           if ( !ok )
1497           {
1498             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1499             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1500             tgtSM->GetComputeError() = err;
1501             return false;
1502           }
1503         }
1504         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1505       }
1506
1507       // Compute quad mesh on wall FACEs
1508       // -------------------------------
1509       const TopoDS_Face& face = (*quad)->face;
1510       SMESH_subMesh* fSM = mesh->GetSubMesh( face );
1511       if ( ! fSM->IsMeshComputed() )
1512       {
1513         // make all EDGES meshed
1514         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1515         if ( !fSM->SubMeshesComputed() )
1516           return toSM( error( COMPERR_BAD_INPUT_MESH,
1517                               "Not all edges have valid algorithm and hypothesis"));
1518         // mesh the <face>
1519         quadAlgo->InitComputeError();
1520         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1521         bool ok = quadAlgo->Compute( *mesh, face );
1522         fSM->GetComputeError() = quadAlgo->GetComputeError();
1523         if ( !ok )
1524           return false;
1525         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1526       }
1527       if ( myHelper->GetIsQuadratic() )
1528       {
1529         // fill myHelper with medium nodes built by quadAlgo
1530         SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements();
1531         while ( fIt->more() )
1532           myHelper->AddTLinks( dynamic_cast<const SMDS_MeshFace*>( fIt->next() ));
1533       }
1534     }
1535   }
1536
1537   return true;
1538 }
1539
1540 //=======================================================================
1541 /*!
1542  * \brief Returns a source EDGE of propagation to a given EDGE
1543  */
1544 //=======================================================================
1545
1546 TopoDS_Edge StdMeshers_Prism_3D::findPropagationSource( const TopoDS_Edge& E )
1547 {
1548   for ( size_t i = 0; !myPropagChains[i].IsEmpty(); ++i )
1549     if ( myPropagChains[i].Contains( E ))
1550       return TopoDS::Edge( myPropagChains[i].FindKey( 1 ));
1551
1552   return TopoDS_Edge();
1553 }
1554
1555 //=======================================================================
1556 //function : Evaluate
1557 //purpose  : 
1558 //=======================================================================
1559
1560 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1561                                    const TopoDS_Shape& theShape,
1562                                    MapShapeNbElems&    aResMap)
1563 {
1564   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1565   {
1566     bool ok = true;
1567     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1568       ok &= Evaluate( theMesh, it.Value(), aResMap );
1569     return ok;
1570   }
1571   SMESH_MesherHelper helper( theMesh );
1572   myHelper = &helper;
1573   myHelper->SetSubShape( theShape );
1574
1575   // find face contains only triangles
1576   vector < SMESH_subMesh * >meshFaces;
1577   TopTools_SequenceOfShape aFaces;
1578   int NumBase = 0, i = 0, NbQFs = 0;
1579   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1580     i++;
1581     aFaces.Append(exp.Current());
1582     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1583     meshFaces.push_back(aSubMesh);
1584     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1585     if( anIt==aResMap.end() )
1586       return toSM( error( "Submesh can not be evaluated"));
1587
1588     std::vector<int> aVec = (*anIt).second;
1589     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1590     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1591     if( nbtri==0 && nbqua>0 ) {
1592       NbQFs++;
1593     }
1594     if( nbtri>0 ) {
1595       NumBase = i;
1596     }
1597   }
1598
1599   if(NbQFs<4) {
1600     std::vector<int> aResVec(SMDSEntity_Last);
1601     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1602     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1603     aResMap.insert(std::make_pair(sm,aResVec));
1604     return toSM( error( "Submesh can not be evaluated" ));
1605   }
1606
1607   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1608
1609   // find number of 1d elems for base face
1610   int nb1d = 0;
1611   TopTools_MapOfShape Edges1;
1612   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1613     Edges1.Add(exp.Current());
1614     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1615     if( sm ) {
1616       MapShapeNbElemsItr anIt = aResMap.find(sm);
1617       if( anIt == aResMap.end() ) continue;
1618       std::vector<int> aVec = (*anIt).second;
1619       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1620     }
1621   }
1622   // find face opposite to base face
1623   int OppNum = 0;
1624   for(i=1; i<=6; i++) {
1625     if(i==NumBase) continue;
1626     bool IsOpposite = true;
1627     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1628       if( Edges1.Contains(exp.Current()) ) {
1629         IsOpposite = false;
1630         break;
1631       }
1632     }
1633     if(IsOpposite) {
1634       OppNum = i;
1635       break;
1636     }
1637   }
1638   // find number of 2d elems on side faces
1639   int nb2d = 0;
1640   for(i=1; i<=6; i++) {
1641     if( i==OppNum || i==NumBase ) continue;
1642     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1643     if( anIt == aResMap.end() ) continue;
1644     std::vector<int> aVec = (*anIt).second;
1645     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1646   }
1647   
1648   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
1649   std::vector<int> aVec = (*anIt).second;
1650   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
1651                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
1652   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1653   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1654   int nb0d_face0 = aVec[SMDSEntity_Node];
1655   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
1656
1657   std::vector<int> aResVec(SMDSEntity_Last);
1658   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1659   if(IsQuadratic) {
1660     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1661     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1662     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
1663   }
1664   else {
1665     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
1666     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1667     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1668   }
1669   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1670   aResMap.insert(std::make_pair(sm,aResVec));
1671
1672   return true;
1673 }
1674
1675 //================================================================================
1676 /*!
1677  * \brief Create prisms
1678  * \param columns - columns of nodes generated from nodes of a mesh face
1679  * \param helper - helper initialized by mesh and shape to add prisms to
1680  */
1681 //================================================================================
1682
1683 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
1684                                      SMESH_MesherHelper*          helper)
1685 {
1686   int nbNodes = columns.size();
1687   int nbZ     = columns[0]->size();
1688   if ( nbZ < 2 ) return;
1689
1690   // find out orientation
1691   bool isForward = true;
1692   SMDS_VolumeTool vTool;
1693   int z = 1;
1694   switch ( nbNodes ) {
1695   case 3: {
1696     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
1697                                   (*columns[1])[z-1],
1698                                   (*columns[2])[z-1],
1699                                   (*columns[0])[z],   // top
1700                                   (*columns[1])[z],
1701                                   (*columns[2])[z] );
1702     vTool.Set( &tmpPenta );
1703     isForward  = vTool.IsForward();
1704     break;
1705   }
1706   case 4: {
1707     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
1708                                (*columns[2])[z-1], (*columns[3])[z-1],
1709                                (*columns[0])[z],   (*columns[1])[z],   // top
1710                                (*columns[2])[z],   (*columns[3])[z] );
1711     vTool.Set( &tmpHex );
1712     isForward  = vTool.IsForward();
1713     break;
1714   }
1715   default:
1716     const int di = (nbNodes+1) / 3;
1717     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
1718                                 (*columns[di]  )[z-1],
1719                                 (*columns[2*di])[z-1],
1720                                 (*columns[0]   )[z],
1721                                 (*columns[di]  )[z],
1722                                 (*columns[2*di])[z] );
1723     vTool.Set( &tmpVol );
1724     isForward  = vTool.IsForward();
1725   }
1726
1727   // vertical loop on columns
1728
1729   helper->SetElementsOnShape( true );
1730
1731   switch ( nbNodes ) {
1732
1733   case 3: { // ---------- pentahedra
1734     const int i1 = isForward ? 1 : 2;
1735     const int i2 = isForward ? 2 : 1;
1736     for ( z = 1; z < nbZ; ++z )
1737       helper->AddVolume( (*columns[0 ])[z-1], // bottom
1738                          (*columns[i1])[z-1],
1739                          (*columns[i2])[z-1],
1740                          (*columns[0 ])[z],   // top
1741                          (*columns[i1])[z],
1742                          (*columns[i2])[z] );
1743     break;
1744   }
1745   case 4: { // ---------- hexahedra
1746     const int i1 = isForward ? 1 : 3;
1747     const int i3 = isForward ? 3 : 1;
1748     for ( z = 1; z < nbZ; ++z )
1749       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
1750                          (*columns[2])[z-1], (*columns[i3])[z-1],
1751                          (*columns[0])[z],   (*columns[i1])[z],     // top
1752                          (*columns[2])[z],   (*columns[i3])[z] );
1753     break;
1754   }
1755   case 6: { // ---------- octahedra
1756     const int iBase1 = isForward ? -1 : 0;
1757     const int iBase2 = isForward ?  0 :-1;
1758     for ( z = 1; z < nbZ; ++z )
1759       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
1760                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
1761                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
1762                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
1763                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
1764                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
1765     break;
1766   }
1767   default: // ---------- polyhedra
1768     vector<int> quantities( 2 + nbNodes, 4 );
1769     quantities[0] = quantities[1] = nbNodes;
1770     columns.resize( nbNodes + 1 );
1771     columns[ nbNodes ] = columns[ 0 ];
1772     const int i1 = isForward ? 1 : 3;
1773     const int i3 = isForward ? 3 : 1;
1774     const int iBase1 = isForward ? -1 : 0;
1775     const int iBase2 = isForward ?  0 :-1;
1776     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
1777     for ( z = 1; z < nbZ; ++z )
1778     {
1779       for ( int i = 0; i < nbNodes; ++i ) {
1780         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
1781         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
1782         // side
1783         int di = 2*nbNodes + 4*i;
1784         nodes[ di+0 ] = (*columns[i  ])[z  ];
1785         nodes[ di+i1] = (*columns[i+1])[z  ];
1786         nodes[ di+2 ] = (*columns[i+1])[z-1];
1787         nodes[ di+i3] = (*columns[i  ])[z-1];
1788       }
1789       helper->AddPolyhedralVolume( nodes, quantities );
1790     }
1791
1792   } // switch ( nbNodes )
1793 }
1794
1795 //================================================================================
1796 /*!
1797  * \brief Find correspondence between bottom and top nodes
1798  *  If elements on the bottom and top faces are topologically different,
1799  *  and projection is possible and allowed, perform the projection
1800  *  \retval bool - is a success or not
1801  */
1802 //================================================================================
1803
1804 bool StdMeshers_Prism_3D::assocOrProjBottom2Top( const gp_Trsf & bottomToTopTrsf )
1805 {
1806   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1807   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1808
1809   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1810   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1811
1812   if ( !botSMDS || botSMDS->NbElements() == 0 )
1813   {
1814     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape() );
1815     botSMDS = botSM->GetSubMeshDS();
1816     if ( !botSMDS || botSMDS->NbElements() == 0 )
1817       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
1818   }
1819
1820   bool needProject = !topSM->IsMeshComputed();
1821   if ( !needProject && 
1822        (botSMDS->NbElements() != topSMDS->NbElements() ||
1823         botSMDS->NbNodes()    != topSMDS->NbNodes()))
1824   {
1825     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
1826             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
1827     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
1828             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
1829     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1830                        <<" and #"<< topSM->GetId() << " seems different" ));
1831   }
1832
1833   if ( 0/*needProject && !myProjectTriangles*/ )
1834     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1835                        <<" and #"<< topSM->GetId() << " seems different" ));
1836   ///RETURN_BAD_RESULT("Need to project but not allowed");
1837
1838   if ( needProject )
1839   {
1840     return projectBottomToTop( bottomToTopTrsf );
1841   }
1842
1843   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
1844   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
1845   // associate top and bottom faces
1846   TAssocTool::TShapeShapeMap shape2ShapeMap;
1847   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
1848                                              topFace, myBlock.Mesh(),
1849                                              shape2ShapeMap) )
1850     return toSM( error(TCom("Topology of faces #") << botSM->GetId()
1851                        <<" and #"<< topSM->GetId() << " seems different" ));
1852
1853   // Find matching nodes of top and bottom faces
1854   TNodeNodeMap n2nMap;
1855   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
1856                                                topFace, myBlock.Mesh(),
1857                                                shape2ShapeMap, n2nMap ))
1858     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1859                        <<" and #"<< topSM->GetId() << " seems different" ));
1860
1861   // Fill myBotToColumnMap
1862
1863   int zSize = myBlock.VerticalSize();
1864   //TNode prevTNode;
1865   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
1866   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
1867   {
1868     const SMDS_MeshNode* botNode = bN_tN->first;
1869     const SMDS_MeshNode* topNode = bN_tN->second;
1870     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1871       continue; // wall columns are contained in myBlock
1872     // create node column
1873     Prism_3D::TNode bN( botNode );
1874     TNode2ColumnMap::iterator bN_col = 
1875       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1876     TNodeColumn & column = bN_col->second;
1877     column.resize( zSize );
1878     column.front() = botNode;
1879     column.back()  = topNode;
1880   }
1881   return true;
1882 }
1883
1884 //================================================================================
1885 /*!
1886  * \brief Remove quadrangles from the top face and
1887  * create triangles there by projection from the bottom
1888  * \retval bool - a success or not
1889  */
1890 //================================================================================
1891
1892 bool StdMeshers_Prism_3D::projectBottomToTop( const gp_Trsf & bottomToTopTrsf )
1893 {
1894   SMESHDS_Mesh*  meshDS = myBlock.MeshDS();
1895   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1896   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1897
1898   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1899   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1900
1901   if ( topSMDS && topSMDS->NbElements() > 0 )
1902     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1903
1904   const TopoDS_Face& botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE )); // oriented within
1905   const TopoDS_Face& topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE )); //    the 3D SHAPE
1906   int topFaceID = meshDS->ShapeToIndex( topFace );
1907
1908   SMESH_MesherHelper botHelper( *myHelper->GetMesh() );
1909   botHelper.SetSubShape( botFace );
1910   botHelper.ToFixNodeParameters( true );
1911   bool checkUV;
1912   SMESH_MesherHelper topHelper( *myHelper->GetMesh() );
1913   topHelper.SetSubShape( topFace );
1914   topHelper.ToFixNodeParameters( true );
1915   double distXYZ[4], fixTol = 10 * topHelper.MaxTolerance( topFace );
1916
1917   // Fill myBotToColumnMap
1918
1919   int zSize = myBlock.VerticalSize();
1920   Prism_3D::TNode prevTNode;
1921   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
1922   while ( nIt->more() )
1923   {
1924     const SMDS_MeshNode* botNode = nIt->next();
1925     const SMDS_MeshNode* topNode = 0;
1926     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1927       continue; // strange
1928
1929     Prism_3D::TNode bN( botNode );
1930     if ( bottomToTopTrsf.Form() == gp_Identity )
1931     {
1932       // compute bottom node params
1933       gp_XYZ paramHint(-1,-1,-1);
1934       if ( prevTNode.IsNeighbor( bN ))
1935       {
1936         paramHint = prevTNode.GetParams();
1937         // double tol = 1e-2 * ( prevTNode.GetCoords() - bN.GetCoords() ).Modulus();
1938         // myBlock.SetTolerance( Min( myBlock.GetTolerance(), tol ));
1939       }
1940       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
1941                                        ID_BOT_FACE, paramHint ))
1942         return toSM( error(TCom("Can't compute normalized parameters for node ")
1943                            << botNode->GetID() << " on the face #"<< botSM->GetId() ));
1944       prevTNode = bN;
1945       // compute top node coords
1946       gp_XYZ topXYZ; gp_XY topUV;
1947       if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
1948            !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
1949         return toSM( error(TCom("Can't compute coordinates "
1950                                 "by normalized parameters on the face #")<< topSM->GetId() ));
1951       topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
1952       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
1953     }
1954     else // use bottomToTopTrsf
1955     {
1956       gp_XYZ coords = bN.GetCoords();
1957       bottomToTopTrsf.Transforms( coords );
1958       topNode = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1959       gp_XY topUV = botHelper.GetNodeUV( botFace, botNode, 0, &checkUV );
1960       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
1961       distXYZ[0] = -1;
1962       if ( topHelper.CheckNodeUV( topFace, topNode, topUV, fixTol, /*force=*/false, distXYZ ) &&
1963            distXYZ[0] > fixTol && distXYZ[0] < fixTol * 1e+3 )
1964         meshDS->MoveNode( topNode, distXYZ[1], distXYZ[2], distXYZ[3] ); // transform can be inaccurate
1965     }
1966     // create node column
1967     TNode2ColumnMap::iterator bN_col = 
1968       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1969     TNodeColumn & column = bN_col->second;
1970     column.resize( zSize );
1971     column.front() = botNode;
1972     column.back()  = topNode;
1973   }
1974
1975   // Create top faces
1976
1977   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
1978
1979   // care of orientation;
1980   // if the bottom faces is orienetd OK then top faces must be reversed
1981   bool reverseTop = true;
1982   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
1983     reverseTop = ! myHelper->IsReversedSubMesh( botFace );
1984   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
1985
1986   // loop on bottom mesh faces
1987   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
1988   vector< const SMDS_MeshNode* > nodes;
1989   while ( faceIt->more() )
1990   {
1991     const SMDS_MeshElement* face = faceIt->next();
1992     if ( !face || face->GetType() != SMDSAbs_Face )
1993       continue;
1994
1995     // find top node in columns for each bottom node
1996     int nbNodes = face->NbCornerNodes();
1997     nodes.resize( nbNodes );
1998     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
1999     {
2000       const SMDS_MeshNode* n = face->GetNode( *iPtr );
2001       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
2002         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
2003         if ( bot_column == myBotToColumnMap.end() )
2004           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
2005         nodes[ iFrw ] = bot_column->second.back();
2006       }
2007       else {
2008         const TNodeColumn* column = myBlock.GetNodeColumn( n );
2009         if ( !column )
2010           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
2011         nodes[ iFrw ] = column->back();
2012       }
2013     }
2014     SMDS_MeshElement* newFace = 0;
2015     switch ( nbNodes ) {
2016
2017     case 3: {
2018       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
2019       break;
2020       }
2021     case 4: {
2022       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
2023       break;
2024       }
2025     default:
2026       newFace = meshDS->AddPolygonalFace( nodes );
2027     }
2028     if ( newFace )
2029       meshDS->SetMeshElementOnShape( newFace, topFaceID );
2030   }
2031
2032   myHelper->SetElementsOnShape( oldSetElemsOnShape );  
2033
2034   return true;
2035 }
2036
2037 //=======================================================================
2038 //function : project2dMesh
2039 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
2040 //           to a source FACE of another prism (theTgtFace)
2041 //=======================================================================
2042
2043 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
2044                                         const TopoDS_Face& theTgtFace)
2045 {
2046   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
2047   projector2D->myHyp.SetSourceFace( theSrcFace );
2048   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
2049
2050   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
2051   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
2052   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2053
2054   return ok;
2055 }
2056
2057 //================================================================================
2058 /*!
2059  * \brief Set projection coordinates of a node to a face and it's sub-shapes
2060  * \param faceID - the face given by in-block ID
2061  * \param params - node normalized parameters
2062  * \retval bool - is a success
2063  */
2064 //================================================================================
2065
2066 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
2067 {
2068   // find base and top edges of the face
2069   enum { BASE = 0, TOP, LEFT, RIGHT };
2070   vector< int > edgeVec; // 0-base, 1-top
2071   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
2072
2073   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
2074   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
2075
2076   SHOWYXZ("\nparams ", params);
2077   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
2078   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
2079
2080   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
2081   {
2082     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
2083     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
2084
2085     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
2086     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
2087   }
2088   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
2089   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
2090
2091   return true;
2092 }
2093
2094 //=======================================================================
2095 //function : toSM
2096 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
2097 //=======================================================================
2098
2099 bool StdMeshers_Prism_3D::toSM( bool isOK )
2100 {
2101   if ( mySetErrorToSM &&
2102        !isOK &&
2103        myHelper &&
2104        !myHelper->GetSubShape().IsNull() &&
2105        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
2106   {
2107     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
2108     sm->GetComputeError() = this->GetComputeError();
2109     // clear error in order not to return it twice
2110     _error = COMPERR_OK;
2111     _comment.clear();
2112   }
2113   return isOK;
2114 }
2115
2116 //=======================================================================
2117 //function : shapeID
2118 //purpose  : Return index of a shape
2119 //=======================================================================
2120
2121 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
2122 {
2123   if ( S.IsNull() ) return 0;
2124   if ( !myHelper  ) return -3;
2125   return myHelper->GetMeshDS()->ShapeToIndex( S );
2126 }
2127
2128 namespace // utils used by StdMeshers_Prism_3D::IsApplicable()
2129 {
2130   struct EdgeWithNeighbors
2131   {
2132     TopoDS_Edge _edge;
2133     int         _iL, _iR;
2134     EdgeWithNeighbors(const TopoDS_Edge& E, int iE, int nbE, int shift = 0 ):
2135       _edge( E ),
2136       _iL( SMESH_MesherHelper::WrapIndex( iE-1, nbE ) + shift ),
2137       _iR( SMESH_MesherHelper::WrapIndex( iE+1, nbE ) + shift )
2138     {
2139     }
2140     EdgeWithNeighbors() {}
2141   };
2142   struct PrismSide
2143   {
2144     TopoDS_Face                 _face;
2145     TopTools_IndexedMapOfShape *_faces; // pointer because its copy constructor is private
2146     TopoDS_Edge                 _topEdge;
2147     vector< EdgeWithNeighbors >*_edges;
2148     int                         _iBotEdge;
2149     vector< bool >              _isCheckedEdge;
2150     int                         _nbCheckedEdges; // nb of EDGEs whose location is defined
2151     PrismSide                  *_leftSide;
2152     PrismSide                  *_rightSide;
2153     const TopoDS_Edge& Edge( int i ) const
2154     {
2155       return (*_edges)[ i ]._edge;
2156     }
2157     int FindEdge( const TopoDS_Edge& E ) const
2158     {
2159       for ( size_t i = 0; i < _edges->size(); ++i )
2160         if ( E.IsSame( Edge( i ))) return i;
2161       return -1;
2162     }
2163   };
2164   //--------------------------------------------------------------------------------
2165   /*!
2166    * \brief Return ordered edges of a face
2167    */
2168   bool getEdges( const TopoDS_Face&            face,
2169                  vector< EdgeWithNeighbors > & edges,
2170                  const bool                    noHolesAllowed)
2171   {
2172     list< TopoDS_Edge > ee;
2173     list< int >         nbEdgesInWires;
2174     int nbW = SMESH_Block::GetOrderedEdges( face, ee, nbEdgesInWires );
2175     if ( nbW > 1 && noHolesAllowed )
2176       return false;
2177
2178     int iE, nbTot = 0;
2179     list< TopoDS_Edge >::iterator e = ee.begin();
2180     list< int >::iterator       nbE = nbEdgesInWires.begin();
2181     for ( ; nbE != nbEdgesInWires.end(); ++nbE )
2182       for ( iE = 0; iE < *nbE; ++e, ++iE )
2183         if ( SMESH_Algo::isDegenerated( *e ))
2184         {
2185           ee.erase( e );
2186           --(*nbE);
2187           --iE;
2188         }
2189         else
2190         {
2191           e->Orientation( TopAbs_FORWARD ); // for operator==() to work
2192         }
2193
2194     edges.clear();
2195     e = ee.begin();
2196     for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
2197     {
2198       for ( iE = 0; iE < *nbE; ++e, ++iE )
2199         edges.push_back( EdgeWithNeighbors( *e, iE, *nbE, nbTot ));
2200       nbTot += *nbE;
2201     }
2202     return edges.size();
2203   }
2204   //--------------------------------------------------------------------------------
2205   /*!
2206    * \brief Return another faces sharing an edge
2207    */
2208   const TopoDS_Shape & getAnotherFace( const TopoDS_Face& face,
2209                                        const TopoDS_Edge& edge,
2210                                        TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge)
2211   {
2212     TopTools_ListIteratorOfListOfShape faceIt( facesOfEdge.FindFromKey( edge ));
2213     for ( ; faceIt.More(); faceIt.Next() )
2214       if ( !face.IsSame( faceIt.Value() ))
2215         return faceIt.Value();
2216     return face;
2217   }
2218 }
2219
2220 //================================================================================
2221 /*!
2222  * \brief Return true if the algorithm can mesh this shape
2223  *  \param [in] aShape - shape to check
2224  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
2225  *              else, returns OK if at least one shape is OK
2226  */
2227 //================================================================================
2228
2229 bool StdMeshers_Prism_3D::IsApplicable(const TopoDS_Shape & shape, bool toCheckAll)
2230 {
2231   TopExp_Explorer sExp( shape, TopAbs_SOLID );
2232   if ( !sExp.More() )
2233     return false;
2234
2235   for ( ; sExp.More(); sExp.Next() )
2236   {
2237     // check nb shells
2238     TopoDS_Shape shell;
2239     TopExp_Explorer shExp( sExp.Current(), TopAbs_SHELL );
2240     if ( shExp.More() ) {
2241       shell = shExp.Current();
2242       shExp.Next();
2243       if ( shExp.More() )
2244         shell.Nullify();
2245     }
2246     if ( shell.IsNull() ) {
2247       if ( toCheckAll ) return false;
2248       continue;
2249     }
2250     // get all faces
2251     TopTools_IndexedMapOfShape allFaces;
2252     TopExp::MapShapes( shell, TopAbs_FACE, allFaces );
2253     if ( allFaces.Extent() < 3 ) {
2254       if ( toCheckAll ) return false;
2255       continue;
2256     }
2257     // is a box?
2258     if ( allFaces.Extent() == 6 )
2259     {
2260       TopTools_IndexedMapOfOrientedShape map;
2261       bool isBox = SMESH_Block::FindBlockShapes( TopoDS::Shell( shell ),
2262                                                  TopoDS_Vertex(), TopoDS_Vertex(), map );
2263       if ( isBox ) {
2264         if ( !toCheckAll ) return true;
2265         continue;
2266       }
2267     }
2268 #ifdef _DEBUG_
2269     TopTools_IndexedMapOfShape allShapes;
2270     TopExp::MapShapes( shape, allShapes );
2271 #endif
2272
2273     TopTools_IndexedDataMapOfShapeListOfShape facesOfEdge;
2274     TopTools_ListIteratorOfListOfShape faceIt;
2275     TopExp::MapShapesAndAncestors( sExp.Current(), TopAbs_EDGE, TopAbs_FACE , facesOfEdge );
2276     if ( facesOfEdge.IsEmpty() ) {
2277       if ( toCheckAll ) return false;
2278       continue;
2279     }
2280
2281     typedef vector< EdgeWithNeighbors > TEdgeWithNeighborsVec;
2282     vector< TEdgeWithNeighborsVec > faceEdgesVec( allFaces.Extent() + 1 );
2283     TopTools_IndexedMapOfShape* facesOfSide = new TopTools_IndexedMapOfShape[ faceEdgesVec.size() ];
2284     SMESHUtils::ArrayDeleter<TopTools_IndexedMapOfShape> delFacesOfSide( facesOfSide );
2285
2286     // try to use each face as a bottom one
2287     bool prismDetected = false;
2288     for ( int iF = 1; iF < allFaces.Extent() && !prismDetected; ++iF )
2289     {
2290       const TopoDS_Face& botF = TopoDS::Face( allFaces( iF ));
2291
2292       TEdgeWithNeighborsVec& botEdges = faceEdgesVec[ iF ];
2293       if ( botEdges.empty() )
2294       {
2295         if ( !getEdges( botF, botEdges, /*noHoles=*/false ))
2296           break;
2297         if ( allFaces.Extent()-1 <= (int) botEdges.size() )
2298           continue; // all faces are adjacent to botF - no top FACE
2299       }
2300       // init data of side FACEs
2301       vector< PrismSide > sides( botEdges.size() );
2302       for ( int iS = 0; iS < botEdges.size(); ++iS )
2303       {
2304         sides[ iS ]._topEdge = botEdges[ iS ]._edge;
2305         sides[ iS ]._face    = botF;
2306         sides[ iS ]._leftSide  = & sides[ botEdges[ iS ]._iR ];
2307         sides[ iS ]._rightSide = & sides[ botEdges[ iS ]._iL ];
2308         sides[ iS ]._faces = & facesOfSide[ iS ];
2309         sides[ iS ]._faces->Clear();
2310       }
2311
2312       bool isOK = true; // ok for a current botF
2313       bool isAdvanced = true;
2314       int nbFoundSideFaces = 0;
2315       for ( int iLoop = 0; isOK && isAdvanced; ++iLoop )
2316       {
2317         isAdvanced = false;
2318         for ( size_t iS = 0; iS < sides.size() && isOK; ++iS )
2319         {
2320           PrismSide& side = sides[ iS ];
2321           if ( side._face.IsNull() )
2322             continue;
2323           if ( side._topEdge.IsNull() )
2324           {
2325             // find vertical EDGEs --- EGDEs shared with neighbor side FACEs
2326             for ( int is2nd = 0; is2nd < 2 && isOK; ++is2nd ) // 2 adjacent neighbors
2327             {
2328               int di = is2nd ? 1 : -1;
2329               const PrismSide* adjSide = is2nd ? side._rightSide : side._leftSide;
2330               for ( size_t i = 1; i < side._edges->size(); ++i )
2331               {
2332                 int iE = SMESH_MesherHelper::WrapIndex( i*di + side._iBotEdge, side._edges->size());
2333                 if ( side._isCheckedEdge[ iE ] ) continue;
2334                 const TopoDS_Edge&      vertE = side.Edge( iE );
2335                 const TopoDS_Shape& neighborF = getAnotherFace( side._face, vertE, facesOfEdge );
2336                 bool isEdgeShared = adjSide->_faces->Contains( neighborF );
2337                 if ( isEdgeShared )
2338                 {
2339                   isAdvanced = true;
2340                   side._isCheckedEdge[ iE ] = true;
2341                   side._nbCheckedEdges++;
2342                   int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
2343                   if ( nbNotCheckedE == 1 )
2344                     break;
2345                 }
2346                 else
2347                 {
2348                   if ( i == 1 && iLoop == 0 ) isOK = false;
2349                   break;
2350                 }
2351               }
2352             }
2353             // find a top EDGE
2354             int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
2355             if ( nbNotCheckedE == 1 )
2356             {
2357               vector<bool>::iterator ii = std::find( side._isCheckedEdge.begin(),
2358                                                      side._isCheckedEdge.end(), false );
2359               if ( ii != side._isCheckedEdge.end() )
2360               {
2361                 size_t iE = std::distance( side._isCheckedEdge.begin(), ii );
2362                 side._topEdge = side.Edge( iE );
2363               }
2364             }
2365             isOK = ( nbNotCheckedE >= 1 );
2366           }
2367           else //if ( !side._topEdge.IsNull() )
2368           {
2369             // get a next face of a side
2370             const TopoDS_Shape& f = getAnotherFace( side._face, side._topEdge, facesOfEdge );
2371             side._faces->Add( f );
2372             bool stop = false;
2373             if ( f.IsSame( side._face ) || // _topEdge is a seam
2374                  SMESH_MesherHelper::Count( f, TopAbs_WIRE, false ) != 1 )
2375             {
2376               stop = true;
2377             }
2378             else if ( side._leftSide != & side ) // not closed side face
2379             {
2380               if ( side._leftSide->_faces->Contains( f ))
2381               {
2382                 stop = true;
2383                 side._leftSide->_face.Nullify();
2384                 side._leftSide->_topEdge.Nullify();
2385               }
2386               if ( side._rightSide->_faces->Contains( f ))
2387               {
2388                 stop = true;
2389                 side._rightSide->_face.Nullify();
2390                 side._rightSide->_topEdge.Nullify();
2391               }
2392             }
2393             if ( stop )
2394             {
2395               side._face.Nullify();
2396               side._topEdge.Nullify();
2397               continue;
2398             }
2399             side._face = TopoDS::Face( f );
2400             int faceID = allFaces.FindIndex( side._face );
2401             side._edges = & faceEdgesVec[ faceID ];
2402             if ( side._edges->empty() )
2403               if ( !getEdges( side._face, * side._edges, /*noHoles=*/true ))
2404                 break;
2405             const int nbE = side._edges->size();
2406             if ( nbE >= 4 )
2407             {
2408               isAdvanced = true;
2409               ++nbFoundSideFaces;
2410               side._iBotEdge = side.FindEdge( side._topEdge );
2411               side._isCheckedEdge.clear();
2412               side._isCheckedEdge.resize( nbE, false );
2413               side._isCheckedEdge[ side._iBotEdge ] = true;
2414               side._nbCheckedEdges = 1; // bottom EDGE is known
2415             }
2416             side._topEdge.Nullify();
2417             isOK = ( !side._edges->empty() || side._faces->Extent() > 1 );
2418
2419           } //if ( !side._topEdge.IsNull() )
2420
2421         } // loop on prism sides
2422
2423         if ( nbFoundSideFaces > allFaces.Extent() )
2424         {
2425           isOK = false;
2426         }
2427         if ( iLoop > allFaces.Extent() * 10 )
2428         {
2429           isOK = false;
2430 #ifdef _DEBUG_
2431           cerr << "BUG: infinite loop in StdMeshers_Prism_3D::IsApplicable()" << endl;
2432 #endif
2433         }
2434       } // while isAdvanced
2435
2436       if ( isOK && sides[0]._faces->Extent() > 1 )
2437       {
2438         const int nbFaces = sides[0]._faces->Extent();
2439         if ( botEdges.size() == 1 ) // cylinder
2440         {
2441           prismDetected = ( nbFaces == allFaces.Extent()-1 );
2442         }
2443         else
2444         {
2445           const TopoDS_Shape& topFace = sides[0]._faces->FindKey( nbFaces );
2446           size_t iS;
2447           for ( iS = 1; iS < sides.size(); ++iS )
2448             if ( !sides[ iS ]._faces->Contains( topFace ))
2449               break;
2450           prismDetected = ( iS == sides.size() );
2451         }
2452       }
2453     } // loop on allFaces
2454
2455     if ( !prismDetected && toCheckAll ) return false;
2456     if ( prismDetected && !toCheckAll ) return true;
2457
2458   } // loop on solids
2459
2460   return toCheckAll;
2461 }
2462
2463 namespace Prism_3D
2464 {
2465   //================================================================================
2466   /*!
2467    * \brief Return true if this node and other one belong to one face
2468    */
2469   //================================================================================
2470
2471   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
2472   {
2473     if ( !other.myNode || !myNode ) return false;
2474
2475     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
2476     while ( fIt->more() )
2477       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
2478         return true;
2479     return false;
2480   }
2481
2482   //================================================================================
2483   /*!
2484    * \brief Prism initialization
2485    */
2486   //================================================================================
2487
2488   void TPrismTopo::Clear()
2489   {
2490     myShape3D.Nullify();
2491     myTop.Nullify();
2492     myBottom.Nullify();
2493     myWallQuads.clear();
2494     myBottomEdges.clear();
2495     myNbEdgesInWires.clear();
2496     myWallQuads.clear();
2497   }
2498
2499 } // namespace Prism_3D
2500
2501 //================================================================================
2502 /*!
2503  * \brief Constructor. Initialization is needed
2504  */
2505 //================================================================================
2506
2507 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
2508 {
2509   mySide = 0;
2510 }
2511
2512 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
2513 {
2514   Clear();
2515 }
2516 void StdMeshers_PrismAsBlock::Clear()
2517 {
2518   myHelper = 0;
2519   myShapeIDMap.Clear();
2520   myError.reset();
2521
2522   if ( mySide ) {
2523     delete mySide; mySide = 0;
2524   }
2525   myParam2ColumnMaps.clear();
2526   myShapeIndex2ColumnMap.clear();
2527 }
2528
2529 //=======================================================================
2530 //function : initPrism
2531 //purpose  : Analyse shape geometry and mesh.
2532 //           If there are triangles on one of faces, it becomes 'bottom'.
2533 //           thePrism.myBottom can be already set up.
2534 //=======================================================================
2535
2536 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
2537                                     const TopoDS_Shape&   shape3D)
2538 {
2539   myHelper->SetSubShape( shape3D );
2540
2541   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
2542   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
2543
2544   // detect not-quad FACE sub-meshes of the 3D SHAPE
2545   list< SMESH_subMesh* > notQuadGeomSubMesh;
2546   list< SMESH_subMesh* > notQuadElemSubMesh;
2547   int nbFaces = 0;
2548   //
2549   SMESH_subMesh* anyFaceSM = 0;
2550   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
2551   while ( smIt->more() )
2552   {
2553     SMESH_subMesh* sm = smIt->next();
2554     const TopoDS_Shape& face = sm->GetSubShape();
2555     if      ( face.ShapeType() > TopAbs_FACE ) break;
2556     else if ( face.ShapeType() < TopAbs_FACE ) continue;
2557     nbFaces++;
2558     anyFaceSM = sm;
2559
2560     // is quadrangle FACE?
2561     list< TopoDS_Edge > orderedEdges;
2562     list< int >         nbEdgesInWires;
2563     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
2564                                                 nbEdgesInWires );
2565     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
2566       notQuadGeomSubMesh.push_back( sm );
2567
2568     // look for not quadrangle mesh elements
2569     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2570       if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
2571         notQuadElemSubMesh.push_back( sm );
2572   }
2573
2574   int nbNotQuadMeshed = notQuadElemSubMesh.size();
2575   int       nbNotQuad = notQuadGeomSubMesh.size();
2576   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
2577
2578   // detect bad cases
2579   if ( nbNotQuadMeshed > 2 )
2580   {
2581     return toSM( error(COMPERR_BAD_INPUT_MESH,
2582                        TCom("More than 2 faces with not quadrangle elements: ")
2583                        <<nbNotQuadMeshed));
2584   }
2585   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
2586   {
2587     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
2588     // Remove from notQuadGeomSubMesh faces meshed with regular grid
2589     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
2590                                          TQuadrangleAlgo::instance(this,myHelper) );
2591     nbNotQuad -= nbQuasiQuads;
2592     if ( nbNotQuad > 2 )
2593       return toSM( error(COMPERR_BAD_SHAPE,
2594                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
2595     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
2596   }
2597
2598   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
2599   // If there are not quadrangle FACEs, they are top and bottom ones.
2600   // Not quadrangle FACEs must be only on top and bottom.
2601
2602   SMESH_subMesh * botSM = 0;
2603   SMESH_subMesh * topSM = 0;
2604
2605   if ( hasNotQuad ) // can chose a bottom FACE
2606   {
2607     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
2608     else                       botSM = notQuadGeomSubMesh.front();
2609     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
2610     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
2611
2612     if ( topSM == botSM ) {
2613       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
2614       else                       topSM = notQuadGeomSubMesh.front();
2615     }
2616
2617     // detect mesh triangles on wall FACEs
2618     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
2619       bool ok = false;
2620       if ( nbNotQuadMeshed == 1 )
2621         ok = ( find( notQuadGeomSubMesh.begin(),
2622                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
2623       else
2624         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
2625       if ( !ok )
2626         return toSM( error(COMPERR_BAD_INPUT_MESH,
2627                            "Side face meshed with not quadrangle elements"));
2628     }
2629   }
2630
2631   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
2632
2633   // use thePrism.myBottom
2634   if ( !thePrism.myBottom.IsNull() )
2635   {
2636     if ( botSM ) {
2637       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
2638         std::swap( botSM, topSM );
2639         if ( !botSM || ! botSM->GetSubShape().IsSame( thePrism.myBottom ))
2640           return toSM( error( COMPERR_BAD_INPUT_MESH,
2641                               "Incompatible non-structured sub-meshes"));
2642       }
2643     }
2644     else {
2645       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2646     }
2647   }
2648   else if ( !botSM ) // find a proper bottom
2649   {
2650     // composite walls or not prism shape
2651     for ( TopExp_Explorer f( shape3D, TopAbs_FACE ); f.More(); f.Next() )
2652     {
2653       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
2654       if ( nbFaces >= minNbFaces)
2655       {
2656         thePrism.Clear();
2657         thePrism.myBottom = TopoDS::Face( f.Current() );
2658         if ( initPrism( thePrism, shape3D ))
2659           return true;
2660       }
2661       return toSM( error( COMPERR_BAD_SHAPE ));
2662     }
2663   }
2664
2665   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
2666   TopoDS_Vertex V000;
2667   double minVal = DBL_MAX, minX, val;
2668   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
2669         exp.More(); exp.Next() )
2670   {
2671     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
2672     gp_Pnt P = BRep_Tool::Pnt( v );
2673     val = P.X() + P.Y() + P.Z();
2674     if ( val < minVal || ( val == minVal && P.X() < minX )) {
2675       V000 = v;
2676       minVal = val;
2677       minX = P.X();
2678     }
2679   }
2680
2681   thePrism.myShape3D = shape3D;
2682   if ( thePrism.myBottom.IsNull() )
2683     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
2684   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( shape3D,
2685                                                            thePrism.myBottom ));
2686   // Get ordered bottom edges
2687   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
2688     TopoDS::Face( thePrism.myBottom.Reversed() );
2689   SMESH_Block::GetOrderedEdges( reverseBottom,
2690                                 thePrism.myBottomEdges,
2691                                 thePrism.myNbEdgesInWires, V000 );
2692
2693   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
2694   if ( !getWallFaces( thePrism, nbFaces ))
2695     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
2696
2697   if ( topSM )
2698   {
2699     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
2700       return toSM( error
2701                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2702                     "Non-quadrilateral faces are not opposite"));
2703
2704     // check that the found top and bottom FACEs are opposite
2705     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
2706     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
2707       if ( myHelper->IsSubShape( *edge, thePrism.myTop ))
2708         return toSM( error
2709                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2710                       "Non-quadrilateral faces are not opposite"));
2711   }
2712
2713   return true;
2714 }
2715
2716 //================================================================================
2717 /*!
2718  * \brief Initialization.
2719  * \param helper - helper loaded with mesh and 3D shape
2720  * \param thePrism - a prism data
2721  * \retval bool - false if a mesh or a shape are KO
2722  */
2723 //================================================================================
2724
2725 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
2726                                    const Prism_3D::TPrismTopo& thePrism)
2727 {
2728   myHelper = helper;
2729   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2730   SMESH_Mesh*     mesh = myHelper->GetMesh();
2731
2732   if ( mySide ) {
2733     delete mySide; mySide = 0;
2734   }
2735   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
2736   vector< pair< double, double> > params( NB_WALL_FACES );
2737   mySide = new TSideFace( *mesh, sideFaces, params );
2738
2739
2740   SMESH_Block::init();
2741   myShapeIDMap.Clear();
2742   myShapeIndex2ColumnMap.clear();
2743   
2744   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
2745     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
2746     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
2747   };
2748
2749   myError = SMESH_ComputeError::New();
2750
2751   myNotQuadOnTop = thePrism.myNotQuadOnTop;
2752
2753   // Find columns of wall nodes and calculate edges' lengths
2754   // --------------------------------------------------------
2755
2756   myParam2ColumnMaps.clear();
2757   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
2758
2759   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
2760   vector< double > edgeLength( nbEdges );
2761   multimap< double, int > len2edgeMap;
2762
2763   // for each EDGE: either split into several parts, or join with several next EDGEs
2764   vector<int> nbSplitPerEdge( nbEdges, 0 );
2765   vector<int> nbUnitePerEdge( nbEdges, 0 ); // -1 means "joined to a previous"
2766
2767   // consider continuous straight EDGEs as one side
2768   const int nbSides = countNbSides( thePrism, nbUnitePerEdge, edgeLength );
2769
2770   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
2771   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
2772   {
2773     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2774
2775     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2776     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2777     {
2778       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
2779       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2780         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2781                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2782     }
2783     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2784     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2785     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2786
2787     if ( nbSides < NB_WALL_FACES ) // fill map used to split faces
2788       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE )); // sort edges by length
2789   }
2790   // Load columns of internal edges (forming holes)
2791   // and fill map ShapeIndex to TParam2ColumnMap for them
2792   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
2793   {
2794     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2795
2796     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2797     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2798     {
2799       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
2800       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2801         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2802                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2803     }
2804     // edge columns
2805     int id = MeshDS()->ShapeToIndex( *edgeIt );
2806     bool isForward = true; // meaningless for intenal wires
2807     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2808     // columns for vertices
2809     // 1
2810     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
2811     id = n0->getshapeId();
2812     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2813     // 2
2814     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
2815     id = n1->getshapeId();
2816     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2817
2818     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2819     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2820     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2821   }
2822
2823   // Create 4 wall faces of a block
2824   // -------------------------------
2825
2826   if ( nbSides <= NB_WALL_FACES ) // ************* Split faces if necessary
2827   {
2828     if ( nbSides != NB_WALL_FACES ) // define how to split
2829     {
2830       if ( len2edgeMap.size() != nbEdges )
2831         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
2832
2833       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
2834       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
2835
2836       double maxLen = maxLen_i->first;
2837       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
2838       switch ( nbEdges ) {
2839       case 1: // 0-th edge is split into 4 parts
2840         nbSplitPerEdge[ 0 ] = 4;
2841         break;
2842       case 2: // either the longest edge is split into 3 parts, or both edges into halves
2843         if ( maxLen / 3 > midLen / 2 ) {
2844           nbSplitPerEdge[ maxLen_i->second ] = 3;
2845         }
2846         else {
2847           nbSplitPerEdge[ maxLen_i->second ] = 2;
2848           nbSplitPerEdge[ midLen_i->second ] = 2;
2849         }
2850         break;
2851       case 3:
2852         if ( nbSides == 2 )
2853           // split longest into 3 parts
2854           nbSplitPerEdge[ maxLen_i->second ] = 3;
2855         else
2856           // split longest into halves
2857           nbSplitPerEdge[ maxLen_i->second ] = 2;
2858       }
2859     }
2860   }
2861   else // **************************** Unite faces
2862   {
2863     int nbExraFaces = nbSides - 4; // nb of faces to fuse
2864     for ( iE = 0; iE < nbEdges; ++iE )
2865     {
2866       if ( nbUnitePerEdge[ iE ] < 0 )
2867         continue;
2868       // look for already united faces
2869       for ( int i = iE; i < iE + nbExraFaces; ++i )
2870       {
2871         if ( nbUnitePerEdge[ i ] > 0 ) // a side including nbUnitePerEdge[i]+1 edge
2872           nbExraFaces += nbUnitePerEdge[ i ];
2873         nbUnitePerEdge[ i ] = -1;
2874       }
2875       nbUnitePerEdge[ iE ] = nbExraFaces;
2876       break;
2877     }
2878   }
2879
2880   // Create TSideFace's
2881   int iSide = 0;
2882   list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2883   for ( iE = 0; iE < nbEdges; ++iE, ++botE )
2884   {
2885     TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
2886     const int       nbSplit = nbSplitPerEdge[ iE ];
2887     const int   nbExraFaces = nbUnitePerEdge[ iE ] + 1;
2888     if ( nbSplit > 0 ) // split
2889     {
2890       vector< double > params;
2891       splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
2892       const bool isForward =
2893         StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
2894                                                 myParam2ColumnMaps[iE],
2895                                                 *botE, SMESH_Block::ID_Fx0z );
2896       for ( int i = 0; i < nbSplit; ++i ) {
2897         double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
2898         double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
2899         TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
2900                                          thePrism.myWallQuads[ iE ], *botE,
2901                                          &myParam2ColumnMaps[ iE ], f, l );
2902         mySide->SetComponent( iSide++, comp );
2903       }
2904     }
2905     else if ( nbExraFaces > 1 ) // unite
2906     {
2907       double u0 = 0, sumLen = 0;
2908       for ( int i = iE; i < iE + nbExraFaces; ++i )
2909         sumLen += edgeLength[ i ];
2910
2911       vector< TSideFace* >        components( nbExraFaces );
2912       vector< pair< double, double> > params( nbExraFaces );
2913       bool endReached = false;
2914       for ( int i = 0; i < nbExraFaces; ++i, ++botE, ++iE )
2915       {
2916         if ( iE == nbEdges )
2917         {
2918           endReached = true;
2919           botE = thePrism.myBottomEdges.begin();
2920           iE = 0;
2921         }
2922         components[ i ] = new TSideFace( *mesh, wallFaceIds[ iSide ],
2923                                          thePrism.myWallQuads[ iE ], *botE,
2924                                          &myParam2ColumnMaps[ iE ]);
2925         double u1 = u0 + edgeLength[ iE ] / sumLen;
2926         params[ i ] = make_pair( u0 , u1 );
2927         u0 = u1;
2928       }
2929       TSideFace* comp = new TSideFace( *mesh, components, params );
2930       mySide->SetComponent( iSide++, comp );
2931       if ( endReached )
2932         break;
2933       --iE; // for increment in an external loop on iE
2934       --botE;
2935     }
2936     else if ( nbExraFaces < 0 ) // skip already united face
2937     {
2938     }
2939     else // use as is
2940     {
2941       TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
2942                                        thePrism.myWallQuads[ iE ], *botE,
2943                                        &myParam2ColumnMaps[ iE ]);
2944       mySide->SetComponent( iSide++, comp );
2945     }
2946   }
2947
2948
2949   // Fill geometry fields of SMESH_Block
2950   // ------------------------------------
2951
2952   vector< int > botEdgeIdVec;
2953   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
2954
2955   bool isForward[NB_WALL_FACES] = { true, true, true, true };
2956   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
2957   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
2958
2959   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
2960   {
2961     TSideFace * sideFace = mySide->GetComponent( iF );
2962     if ( !sideFace )
2963       RETURN_BAD_RESULT("NULL TSideFace");
2964     int fID = sideFace->FaceID(); // in-block ID
2965
2966     // fill myShapeIDMap
2967     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
2968          !sideFace->IsComplex())
2969       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
2970
2971     // side faces geometry
2972     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
2973     if ( !sideFace->GetPCurves( pcurves ))
2974       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
2975
2976     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
2977     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
2978
2979     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
2980     // edges 3D geometry
2981     vector< int > edgeIdVec;
2982     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
2983     for ( int isMax = 0; isMax < 2; ++isMax ) {
2984       {
2985         int eID = edgeIdVec[ isMax ];
2986         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
2987         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
2988         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
2989         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
2990       }
2991       {
2992         int eID = edgeIdVec[ isMax+2 ];
2993         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
2994         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
2995         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
2996         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
2997
2998         // corner points
2999         vector< int > vertexIdVec;
3000         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
3001         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
3002         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
3003       }
3004     }
3005     // pcurves on horizontal faces
3006     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
3007       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
3008         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
3009         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
3010         break;
3011       }
3012     }
3013     //sideFace->dumpNodes( 4 ); // debug
3014   }
3015   // horizontal faces geometry
3016   {
3017     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
3018     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
3019     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
3020   }
3021   {
3022     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
3023     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
3024     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
3025   }
3026   //faceGridToPythonDump( SMESH_Block::ID_Fxy0, 50 );
3027   //faceGridToPythonDump( SMESH_Block::ID_Fxy1 );
3028
3029   // Fill map ShapeIndex to TParam2ColumnMap
3030   // ----------------------------------------
3031
3032   list< TSideFace* > fList;
3033   list< TSideFace* >::iterator fListIt;
3034   fList.push_back( mySide );
3035   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
3036   {
3037     int nb = (*fListIt)->NbComponents();
3038     for ( int i = 0; i < nb; ++i ) {
3039       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
3040         fList.push_back( comp );
3041     }
3042     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
3043       // columns for a base edge
3044       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
3045       bool isForward = (*fListIt)->IsForward();
3046       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3047
3048       // columns for vertices
3049       const SMDS_MeshNode* n0 = cols->begin()->second.front();
3050       id = n0->getshapeId();
3051       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3052
3053       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
3054       id = n1->getshapeId();
3055       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
3056     }
3057   }
3058
3059 // #define SHOWYXZ(msg, xyz) {                     \
3060 //     gp_Pnt p (xyz);                                                     \
3061 //     cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; \
3062 //   }
3063 //   double _u[]={ 0.1, 0.1, 0.9, 0.9 };
3064 //   double _v[]={ 0.1, 0.9, 0.1, 0.9 };
3065 //   for ( int z = 0; z < 2; ++z )
3066 //     for ( int i = 0; i < 4; ++i )
3067 //     {
3068 //       //gp_XYZ testPar(0.25, 0.25, 0), testCoord;
3069 //       int iFace = (z ? ID_TOP_FACE : ID_BOT_FACE);
3070 //       gp_XYZ testPar(_u[i], _v[i], z), testCoord;
3071 //       if ( !FacePoint( iFace, testPar, testCoord ))
3072 //         RETURN_BAD_RESULT("TEST FacePoint() FAILED");
3073 //       SHOWYXZ("IN TEST PARAM" , testPar);
3074 //       SHOWYXZ("OUT TEST CORD" , testCoord);
3075 //       if ( !ComputeParameters( testCoord, testPar , iFace))
3076 //         RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
3077 //       SHOWYXZ("OUT TEST PARAM" , testPar);
3078 //     }
3079   return true;
3080 }
3081
3082 //================================================================================
3083 /*!
3084  * \brief Return pointer to column of nodes
3085  * \param node - bottom node from which the returned column goes up
3086  * \retval const TNodeColumn* - the found column
3087  */
3088 //================================================================================
3089
3090 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
3091 {
3092   int sID = node->getshapeId();
3093
3094   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
3095     myShapeIndex2ColumnMap.find( sID );
3096   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
3097     const TParam2ColumnMap* cols = col_frw->second.first;
3098     TParam2ColumnIt u_col = cols->begin();
3099     for ( ; u_col != cols->end(); ++u_col )
3100       if ( u_col->second[ 0 ] == node )
3101         return & u_col->second;
3102   }
3103   return 0;
3104 }
3105
3106 //=======================================================================
3107 //function : GetLayersTransformation
3108 //purpose  : Return transformations to get coordinates of nodes of each layer
3109 //           by nodes of the bottom. Layer is a set of nodes at a certain step
3110 //           from bottom to top.
3111 //           Transformation to get top node from bottom ones is computed
3112 //           only if the top FACE is not meshed.
3113 //=======================================================================
3114
3115 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
3116                                                       const Prism_3D::TPrismTopo& prism) const
3117 {
3118   const bool itTopMeshed = !SubMesh( ID_BOT_FACE )->IsEmpty();
3119   const int zSize = VerticalSize();
3120   if ( zSize < 3 && !itTopMeshed ) return true;
3121   trsf.resize( zSize - 1 );
3122
3123   // Select some node columns by which we will define coordinate system of layers
3124
3125   vector< const TNodeColumn* > columns;
3126   {
3127     bool isReverse;
3128     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
3129     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
3130     {
3131       if ( SMESH_Algo::isDegenerated( *edgeIt )) continue;
3132       const TParam2ColumnMap* u2colMap =
3133         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
3134       if ( !u2colMap ) return false;
3135       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
3136       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
3137       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
3138       const int nbCol = 5;
3139       for ( int i = 0; i < nbCol; ++i )
3140       {
3141         double u = f + i/double(nbCol) * ( l - f );
3142         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
3143         if ( columns.empty() || col != columns.back() )
3144           columns.push_back( col );
3145       }
3146     }
3147   }
3148
3149   // Find tolerance to check transformations
3150
3151   double tol2;
3152   {
3153     Bnd_B3d bndBox;
3154     for ( int i = 0; i < columns.size(); ++i )
3155       bndBox.Add( gpXYZ( columns[i]->front() ));
3156     tol2 = bndBox.SquareExtent() * 1e-5;
3157   }
3158
3159   // Compute transformations
3160
3161   int xCol = -1;
3162   gp_Trsf fromCsZ, toCs0;
3163   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
3164   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
3165   toCs0.SetTransformation( cs0 );
3166   for ( int z = 1; z < zSize; ++z )
3167   {
3168     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
3169     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
3170     fromCsZ.SetTransformation( csZ );
3171     fromCsZ.Invert();
3172     gp_Trsf& t = trsf[ z-1 ];
3173     t = fromCsZ * toCs0;
3174     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
3175
3176     // check a transformation
3177     for ( int i = 0; i < columns.size(); ++i )
3178     {
3179       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
3180       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
3181       t.Transforms( p0.ChangeCoord() );
3182       if ( p0.SquareDistance( pz ) > tol2 )
3183       {
3184         t = gp_Trsf();
3185         return ( z == zSize - 1 ); // OK if fails only botton->top trsf
3186       }
3187     }
3188   }
3189   return true;
3190 }
3191
3192 //================================================================================
3193 /*!
3194  * \brief Check curve orientation of a bootom edge
3195   * \param meshDS - mesh DS
3196   * \param columnsMap - node columns map of side face
3197   * \param bottomEdge - the bootom edge
3198   * \param sideFaceID - side face in-block ID
3199   * \retval bool - true if orientation coinside with in-block forward orientation
3200  */
3201 //================================================================================
3202
3203 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
3204                                             const TParam2ColumnMap& columnsMap,
3205                                             const TopoDS_Edge &     bottomEdge,
3206                                             const int               sideFaceID)
3207 {
3208   bool isForward = false;
3209   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
3210   {
3211     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
3212   }
3213   else
3214   {
3215     const TNodeColumn&     firstCol = columnsMap.begin()->second;
3216     const SMDS_MeshNode* bottomNode = firstCol[0];
3217     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
3218     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
3219   }
3220   // on 2 of 4 sides first vertex is end
3221   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
3222     isForward = !isForward;
3223   return isForward;
3224 }
3225
3226 //=======================================================================
3227 //function : faceGridToPythonDump
3228 //purpose  : Prints a script creating a normal grid on the prism side
3229 //=======================================================================
3230
3231 void StdMeshers_PrismAsBlock::faceGridToPythonDump(const SMESH_Block::TShapeID face,
3232                                                    const int                   nb)
3233 {
3234 #ifdef _DEBUG_
3235   gp_XYZ pOnF[6] = { gp_XYZ(0,0,0), gp_XYZ(0,0,1),
3236                      gp_XYZ(0,0,0), gp_XYZ(0,1,0),
3237                      gp_XYZ(0,0,0), gp_XYZ(1,0,0) };
3238   gp_XYZ p2;
3239   cout << "mesh = smesh.Mesh( 'Face " << face << "')" << endl;
3240   SMESH_Block::TFace& f = myFace[ face - ID_FirstF ];
3241   gp_XYZ params = pOnF[ face - ID_FirstF ];
3242   //const int nb = 10; // nb face rows
3243   for ( int j = 0; j <= nb; ++j )
3244   {
3245     params.SetCoord( f.GetVInd(), double( j )/ nb );
3246     for ( int i = 0; i <= nb; ++i )
3247     {
3248       params.SetCoord( f.GetUInd(), double( i )/ nb );
3249       gp_XYZ p = f.Point( params );
3250       gp_XY uv = f.GetUV( params );
3251       cout << "mesh.AddNode( " << p.X() << ", " << p.Y() << ", " << p.Z() << " )"
3252            << " # " << 1 + i + j * ( nb + 1 )
3253            << " ( " << i << ", " << j << " ) "
3254            << " UV( " << uv.X() << ", " << uv.Y() << " )" << endl;
3255       ShellPoint( params, p2 );
3256       double dist = ( p2 - p ).Modulus();
3257       if ( dist > 1e-4 )
3258         cout << "#### dist from ShellPoint " << dist
3259              << " (" << p2.X() << ", " << p2.Y() << ", " << p2.Z() << " ) " << endl;
3260     }
3261   }
3262   for ( int j = 0; j < nb; ++j )
3263     for ( int i = 0; i < nb; ++i )
3264     {
3265       int n = 1 + i + j * ( nb + 1 );
3266       cout << "mesh.AddFace([ "
3267            << n << ", " << n+1 << ", "
3268            << n+nb+2 << ", " << n+nb+1 << "]) " << endl;
3269     }
3270   
3271 #endif
3272 }
3273
3274 //================================================================================
3275 /*!
3276  * \brief Constructor
3277   * \param faceID - in-block ID
3278   * \param face - geom FACE
3279   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
3280   * \param columnsMap - map of node columns
3281   * \param first - first normalized param
3282   * \param last - last normalized param
3283  */
3284 //================================================================================
3285
3286 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_Mesh&                mesh,
3287                                               const int                  faceID,
3288                                               const Prism_3D::TQuadList& quadList,
3289                                               const TopoDS_Edge&         baseEdge,
3290                                               TParam2ColumnMap*          columnsMap,
3291                                               const double               first,
3292                                               const double               last):
3293   myID( faceID ),
3294   myParamToColumnMap( columnsMap ),
3295   myHelper( mesh )
3296 {
3297   myParams.resize( 1 );
3298   myParams[ 0 ] = make_pair( first, last );
3299   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
3300   myBaseEdge    = baseEdge;
3301   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper.GetMeshDS(),
3302                                                           *myParamToColumnMap,
3303                                                           myBaseEdge, myID );
3304   myHelper.SetSubShape( quadList.front()->face );
3305
3306   if ( quadList.size() > 1 ) // side is vertically composite
3307   {
3308     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
3309
3310     SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
3311
3312     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
3313     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
3314     for ( ; quad != quadList.end(); ++quad )
3315     {
3316       const TopoDS_Face& face = (*quad)->face;
3317       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
3318       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
3319       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
3320                                         PSurface( new BRepAdaptor_Surface( face ))));
3321     }
3322     for ( int i = 1; i <= subToFaces.Extent(); ++i )
3323     {
3324       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
3325       TopTools_ListOfShape& faces = subToFaces( i );
3326       int subID  = meshDS->ShapeToIndex( sub );
3327       int faceID = meshDS->ShapeToIndex( faces.First() );
3328       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
3329     }
3330   }
3331 }
3332
3333 //================================================================================
3334 /*!
3335  * \brief Constructor of a complex side face
3336  */
3337 //================================================================================
3338
3339 StdMeshers_PrismAsBlock::TSideFace::
3340 TSideFace(SMESH_Mesh&                             mesh,
3341           const vector< TSideFace* >&             components,
3342           const vector< pair< double, double> > & params)
3343   :myID( components[0] ? components[0]->myID : 0 ),
3344    myParamToColumnMap( 0 ),
3345    myParams( params ),
3346    myIsForward( true ),
3347    myComponents( components ),
3348    myHelper( mesh )
3349 {
3350   if ( myID == ID_Fx1z || myID == ID_F0yz )
3351   {
3352     // reverse components
3353     std::reverse( myComponents.begin(), myComponents.end() );
3354     std::reverse( myParams.begin(),     myParams.end() );
3355     for ( size_t i = 0; i < myParams.size(); ++i )
3356     {
3357       const double f = myParams[i].first;
3358       const double l = myParams[i].second;
3359       myParams[i] = make_pair( 1. - l, 1. - f );
3360     }
3361   }
3362 }
3363 //================================================================================
3364 /*!
3365  * \brief Copy constructor
3366   * \param other - other side
3367  */
3368 //================================================================================
3369
3370 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other ):
3371   myID               ( other.myID ),
3372   myParamToColumnMap ( other.myParamToColumnMap ),
3373   mySurface          ( other.mySurface ),
3374   myBaseEdge         ( other.myBaseEdge ),
3375   myShapeID2Surf     ( other.myShapeID2Surf ),
3376   myParams           ( other.myParams ),
3377   myIsForward        ( other.myIsForward ),
3378   myComponents       ( other.myComponents.size() ),
3379   myHelper           ( *other.myHelper.GetMesh() )
3380 {
3381   for (int i = 0 ; i < myComponents.size(); ++i )
3382     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
3383 }
3384
3385 //================================================================================
3386 /*!
3387  * \brief Deletes myComponents
3388  */
3389 //================================================================================
3390
3391 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
3392 {
3393   for (int i = 0 ; i < myComponents.size(); ++i )
3394     if ( myComponents[ i ] )
3395       delete myComponents[ i ];
3396 }
3397
3398 //================================================================================
3399 /*!
3400  * \brief Return geometry of the vertical curve
3401   * \param isMax - true means curve located closer to (1,1,1) block point
3402   * \retval Adaptor3d_Curve* - curve adaptor
3403  */
3404 //================================================================================
3405
3406 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
3407 {
3408   if ( !myComponents.empty() ) {
3409     if ( isMax )
3410       return myComponents.back()->VertiCurve(isMax);
3411     else
3412       return myComponents.front()->VertiCurve(isMax);
3413   }
3414   double f = myParams[0].first, l = myParams[0].second;
3415   if ( !myIsForward ) std::swap( f, l );
3416   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
3417 }
3418
3419 //================================================================================
3420 /*!
3421  * \brief Return geometry of the top or bottom curve
3422   * \param isTop - 
3423   * \retval Adaptor3d_Curve* - 
3424  */
3425 //================================================================================
3426
3427 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
3428 {
3429   return new THorizontalEdgeAdaptor( this, isTop );
3430 }
3431
3432 //================================================================================
3433 /*!
3434  * \brief Return pcurves
3435   * \param pcurv - array of 4 pcurves
3436   * \retval bool - is a success
3437  */
3438 //================================================================================
3439
3440 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
3441 {
3442   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
3443
3444   for ( int i = 0 ; i < 4 ; ++i ) {
3445     Handle(Geom2d_Line) line;
3446     switch ( iEdge[ i ] ) {
3447     case TOP_EDGE:
3448       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
3449     case BOTTOM_EDGE:
3450       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
3451     case V0_EDGE:
3452       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
3453     case V1_EDGE:
3454       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
3455     }
3456     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
3457   }
3458   return true;
3459 }
3460
3461 //================================================================================
3462 /*!
3463  * \brief Returns geometry of pcurve on a horizontal face
3464   * \param isTop - is top or bottom face
3465   * \param horFace - a horizontal face
3466   * \retval Adaptor2d_Curve2d* - curve adaptor
3467  */
3468 //================================================================================
3469
3470 Adaptor2d_Curve2d*
3471 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
3472                                                 const TopoDS_Face& horFace) const
3473 {
3474   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
3475 }
3476
3477 //================================================================================
3478 /*!
3479  * \brief Return a component corresponding to parameter
3480   * \param U - parameter along a horizontal size
3481   * \param localU - parameter along a horizontal size of a component
3482   * \retval TSideFace* - found component
3483  */
3484 //================================================================================
3485
3486 StdMeshers_PrismAsBlock::TSideFace*
3487 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
3488 {
3489   localU = U;
3490   if ( myComponents.empty() )
3491     return const_cast<TSideFace*>( this );
3492
3493   int i;
3494   for ( i = 0; i < myComponents.size(); ++i )
3495     if ( U < myParams[ i ].second )
3496       break;
3497   if ( i >= myComponents.size() )
3498     i = myComponents.size() - 1;
3499
3500   double f = myParams[ i ].first, l = myParams[ i ].second;
3501   localU = ( U - f ) / ( l - f );
3502   return myComponents[ i ];
3503 }
3504
3505 //================================================================================
3506 /*!
3507  * \brief Find node columns for a parameter
3508   * \param U - parameter along a horizontal edge
3509   * \param col1 - the 1st found column
3510   * \param col2 - the 2nd found column
3511   * \retval r - normalized position of U between the found columns
3512  */
3513 //================================================================================
3514
3515 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
3516                                                       TParam2ColumnIt & col1,
3517                                                       TParam2ColumnIt & col2) const
3518 {
3519   double u = U, r = 0;
3520   if ( !myComponents.empty() ) {
3521     TSideFace * comp = GetComponent(U,u);
3522     return comp->GetColumns( u, col1, col2 );
3523   }
3524
3525   if ( !myIsForward )
3526     u = 1 - u;
3527   double f = myParams[0].first, l = myParams[0].second;
3528   u = f + u * ( l - f );
3529
3530   col1 = col2 = getColumn( myParamToColumnMap, u );
3531   if ( ++col2 == myParamToColumnMap->end() ) {
3532     --col2;
3533     r = 0.5;
3534   }
3535   else {
3536     double uf = col1->first;
3537     double ul = col2->first;
3538     r = ( u - uf ) / ( ul - uf );
3539   }
3540   return r;
3541 }
3542
3543 //================================================================================
3544 /*!
3545  * \brief Return all nodes at a given height together with their normalized parameters
3546  *  \param [in] Z - the height of interest
3547  *  \param [out] nodes - map of parameter to node
3548  */
3549 //================================================================================
3550
3551 void StdMeshers_PrismAsBlock::
3552 TSideFace::GetNodesAtZ(const int Z,
3553                        map<double, const SMDS_MeshNode* >& nodes ) const
3554 {
3555   if ( !myComponents.empty() )
3556   {
3557     double u0 = 0.;
3558     for ( size_t i = 0; i < myComponents.size(); ++i )
3559     {
3560       map<double, const SMDS_MeshNode* > nn;
3561       myComponents[i]->GetNodesAtZ( Z, nn );
3562       map<double, const SMDS_MeshNode* >::iterator u2n = nn.begin();
3563       if ( !nodes.empty() && nodes.rbegin()->second == u2n->second )
3564         ++u2n;
3565       const double uRange = myParams[i].second - myParams[i].first;
3566       for ( ; u2n != nn.end(); ++u2n )
3567         nodes.insert( nodes.end(), make_pair( u0 + uRange * u2n->first, u2n->second ));
3568       u0 += uRange;
3569     }
3570   }
3571   else
3572   {
3573     double f = myParams[0].first, l = myParams[0].second;
3574     if ( !myIsForward )
3575       std::swap( f, l );
3576     const double uRange = l - f;
3577     if ( Abs( uRange ) < std::numeric_limits<double>::min() )
3578       return;
3579     TParam2ColumnIt u2col = getColumn( myParamToColumnMap, myParams[0].first + 1e-3 );
3580     for ( ; u2col != myParamToColumnMap->end(); ++u2col )
3581       if ( u2col->first > myParams[0].second + 1e-9 )
3582         break;
3583       else
3584         nodes.insert( nodes.end(),
3585                       make_pair( ( u2col->first - f ) / uRange, u2col->second[ Z ] ));
3586   }
3587 }
3588
3589 //================================================================================
3590 /*!
3591  * \brief Return coordinates by normalized params
3592   * \param U - horizontal param
3593   * \param V - vertical param
3594   * \retval gp_Pnt - result point
3595  */
3596 //================================================================================
3597
3598 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
3599                                                  const Standard_Real V) const
3600 {
3601   if ( !myComponents.empty() ) {
3602     double u;
3603     TSideFace * comp = GetComponent(U,u);
3604     return comp->Value( u, V );
3605   }
3606
3607   TParam2ColumnIt u_col1, u_col2;
3608   double vR, hR = GetColumns( U, u_col1, u_col2 );
3609
3610   const SMDS_MeshNode* nn[4];
3611
3612   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
3613   // Workaround for a wrongly located point returned by mySurface.Value() for
3614   // UV located near boundary of BSpline surface.
3615   // To bypass the problem, we take point from 3D curve of EDGE.
3616   // It solves pb of the bloc_fiss_new.py
3617   const double tol = 1e-3;
3618   if ( V < tol || V+tol >= 1. )
3619   {
3620     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
3621     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
3622     TopoDS_Edge edge;
3623     if ( V < tol )
3624     {
3625       edge = myBaseEdge;
3626     }
3627     else
3628     {
3629       TopoDS_Shape s = myHelper.GetSubShapeByNode( nn[0], myHelper.GetMeshDS() );
3630       if ( s.ShapeType() != TopAbs_EDGE )
3631         s = myHelper.GetSubShapeByNode( nn[2], myHelper.GetMeshDS() );
3632       if ( s.ShapeType() == TopAbs_EDGE )
3633         edge = TopoDS::Edge( s );
3634     }
3635     if ( !edge.IsNull() )
3636     {
3637       double u1 = myHelper.GetNodeU( edge, nn[0] );
3638       double u3 = myHelper.GetNodeU( edge, nn[2] );
3639       double u = u1 * ( 1 - hR ) + u3 * hR;
3640       TopLoc_Location loc; double f,l;
3641       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
3642       return curve->Value( u ).Transformed( loc );
3643     }
3644   }
3645   // END issue 0020680: Bad cell created by Radial prism in center of torus
3646
3647   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
3648   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
3649
3650   if ( !myShapeID2Surf.empty() ) // side is vertically composite
3651   {
3652     // find a FACE on which the 4 nodes lie
3653     TSideFace* me = (TSideFace*) this;
3654     int notFaceID1 = 0, notFaceID2 = 0;
3655     for ( int i = 0; i < 4; ++i )
3656       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
3657       {
3658         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
3659         notFaceID2 = 0;
3660         break;
3661       }
3662       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
3663       {
3664         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
3665         notFaceID1 = nn[i]->getshapeId();
3666       }
3667       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
3668       {
3669         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
3670           notFaceID2 = nn[i]->getshapeId();
3671       }
3672     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
3673     {
3674       SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
3675       TopoDS_Shape face = myHelper.GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
3676                                                        meshDS->IndexToShape( notFaceID2 ),
3677                                                        *myHelper.GetMesh(),
3678                                                        TopAbs_FACE );
3679       if ( face.IsNull() ) 
3680         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
3681       int faceID = meshDS->ShapeToIndex( face );
3682       me->mySurface = me->myShapeID2Surf[ faceID ];
3683       if ( !mySurface )
3684         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
3685     }
3686   }
3687   ((TSideFace*) this)->myHelper.SetSubShape( mySurface->Face() );
3688
3689   gp_XY uv1 = myHelper.GetNodeUV( mySurface->Face(), nn[0], nn[2]);
3690   gp_XY uv2 = myHelper.GetNodeUV( mySurface->Face(), nn[1], nn[3]);
3691   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
3692
3693   gp_XY uv3 = myHelper.GetNodeUV( mySurface->Face(), nn[2], nn[0]);
3694   gp_XY uv4 = myHelper.GetNodeUV( mySurface->Face(), nn[3], nn[1]);
3695   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
3696
3697   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
3698
3699   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
3700   return p;
3701 }
3702
3703
3704 //================================================================================
3705 /*!
3706  * \brief Return boundary edge
3707   * \param edge - edge index
3708   * \retval TopoDS_Edge - found edge
3709  */
3710 //================================================================================
3711
3712 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
3713 {
3714   if ( !myComponents.empty() ) {
3715     switch ( iEdge ) {
3716     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
3717     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
3718     default: return TopoDS_Edge();
3719     }
3720   }
3721   TopoDS_Shape edge;
3722   const SMDS_MeshNode* node = 0;
3723   SMESHDS_Mesh * meshDS = myHelper.GetMesh()->GetMeshDS();
3724   TNodeColumn* column;
3725
3726   switch ( iEdge ) {
3727   case TOP_EDGE:
3728   case BOTTOM_EDGE:
3729     column = & (( ++myParamToColumnMap->begin())->second );
3730     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
3731     edge = myHelper.GetSubShapeByNode ( node, meshDS );
3732     if ( edge.ShapeType() == TopAbs_VERTEX ) {
3733       column = & ( myParamToColumnMap->begin()->second );
3734       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
3735     }
3736     break;
3737   case V0_EDGE:
3738   case V1_EDGE: {
3739     bool back = ( iEdge == V1_EDGE );
3740     if ( !myIsForward ) back = !back;
3741     if ( back )
3742       column = & ( myParamToColumnMap->rbegin()->second );
3743     else
3744       column = & ( myParamToColumnMap->begin()->second );
3745     if ( column->size() > 0 )
3746       edge = myHelper.GetSubShapeByNode( (*column)[ 1 ], meshDS );
3747     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
3748       node = column->front();
3749     break;
3750   }
3751   default:;
3752   }
3753   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
3754     return TopoDS::Edge( edge );
3755
3756   // find edge by 2 vertices
3757   TopoDS_Shape V1 = edge;
3758   TopoDS_Shape V2 = myHelper.GetSubShapeByNode( node, meshDS );
3759   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
3760   {
3761     TopoDS_Shape ancestor = myHelper.GetCommonAncestor( V1, V2, *myHelper.GetMesh(), TopAbs_EDGE);
3762     if ( !ancestor.IsNull() )
3763       return TopoDS::Edge( ancestor );
3764   }
3765   return TopoDS_Edge();
3766 }
3767
3768 //================================================================================
3769 /*!
3770  * \brief Fill block sub-shapes
3771   * \param shapeMap - map to fill in
3772   * \retval int - nb inserted sub-shapes
3773  */
3774 //================================================================================
3775
3776 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
3777 {
3778   int nbInserted = 0;
3779
3780   // Insert edges
3781   vector< int > edgeIdVec;
3782   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
3783
3784   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
3785     TopoDS_Edge e = GetEdge( i );
3786     if ( !e.IsNull() ) {
3787       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
3788     }
3789   }
3790
3791   // Insert corner vertices
3792
3793   TParam2ColumnIt col1, col2 ;
3794   vector< int > vertIdVec;
3795
3796   // from V0 column
3797   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
3798   GetColumns(0, col1, col2 );
3799   const SMDS_MeshNode* node0 = col1->second.front();
3800   const SMDS_MeshNode* node1 = col1->second.back();
3801   TopoDS_Shape v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
3802   TopoDS_Shape v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
3803   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3804     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3805   }
3806   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3807     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3808   }
3809   
3810   // from V1 column
3811   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
3812   GetColumns(1, col1, col2 );
3813   node0 = col2->second.front();
3814   node1 = col2->second.back();
3815   v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
3816   v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
3817   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3818     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3819   }
3820   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3821     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3822   }
3823
3824 //   TopoDS_Vertex V0, V1, Vcom;
3825 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
3826 //   if ( !myIsForward ) std::swap( V0, V1 );
3827
3828 //   // bottom vertex IDs
3829 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
3830 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
3831 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
3832
3833 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
3834 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
3835 //     return false;
3836
3837 //   // insert one side edge
3838 //   int edgeID;
3839 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
3840 //   else                    edgeID = edgeIdVec[ _v1 ];
3841 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3842
3843 //   // top vertex of the side edge
3844 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
3845 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
3846 //   if ( Vcom.IsSame( Vtop ))
3847 //     Vtop = TopExp::LastVertex( sideEdge );
3848 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
3849
3850 //   // other side edge
3851 //   sideEdge = GetEdge( V1_EDGE );
3852 //   if ( sideEdge.IsNull() )
3853 //     return false;
3854 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
3855 //   else                            edgeID = edgeIdVec[ _v1 ];
3856 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3857   
3858 //   // top edge
3859 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
3860 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
3861
3862 //   // top vertex of the other side edge
3863 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
3864 //     return false;
3865 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
3866 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
3867
3868   return nbInserted;
3869 }
3870
3871 //================================================================================
3872 /*!
3873  * \brief Dump ids of nodes of sides
3874  */
3875 //================================================================================
3876
3877 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
3878 {
3879 #ifdef _DEBUG_
3880   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
3881   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
3882   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
3883   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
3884   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
3885   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
3886   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
3887   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
3888   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
3889   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
3890 #endif
3891 }
3892
3893 //================================================================================
3894 /*!
3895  * \brief Creates TVerticalEdgeAdaptor 
3896   * \param columnsMap - node column map
3897   * \param parameter - normalized parameter
3898  */
3899 //================================================================================
3900
3901 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
3902 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
3903 {
3904   myNodeColumn = & getColumn( columnsMap, parameter )->second;
3905 }
3906
3907 //================================================================================
3908 /*!
3909  * \brief Return coordinates for the given normalized parameter
3910   * \param U - normalized parameter
3911   * \retval gp_Pnt - coordinates
3912  */
3913 //================================================================================
3914
3915 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
3916 {
3917   const SMDS_MeshNode* n1;
3918   const SMDS_MeshNode* n2;
3919   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
3920   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
3921 }
3922
3923 //================================================================================
3924 /*!
3925  * \brief Dump ids of nodes
3926  */
3927 //================================================================================
3928
3929 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
3930 {
3931 #ifdef _DEBUG_
3932   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
3933     cout << (*myNodeColumn)[i]->GetID() << " ";
3934   if ( nbNodes < myNodeColumn->size() )
3935     cout << myNodeColumn->back()->GetID();
3936 #endif
3937 }
3938
3939 //================================================================================
3940 /*!
3941  * \brief Return coordinates for the given normalized parameter
3942   * \param U - normalized parameter
3943   * \retval gp_Pnt - coordinates
3944  */
3945 //================================================================================
3946
3947 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
3948 {
3949   return mySide->TSideFace::Value( U, myV );
3950 }
3951
3952 //================================================================================
3953 /*!
3954  * \brief Dump ids of <nbNodes> first nodes and the last one
3955  */
3956 //================================================================================
3957
3958 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
3959 {
3960 #ifdef _DEBUG_
3961   // Not bedugged code. Last node is sometimes incorrect
3962   const TSideFace* side = mySide;
3963   double u = 0;
3964   if ( mySide->IsComplex() )
3965     side = mySide->GetComponent(0,u);
3966
3967   TParam2ColumnIt col, col2;
3968   TParam2ColumnMap* u2cols = side->GetColumns();
3969   side->GetColumns( u , col, col2 );
3970   
3971   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
3972
3973   const SMDS_MeshNode* n = 0;
3974   const SMDS_MeshNode* lastN
3975     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
3976   for ( j = 0; j < nbNodes && n != lastN; ++j )
3977   {
3978     n = col->second[ i ];
3979     cout << n->GetID() << " ";
3980     if ( side->IsForward() )
3981       ++col;
3982     else
3983       --col;
3984   }
3985
3986   // last node
3987   u = 1;
3988   if ( mySide->IsComplex() )
3989     side = mySide->GetComponent(1,u);
3990
3991   side->GetColumns( u , col, col2 );
3992   if ( n != col->second[ i ] )
3993     cout << col->second[ i ]->GetID();
3994 #endif
3995 }
3996
3997 //================================================================================
3998 /*!
3999  * \brief Costructor of TPCurveOnHorFaceAdaptor fills its map of
4000  * normalized parameter to node UV on a horizontal face
4001  *  \param [in] sideFace - lateral prism side
4002  *  \param [in] isTop - is \a horFace top or bottom of the prism
4003  *  \param [in] horFace - top or bottom face of the prism
4004  */
4005 //================================================================================
4006
4007 StdMeshers_PrismAsBlock::
4008 TPCurveOnHorFaceAdaptor::TPCurveOnHorFaceAdaptor( const TSideFace*   sideFace,
4009                                                   const bool         isTop,
4010                                                   const TopoDS_Face& horFace)
4011 {
4012   if ( sideFace && !horFace.IsNull() )
4013   {
4014     //cout << "\n\t FACE " << sideFace->FaceID() << endl;
4015     const int Z = isTop ? sideFace->ColumnHeight() - 1 : 0;
4016     map<double, const SMDS_MeshNode* > u2nodes;
4017     sideFace->GetNodesAtZ( Z, u2nodes );
4018     if ( u2nodes.empty() )
4019       return;
4020
4021     SMESH_MesherHelper helper( *sideFace->GetMesh() );
4022     helper.SetSubShape( horFace );
4023
4024     bool okUV;
4025     gp_XY uv;
4026     double f,l;
4027     Handle(Geom2d_Curve) C2d;
4028     int edgeID = -1;
4029     const double tol = 10 * helper.MaxTolerance( horFace );
4030     const SMDS_MeshNode* prevNode = u2nodes.rbegin()->second;
4031
4032     map<double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4033     for ( ; u2n != u2nodes.end(); ++u2n )
4034     {
4035       const SMDS_MeshNode* n = u2n->second;
4036       okUV = false;
4037       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
4038       {
4039         if ( n->getshapeId() != edgeID )
4040         {
4041           C2d.Nullify();
4042           edgeID = n->getshapeId();
4043           TopoDS_Shape S = helper.GetSubShapeByNode( n, helper.GetMeshDS() );
4044           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
4045           {
4046             C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), horFace, f,l );
4047           }
4048         }
4049         if ( !C2d.IsNull() )
4050         {
4051           double u = static_cast< const SMDS_EdgePosition* >( n->GetPosition() )->GetUParameter();
4052           if ( f <= u && u <= l )
4053           {
4054             uv = C2d->Value( u ).XY();
4055             okUV = helper.CheckNodeUV( horFace, n, uv, tol );
4056           }
4057         }
4058       }
4059       if ( !okUV )
4060         uv = helper.GetNodeUV( horFace, n, prevNode, &okUV );
4061
4062       myUVmap.insert( myUVmap.end(), make_pair( u2n->first, uv ));
4063       // cout << n->getshapeId() << " N " << n->GetID()
4064       //      << " \t" << uv.X() << ", " << uv.Y() << " \t" << u2n->first << endl;
4065
4066       prevNode = n;
4067     }
4068   }
4069 }
4070
4071 //================================================================================
4072 /*!
4073  * \brief Return UV on pcurve for the given normalized parameter
4074   * \param U - normalized parameter
4075   * \retval gp_Pnt - coordinates
4076  */
4077 //================================================================================
4078
4079 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
4080 {
4081   map< double, gp_XY >::const_iterator i1 = myUVmap.upper_bound( U );
4082
4083   if ( i1 == myUVmap.end() )
4084     return myUVmap.empty() ? gp_XY(0,0) : myUVmap.rbegin()->second;
4085
4086   if ( i1 == myUVmap.begin() )
4087     return (*i1).second;
4088
4089   map< double, gp_XY >::const_iterator i2 = i1--;
4090
4091   double r = ( U - i1->first ) / ( i2->first - i1->first );
4092   return i1->second * ( 1 - r ) + i2->second * r;
4093 }