Salome HOME
0022103: EDF 2550 SMESH : Allow viscous layer with 3D extrusion
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
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 using namespace std;
64
65 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
66 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
67 #define SHOWYXZ(msg, xyz) // {\
68 // gp_Pnt p (xyz); \
69 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
70 // }
71 #ifdef _DEBUG_
72 #define DBGOUT(msg) //cout << msg << endl;
73 #else
74 #define DBGOUT(msg)
75 #endif
76
77 namespace TAssocTool = StdMeshers_ProjectionUtils;
78
79 typedef SMESH_Comment TCom;
80
81 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
82        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
83        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
84        NB_WALL_FACES = 4 }; //
85
86 namespace {
87
88   //=======================================================================
89   /*!
90    * \brief Quadrangle algorithm
91    */
92   struct TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
93   {
94     TQuadrangleAlgo(int studyId, SMESH_Gen* gen)
95       : StdMeshers_Quadrangle_2D( gen->GetANewId(), studyId, gen)
96     {
97     }
98     static StdMeshers_Quadrangle_2D* instance( SMESH_Algo*         fatherAlgo,
99                                                SMESH_MesherHelper* helper=0)
100     {
101       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetStudyId(),
102                                                           fatherAlgo->GetGen() );
103       if ( helper &&
104            algo->myProxyMesh &&
105            algo->myProxyMesh->GetMesh() != helper->GetMesh() )
106         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *helper->GetMesh() ));
107
108       algo->myQuadStruct.reset();
109
110       if ( helper )
111         algo->_quadraticMesh = helper->GetIsQuadratic();
112
113       return algo;
114     }
115   };
116   //=======================================================================
117   /*!
118    * \brief Algorithm projecting 1D mesh
119    */
120   struct TProjction1dAlgo : public StdMeshers_Projection_1D
121   {
122     StdMeshers_ProjectionSource1D myHyp;
123
124     TProjction1dAlgo(int studyId, SMESH_Gen* gen)
125       : StdMeshers_Projection_1D( gen->GetANewId(), studyId, gen),
126         myHyp( gen->GetANewId(), studyId, gen)
127     {
128       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
129     }
130     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
131     {
132       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetStudyId(),
133                                                             fatherAlgo->GetGen() );
134       return algo;
135     }
136   };
137   //=======================================================================
138   /*!
139    * \brief Algorithm projecting 2D mesh
140    */
141   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
142   {
143     StdMeshers_ProjectionSource2D myHyp;
144
145     TProjction2dAlgo(int studyId, SMESH_Gen* gen)
146       : StdMeshers_Projection_1D2D( gen->GetANewId(), studyId, gen),
147         myHyp( gen->GetANewId(), studyId, gen)
148     {
149       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
150     }
151     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
152     {
153       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetStudyId(),
154                                                             fatherAlgo->GetGen() );
155       return algo;
156     }
157   };
158
159   //================================================================================
160   /*!
161    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
162    *        Return false if the BOTTOM_SIDE is composite
163    */
164   //================================================================================
165
166   bool setBottomEdge( const TopoDS_Edge&   botE,
167                       faceQuadStruct::Ptr& quad,
168                       const TopoDS_Shape&  face)
169   {
170     quad->side[ QUAD_TOP_SIDE  ]->Reverse();
171     quad->side[ QUAD_LEFT_SIDE ]->Reverse();
172     int edgeIndex = 0;
173     for ( size_t i = 0; i < quad->side.size(); ++i )
174     {
175       StdMeshers_FaceSide* quadSide = quad->side[i];
176       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
177         if ( botE.IsSame( quadSide->Edge( iE )))
178         {
179           if ( quadSide->NbEdges() > 1 )
180             return false;
181           edgeIndex = i;
182           i = quad->side.size(); // to quit from the outer loop
183           break;
184         }
185     }
186     if ( edgeIndex != QUAD_BOTTOM_SIDE )
187       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
188
189     quad->face = TopoDS::Face( face );
190
191     return true;
192   }
193
194   //================================================================================
195   /*!
196    * \brief Return iterator pointing to node column for the given parameter
197    * \param columnsMap - node column map
198    * \param parameter - parameter
199    * \retval TParam2ColumnMap::iterator - result
200    *
201    * it returns closest left column
202    */
203   //================================================================================
204
205   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
206                              const double            parameter )
207   {
208     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
209     if ( u_col != columnsMap->begin() )
210       --u_col;
211     return u_col; // return left column
212   }
213
214   //================================================================================
215   /*!
216    * \brief Return nodes around given parameter and a ratio
217    * \param column - node column
218    * \param param - parameter
219    * \param node1 - lower node
220    * \param node2 - upper node
221    * \retval double - ratio
222    */
223   //================================================================================
224
225   double getRAndNodes( const TNodeColumn*     column,
226                        const double           param,
227                        const SMDS_MeshNode* & node1,
228                        const SMDS_MeshNode* & node2)
229   {
230     if ( param >= 1.0 || column->size() == 1) {
231       node1 = node2 = column->back();
232       return 0;
233     }
234
235     int i = int( param * ( column->size() - 1 ));
236     double u0 = double( i )/ double( column->size() - 1 );
237     double r = ( param - u0 ) * ( column->size() - 1 );
238
239     node1 = (*column)[ i ];
240     node2 = (*column)[ i + 1];
241     return r;
242   }
243
244   //================================================================================
245   /*!
246    * \brief Compute boundary parameters of face parts
247     * \param nbParts - nb of parts to split columns into
248     * \param columnsMap - node columns of the face to split
249     * \param params - computed parameters
250    */
251   //================================================================================
252
253   void splitParams( const int               nbParts,
254                     const TParam2ColumnMap* columnsMap,
255                     vector< double > &      params)
256   {
257     params.clear();
258     params.reserve( nbParts + 1 );
259     TParam2ColumnIt last_par_col = --columnsMap->end();
260     double par = columnsMap->begin()->first; // 0.
261     double parLast = last_par_col->first;
262     params.push_back( par );
263     for ( int i = 0; i < nbParts - 1; ++ i )
264     {
265       double partSize = ( parLast - par ) / double ( nbParts - i );
266       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
267       if ( par_col->first == par ) {
268         ++par_col;
269         if ( par_col == last_par_col ) {
270           while ( i < nbParts - 1 )
271             params.push_back( par + partSize * i++ );
272           break;
273         }
274       }
275       par = par_col->first;
276       params.push_back( par );
277     }
278     params.push_back( parLast ); // 1.
279   }
280
281   //================================================================================
282   /*!
283    * \brief Return coordinate system for z-th layer of nodes
284    */
285   //================================================================================
286
287   gp_Ax2 getLayerCoordSys(const int                           z,
288                           const vector< const TNodeColumn* >& columns,
289                           int&                                xColumn)
290   {
291     // gravity center of a layer
292     gp_XYZ O(0,0,0);
293     int vertexCol = -1;
294     for ( int i = 0; i < columns.size(); ++i )
295     {
296       O += gpXYZ( (*columns[ i ])[ z ]);
297       if ( vertexCol < 0 &&
298            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
299         vertexCol = i;
300     }
301     O /= columns.size();
302
303     // Z axis
304     gp_Vec Z(0,0,0);
305     int iPrev = columns.size()-1;
306     for ( int i = 0; i < columns.size(); ++i )
307     {
308       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
309       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
310       Z += v1 ^ v2;
311       iPrev = i;
312     }
313
314     if ( vertexCol >= 0 )
315     {
316       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
317     }
318     if ( xColumn < 0 || xColumn >= columns.size() )
319     {
320       // select a column for X dir
321       double maxDist = 0;
322       for ( int i = 0; i < columns.size(); ++i )
323       {
324         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
325         if ( dist > maxDist )
326         {
327           xColumn = i;
328           maxDist = dist;
329         }
330       }
331     }
332
333     // X axis
334     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
335
336     return gp_Ax2( O, Z, X);
337   }
338
339   //================================================================================
340   /*!
341    * \brief Removes submeshes that are or can be meshed with regular grid from given list
342    *  \retval int - nb of removed submeshes
343    */
344   //================================================================================
345
346   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
347                        SMESH_MesherHelper*       helper,
348                        StdMeshers_Quadrangle_2D* quadAlgo)
349   {
350     int nbRemoved = 0;
351     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
352     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
353     while ( smIt != notQuadSubMesh.end() )
354     {
355       SMESH_subMesh* faceSm = *smIt;
356       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
357       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
358       bool toRemove;
359       if ( nbQuads > 0 )
360         toRemove = helper->IsStructured( faceSm );
361       else
362         toRemove = quadAlgo->CheckNbEdges( *helper->GetMesh(),
363                                            faceSm->GetSubShape() );
364       nbRemoved += toRemove;
365       if ( toRemove )
366         smIt = notQuadSubMesh.erase( smIt );
367       else
368         ++smIt;
369     }
370
371     return nbRemoved;
372   }
373
374 } // namespace
375
376 //=======================================================================
377 //function : StdMeshers_Prism_3D
378 //purpose  : 
379 //=======================================================================
380
381 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
382   :SMESH_3D_Algo(hypId, studyId, gen)
383 {
384   _name                    = "Prism_3D";
385   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
386   _onlyUnaryInput          = false; // accept all SOLIDs at once
387   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
388   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
389   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
390   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
391
392   //myProjectTriangles       = false;
393   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
394 }
395
396 //================================================================================
397 /*!
398  * \brief Destructor
399  */
400 //================================================================================
401
402 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
403 {}
404
405 //=======================================================================
406 //function : CheckHypothesis
407 //purpose  : 
408 //=======================================================================
409
410 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
411                                           const TopoDS_Shape&                  aShape,
412                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
413 {
414   // Check shape geometry
415 /*  PAL16229
416   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
417
418   // find not quadrangle faces
419   list< TopoDS_Shape > notQuadFaces;
420   int nbEdge, nbWire, nbFace = 0;
421   TopExp_Explorer exp( aShape, TopAbs_FACE );
422   for ( ; exp.More(); exp.Next() ) {
423     ++nbFace;
424     const TopoDS_Shape& face = exp.Current();
425     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
426     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
427     if (  nbEdge!= 4 || nbWire!= 1 ) {
428       if ( !notQuadFaces.empty() ) {
429         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
430              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
431           RETURN_BAD_RESULT("Different not quad faces");
432       }
433       notQuadFaces.push_back( face );
434     }
435   }
436   if ( !notQuadFaces.empty() )
437   {
438     if ( notQuadFaces.size() != 2 )
439       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
440
441     // check total nb faces
442     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
443     if ( nbFace != nbEdge + 2 )
444       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
445   }
446 */
447   // no hypothesis
448   aStatus = SMESH_Hypothesis::HYP_OK;
449   return true;
450 }
451
452 //=======================================================================
453 //function : Compute
454 //purpose  : Compute mesh on a COMPOUND of SOLIDs
455 //=======================================================================
456
457 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
458 {
459   SMESH_MesherHelper helper( theMesh );
460   myHelper = &helper;
461
462   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
463   if ( nbSolids < 1 )
464     return true;
465
466   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
467   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
468
469   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
470   list< TopoDS_Face > meshedFaces, notQuadMeshedFaces, notQuadFaces;
471   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
472   //StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this );
473   for ( int iF = 1; iF <= faceToSolids.Extent(); ++iF )
474   {
475     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
476     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
477     if ( !faceSM->IsEmpty() )
478     {
479       if ( !meshHasQuads ||
480            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
481            !helper.IsStructured( faceSM )
482            )
483         notQuadMeshedFaces.push_front( face );
484       else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
485         meshedFaces.push_front( face );
486       else
487         meshedFaces.push_back( face );
488     }
489     // not add not quadrilateral FACE as we can't compute it
490     // else if ( !quadAlgo->CheckNbEdges( theMesh, face ))
491     // // not add not quadrilateral FACE as it can be a prism side
492     // // else if ( myHelper->Count( face, TopAbs_EDGE, /*ignoreSame=*/false ) != 4 )
493     // {
494     //   notQuadFaces.push_back( face );
495     // }
496   }
497   // notQuadFaces are of medium priority, put them before ordinary meshed faces
498   meshedFaces.splice( meshedFaces.begin(), notQuadFaces );
499   // notQuadMeshedFaces are of highest priority, put them before notQuadFaces
500   meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
501
502   Prism_3D::TPrismTopo prism;
503
504   if ( nbSolids == 1 )
505   {
506     if ( !meshedFaces.empty() )
507       prism.myBottom = meshedFaces.front();
508     return ( initPrism( prism, TopExp_Explorer( theShape, TopAbs_SOLID ).Current() ) &&
509              compute( prism ));
510   }
511
512   TopTools_MapOfShape meshedSolids;
513   list< Prism_3D::TPrismTopo > meshedPrism;
514   TopTools_ListIteratorOfListOfShape solidIt;
515
516   while ( meshedSolids.Extent() < nbSolids )
517   {
518     if ( _computeCanceled )
519       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
520
521     // compute prisms having avident computed source FACE
522     while ( !meshedFaces.empty() )
523     {
524       TopoDS_Face face = meshedFaces.front();
525       meshedFaces.pop_front();
526       TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( face );
527       while ( !solidList.IsEmpty() )
528       {
529         TopoDS_Shape solid = solidList.First();
530         solidList.RemoveFirst();
531         if ( meshedSolids.Add( solid ))
532         {
533           prism.Clear();
534           prism.myBottom = face;
535           if ( !initPrism( prism, solid ) ||
536                !compute( prism ))
537             return false;
538
539           meshedFaces.push_front( prism.myTop );
540           meshedPrism.push_back( prism );
541         }
542       }
543     }
544     if ( meshedSolids.Extent() == nbSolids )
545       break;
546
547     // below in the loop we try to find source FACEs somehow
548
549     // project mesh from source FACEs of computed prisms to
550     // prisms sharing wall FACEs
551     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
552     for ( ; prismIt != meshedPrism.end(); ++prismIt )
553     {
554       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
555       {
556         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
557         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
558         {
559           const TopoDS_Face& wFace = (*wQuad)->face;
560           TopTools_ListOfShape& solidList = faceToSolids.ChangeFromKey( wFace );
561           solidIt.Initialize( solidList );
562           while ( solidIt.More() )
563           {
564             const TopoDS_Shape& solid = solidIt.Value();
565             if ( meshedSolids.Contains( solid )) {
566               solidList.Remove( solidIt );
567               continue; // already computed prism
568             }
569             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
570             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ]->Edge(0);
571             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
572                                                                TopAbs_FACE);
573             while ( const TopoDS_Shape* f = faceIt->next() )
574             {
575               const TopoDS_Face& candidateF = TopoDS::Face( *f );
576               prism.Clear();
577               prism.myBottom  = candidateF;
578               mySetErrorToSM = false;
579               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
580                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
581                    initPrism( prism, solid ) &&
582                    project2dMesh( prismIt->myBottom, candidateF))
583               {
584                 mySetErrorToSM = true;
585                 if ( !compute( prism ))
586                   return false;
587                 meshedFaces.push_front( prism.myTop );
588                 meshedFaces.push_front( prism.myBottom );
589                 meshedPrism.push_back( prism );
590                 meshedSolids.Add( solid );
591               }
592               InitComputeError();
593             }
594             mySetErrorToSM = true;
595             InitComputeError();
596             if ( meshedSolids.Contains( solid ))
597               solidList.Remove( solidIt );
598             else
599               solidIt.Next();
600           }
601         }
602       }
603       if ( !meshedFaces.empty() )
604         break; // to compute prisms with avident sources
605     }
606
607     // find FACEs with local 1D hyps, which has to be computed by now,
608     // or at least any computed FACEs
609     for ( int iF = 1; ( meshedFaces.empty() && iF < faceToSolids.Extent() ); ++iF )
610     {
611       const TopoDS_Face&               face = TopoDS::Face( faceToSolids.FindKey( iF ));
612       const TopTools_ListOfShape& solidList = faceToSolids.FindFromKey( face );
613       if ( solidList.IsEmpty() ) continue;
614       SMESH_subMesh*                 faceSM = theMesh.GetSubMesh( face );
615       if ( !faceSM->IsEmpty() )
616       {
617         meshedFaces.push_back( face ); // lower priority
618       }
619       else
620       {
621         bool allSubMeComputed = true;
622         SMESH_subMeshIteratorPtr smIt = faceSM->getDependsOnIterator(false,true);
623         while ( smIt->more() && allSubMeComputed )
624           allSubMeComputed = smIt->next()->IsMeshComputed();
625         if ( allSubMeComputed )
626         {
627           faceSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
628           if ( !faceSM->IsEmpty() )
629             meshedFaces.push_front( face ); // higher priority
630           else
631             faceSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
632         }
633       }
634     }
635
636
637     // TODO. there are other ways to find out the source FACE:
638     // propagation, topological similarity, ect.
639
640     // simply try to mesh all not meshed SOLIDs
641     if ( meshedFaces.empty() )
642     {
643       for ( TopExp_Explorer solid( theShape, TopAbs_SOLID ); solid.More(); solid.Next() )
644       {
645         mySetErrorToSM = false;
646         prism.Clear();
647         if ( !meshedSolids.Contains( solid.Current() ) &&
648              initPrism( prism, solid.Current() ))
649         {
650           mySetErrorToSM = true;
651           if ( !compute( prism ))
652             return false;
653           meshedFaces.push_front( prism.myTop );
654           meshedFaces.push_front( prism.myBottom );
655           meshedPrism.push_back( prism );
656           meshedSolids.Add( solid.Current() );
657         }
658         mySetErrorToSM = true;
659       }
660     }
661
662     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
663     {
664       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
665         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
666
667       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
668       TopExp_Explorer solid( theShape, TopAbs_SOLID );
669       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
670         if ( !meshedSolids.Contains( solid.Current() ))
671         {
672           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
673           sm->GetComputeError() = err;
674         }
675       return error( err );
676     }
677   }
678   return true;
679 }
680
681 //================================================================================
682 /*!
683  * \brief Find wall faces by bottom edges
684  */
685 //================================================================================
686
687 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
688                                         const int              totalNbFaces)
689 {
690   thePrism.myWallQuads.clear();
691
692   SMESH_Mesh* mesh = myHelper->GetMesh();
693
694   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
695
696   TopTools_MapOfShape faceMap;
697   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;   
698   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
699                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
700
701   // ------------------------------
702   // Get the 1st row of wall FACEs
703   // ------------------------------
704
705   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
706   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
707   int iE = 0;
708   while ( edge != thePrism.myBottomEdges.end() )
709   {
710     ++iE;
711     if ( BRep_Tool::Degenerated( *edge ))
712     {
713       edge = thePrism.myBottomEdges.erase( edge );
714       --iE;
715       --(*nbE);
716     }
717     else
718     {
719       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
720       for ( ; faceIt.More(); faceIt.Next() )
721       {
722         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
723         if ( !thePrism.myBottom.IsSame( face ))
724         {
725           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
726           if ( !quadList.back() )
727             return toSM( error(TCom("Side face #") << shapeID( face )
728                                << " not meshable with quadrangles"));
729           if ( ! setBottomEdge( *edge, quadList.back(), face ))
730             return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
731           thePrism.myWallQuads.push_back( quadList );
732           faceMap.Add( face );
733           break;
734         }
735       }
736       ++edge;
737     }
738     if ( iE == *nbE )
739     {
740       iE = 0;
741       ++nbE;
742     }
743   }
744
745   // -------------------------
746   // Find the rest wall FACEs
747   // -------------------------
748
749   // Compose a vector of indixes of right neighbour FACE for each wall FACE
750   // that is not so evident in case of several WIREs in the bottom FACE
751   thePrism.myRightQuadIndex.clear();
752   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
753     thePrism.myRightQuadIndex.push_back( i+1 );
754   list< int >::iterator nbEinW = thePrism.myNbEdgesInWires.begin();
755   for ( int iLeft = 0; nbEinW != thePrism.myNbEdgesInWires.end(); ++nbEinW )
756   {
757     thePrism.myRightQuadIndex[ iLeft + *nbEinW - 1 ] = iLeft; // 1st EDGE index of a current WIRE
758     iLeft += *nbEinW;
759   }
760
761   while ( totalNbFaces - faceMap.Extent() > 2 )
762   {
763     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
764     int nbKnownFaces;
765     do {
766       nbKnownFaces = faceMap.Extent();
767       StdMeshers_FaceSide *rightSide, *topSide; // sides of the quad
768       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
769       {
770         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
771         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
772         {
773           const TopoDS_Edge & rightE = rightSide->Edge( iE );
774           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
775           for ( ; face.More(); face.Next() )
776             if ( faceMap.Add( face.Value() ))
777             {
778               // a new wall FACE encountered, store it in thePrism.myWallQuads
779               const int iRight = thePrism.myRightQuadIndex[i];
780               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
781               const TopoDS_Edge&   newBotE = topSide->Edge(0);
782               const TopoDS_Shape& newWallF = face.Value();
783               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
784               if ( !thePrism.myWallQuads[ iRight ].back() )
785                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
786                                    " not meshable with quadrangles"));
787               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
788                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
789             }
790         }
791       }
792     } while ( nbKnownFaces != faceMap.Extent() );
793
794     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
795     if ( totalNbFaces - faceMap.Extent() > 2 )
796     {
797       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
798       {
799         StdMeshers_FaceSide* topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
800         const TopoDS_Edge &     topE = topSide->Edge( 0 );
801         if ( topSide->NbEdges() > 1 )
802           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
803                              shapeID( thePrism.myWallQuads[i].back()->face )
804                              << " has a composite top edge"));
805         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
806         for ( ; faceIt.More(); faceIt.Next() )
807           if ( faceMap.Add( faceIt.Value() ))
808           {
809             // a new wall FACE encountered, store it in wallQuads
810             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
811             if ( !thePrism.myWallQuads[ i ].back() )
812               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
813                                  " not meshable with quadrangles"));
814             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
815               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
816             if ( totalNbFaces - faceMap.Extent() == 2 )
817             {
818               i = thePrism.myWallQuads.size(); // to quit from the outer loop
819               break;
820             }
821           }
822       }
823     }
824   } // while ( totalNbFaces - faceMap.Extent() > 2 )
825
826   // ------------------
827   // Find the top FACE
828   // ------------------
829
830   if ( thePrism.myTop.IsNull() )
831   {
832     // now only top and bottom FACEs are not in the faceMap
833     faceMap.Add( thePrism.myBottom );
834     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE );f.More(); f.Next() )
835       if ( !faceMap.Contains( f.Current() )) {
836         thePrism.myTop = TopoDS::Face( f.Current() );
837         break;
838       }
839     if ( thePrism.myTop.IsNull() )
840       return toSM( error("Top face not found"));
841   }
842
843   // Check that the top FACE shares all the top EDGEs
844   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
845   {
846     StdMeshers_FaceSide* topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
847     const TopoDS_Edge &     topE = topSide->Edge( 0 );
848     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
849       return toSM( error( TCom("Wrong source face (#") << shapeID( thePrism.myBottom )));
850   }
851
852   return true;
853 }
854
855 //=======================================================================
856 //function : compute
857 //purpose  : Compute mesh on a SOLID
858 //=======================================================================
859
860 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
861 {
862   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
863   if ( _computeCanceled )
864     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
865
866   // Make all side FACEs of thePrism meshed with quads
867   if ( !computeWalls( thePrism ))
868     return false;
869
870   // Analyse mesh and geometry to find block sub-shapes and submeshes
871   if ( !myBlock.Init( myHelper, thePrism ))
872     return toSM( error( myBlock.GetError()));
873
874   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
875
876   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
877
878
879   // To compute coordinates of a node inside a block, it is necessary to know
880   // 1. normalized parameters of the node by which
881   // 2. coordinates of node projections on all block sub-shapes are computed
882
883   // So we fill projections on vertices at once as they are same for all nodes
884   myShapeXYZ.resize( myBlock.NbSubShapes() );
885   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
886     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
887     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
888   }
889
890   // Projections on the top and bottom faces are taken from nodes existing
891   // on these faces; find correspondence between bottom and top nodes
892   myBotToColumnMap.clear();
893   if ( !assocOrProjBottom2Top() ) // it also fills myBotToColumnMap
894     return false;
895
896
897   // Create nodes inside the block
898
899   // try to use transformation (issue 0020680)
900   vector<gp_Trsf> trsf;
901   if ( myBlock.GetLayersTransformation( trsf, thePrism ))
902   {
903     // loop on nodes inside the bottom face
904     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
905     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
906     {
907       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
908       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
909         continue; // node is not inside face 
910
911       // column nodes; middle part of the column are zero pointers
912       TNodeColumn& column = bot_column->second;
913       TNodeColumn::iterator columnNodes = column.begin();
914       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
915       {
916         const SMDS_MeshNode* & node = *columnNodes;
917         if ( node ) continue; // skip bottom or top node
918
919         gp_XYZ coords = tBotNode.GetCoords();
920         trsf[z-1].Transforms( coords );
921         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
922         meshDS->SetNodeInVolume( node, volumeID );
923       }
924     } // loop on bottom nodes
925   }
926   else // use block approach
927   {
928     // loop on nodes inside the bottom face
929     Prism_3D::TNode prevBNode;
930     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
931     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
932     {
933       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
934       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
935         continue; // node is not inside face 
936
937       // column nodes; middle part of the column are zero pointers
938       TNodeColumn& column = bot_column->second;
939
940       // compute bottom node parameters
941       gp_XYZ paramHint(-1,-1,-1);
942       if ( prevBNode.IsNeighbor( tBotNode ))
943         paramHint = prevBNode.GetParams();
944       if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
945                                        ID_BOT_FACE, paramHint ))
946         return toSM( error(TCom("Can't compute normalized parameters for node ")
947                            << tBotNode.myNode->GetID() << " on the face #"
948                            << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
949       prevBNode = tBotNode;
950
951       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
952       gp_XYZ botParams          = tBotNode.GetParams();
953
954       // compute top node parameters
955       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
956       gp_XYZ topParams = botParams;
957       topParams.SetZ( 1 );
958       if ( column.size() > 2 ) {
959         gp_Pnt topCoords = myShapeXYZ[ ID_TOP_FACE ];
960         if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
961           return toSM( error(TCom("Can't compute normalized parameters ")
962                              << "for node " << column.back()->GetID()
963                              << " on the face #"<< column.back()->getshapeId() ));
964       }
965
966       // vertical loop
967       TNodeColumn::iterator columnNodes = column.begin();
968       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
969       {
970         const SMDS_MeshNode* & node = *columnNodes;
971         if ( node ) continue; // skip bottom or top node
972
973         // params of a node to create
974         double rz = (double) z / (double) ( column.size() - 1 );
975         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
976
977         // set coords on all faces and nodes
978         const int nbSideFaces = 4;
979         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
980                                          SMESH_Block::ID_Fx1z,
981                                          SMESH_Block::ID_F0yz,
982                                          SMESH_Block::ID_F1yz };
983         for ( int iF = 0; iF < nbSideFaces; ++iF )
984           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
985             return false;
986
987         // compute coords for a new node
988         gp_XYZ coords;
989         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
990           return toSM( error("Can't compute coordinates by normalized parameters"));
991
992         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
993         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
994         SHOWYXZ("ShellPoint ",coords);
995
996         // create a node
997         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
998         meshDS->SetNodeInVolume( node, volumeID );
999       }
1000     } // loop on bottom nodes
1001   }
1002
1003   // Create volumes
1004
1005   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1006   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1007
1008   // loop on bottom mesh faces
1009   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1010   while ( faceIt->more() )
1011   {
1012     const SMDS_MeshElement* face = faceIt->next();
1013     if ( !face || face->GetType() != SMDSAbs_Face )
1014       continue;
1015
1016     // find node columns for each node
1017     int nbNodes = face->NbCornerNodes();
1018     vector< const TNodeColumn* > columns( nbNodes );
1019     for ( int i = 0; i < nbNodes; ++i )
1020     {
1021       const SMDS_MeshNode* n = face->GetNode( i );
1022       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1023         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1024         if ( bot_column == myBotToColumnMap.end() )
1025           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1026         columns[ i ] = & bot_column->second;
1027       }
1028       else {
1029         columns[ i ] = myBlock.GetNodeColumn( n );
1030         if ( !columns[ i ] )
1031           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1032       }
1033     }
1034     // create prisms
1035     AddPrisms( columns, myHelper );
1036
1037   } // loop on bottom mesh faces
1038
1039   // clear data
1040   myBotToColumnMap.clear();
1041   myBlock.Clear();
1042         
1043   return true;
1044 }
1045
1046 //=======================================================================
1047 //function : computeWalls
1048 //purpose  : Compute 2D mesh on walls FACEs of a prism
1049 //=======================================================================
1050
1051 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1052 {
1053   SMESH_Mesh*     mesh = myHelper->GetMesh();
1054   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1055   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1056
1057   TProjction1dAlgo* projector1D = TProjction1dAlgo::instance( this );
1058   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1059
1060   SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1061   hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1062   hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1063
1064   // Discretize equally 'vertical' EDGEs
1065   // -----------------------------------
1066   // find source FACE sides for projection: either already computed ones or
1067   // the 'most composite' ones
1068   multimap< int, int > wgt2quad;
1069   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1070   {
1071     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1072     int wgt = 0; // "weight"
1073     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1074     {
1075       StdMeshers_FaceSide* lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1076       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1077       {
1078         ++wgt;
1079         const TopoDS_Edge& E = lftSide->Edge(i);
1080         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1081           wgt += 10;
1082         else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1083           wgt += 100;
1084       }
1085     }
1086     wgt2quad.insert( make_pair( wgt, iW ));
1087
1088     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1089     if ( myHelper->GetIsQuadratic() )
1090     {
1091       quad = thePrism.myWallQuads[iW].begin();
1092       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1093         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1094           (*quad)->side[ i ]->SetIgnoreMediumNodes( true );
1095     }
1096   }
1097
1098   // Project 'vertical' EDGEs, from left to right
1099   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1100   for ( ; w2q != wgt2quad.rend(); ++w2q )
1101   {
1102     const int iW = w2q->second;
1103     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1104     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1105     for ( ; quad != quads.end(); ++quad )
1106     {
1107       StdMeshers_FaceSide* rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1108       StdMeshers_FaceSide* lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1109       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1110                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1111       if ( swapLeftRight )
1112         std::swap( lftSide, rgtSide );
1113
1114       // assure that all the source (left) EDGEs are meshed
1115       int nbSrcSegments = 0;
1116       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1117       {
1118         const TopoDS_Edge& srcE = lftSide->Edge(i);
1119         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1120         if ( !srcSM->IsMeshComputed() ) {
1121           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1122           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1123           srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1124           if ( !srcSM->IsMeshComputed() )
1125             return false;
1126         }
1127         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1128       }
1129       // check target EDGEs
1130       int nbTgtMeshed = 0, nbTgtSegments = 0;
1131       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1132       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1133       {
1134         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1135         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1136         if (( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1137           ++nbTgtMeshed;
1138           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1139         }
1140       }
1141       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1142       {
1143         if ( nbTgtSegments != nbSrcSegments )
1144         {
1145           for ( int i = 0; i < lftSide->NbEdges(); ++i )
1146             addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1147           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1148             addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1149           return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1150                               << shapeID( lftSide->Edge(0) ) << " and #"
1151                               << shapeID( rgtSide->Edge(0) ) << ": "
1152                               << nbSrcSegments << " != " << nbTgtSegments ));
1153         }
1154         continue;
1155       }
1156       // Compute 'vertical projection'
1157       if ( nbTgtMeshed == 0 )
1158       {
1159         // compute nodes on target VERTEXes
1160         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1161         if ( srcNodeStr.size() == 0 )
1162           return toSM( error( TCom("Invalid node positions on edge #") <<
1163                               shapeID( lftSide->Edge(0) )));
1164         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1165         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1166         {
1167           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1168           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1169           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1170           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1171           newNodes[ is2ndV ? 0 : newNodes.size()-1 ] = (SMDS_MeshNode*) n;
1172         }
1173
1174         // compute nodes on target EDGEs
1175         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1176         rgtSide->Reverse(); // direct it same as the lftSide
1177         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1178         TopoDS_Edge tgtEdge;
1179         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1180         {
1181           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1182           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1183           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1184           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1185         }
1186         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1187         {
1188           // find an EDGE to set a new segment
1189           std::pair<int, TopAbs_ShapeEnum> id2type = 
1190             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1191           if ( id2type.second != TopAbs_EDGE )
1192           {
1193             // new nodes are on different EDGEs; put one of them on VERTEX
1194             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1195             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1196             const gp_Pnt           p = BRep_Tool::Pnt( rgtSide->LastVertex( edgeIndex ));
1197             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1198                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1199             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1200             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], rgtSide->LastVertex( edgeIndex ));
1201             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1202             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1203           }
1204           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1205           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1206         }
1207         myHelper->SetElementsOnShape( true );
1208         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1209         {
1210           const TopoDS_Edge& E = rgtSide->Edge( i );
1211           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1212           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1213         }
1214
1215         // to continue projection from the just computed side as a source
1216         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1217         {
1218           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1219           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1220           wgt2quad.insert( wgt2quadKeyVal );
1221           w2q = wgt2quad.rbegin();
1222         }
1223       }
1224       else
1225       {
1226         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1227         //return toSM( error("Partial projection not implemented"));
1228       }
1229     } // loop on quads of a composite wall side
1230   } // loop on the ordered wall sides
1231
1232
1233
1234   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1235   {
1236     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1237     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1238     {
1239       // Top EDGEs must be projections from the bottom ones
1240       // to compute stuctured quad mesh on wall FACEs
1241       // ---------------------------------------------------
1242       {
1243         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge(0);
1244         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ]->Edge(0);
1245         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1246         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1247         SMESH_subMesh*    srcSM = botSM;
1248         SMESH_subMesh*    tgtSM = topSM;
1249         if ( !srcSM->IsMeshComputed() && topSM->IsMeshComputed() )
1250           std::swap( srcSM, tgtSM );
1251
1252         if ( !srcSM->IsMeshComputed() )
1253         {
1254           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1255           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1256           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1257         }
1258         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1259
1260         if ( !tgtSM->IsMeshComputed() )
1261         {
1262           // compute nodes on VERTEXes
1263           tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1264           // project segments
1265           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1266           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1267           projector1D->InitComputeError();
1268           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1269           if ( !ok )
1270           {
1271             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1272             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1273             tgtSM->GetComputeError() = err;
1274             return false;
1275           }
1276         }
1277         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1278       }
1279
1280       // Compute quad mesh on wall FACEs
1281       // -------------------------------
1282       const TopoDS_Face& face = (*quad)->face;
1283       SMESH_subMesh* fSM = mesh->GetSubMesh( face );
1284       if ( ! fSM->IsMeshComputed() )
1285       {
1286         // make all EDGES meshed
1287         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1288         if ( !fSM->SubMeshesComputed() )
1289           return toSM( error( COMPERR_BAD_INPUT_MESH,
1290                               "Not all edges have valid algorithm and hypothesis"));
1291         // mesh the <face>
1292         quadAlgo->InitComputeError();
1293         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1294         bool ok = quadAlgo->Compute( *mesh, face );
1295         fSM->GetComputeError() = quadAlgo->GetComputeError();
1296         if ( !ok )
1297           return false;
1298         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1299       }
1300       if ( myHelper->GetIsQuadratic() )
1301       {
1302         // fill myHelper with medium nodes built by quadAlgo
1303         SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements();
1304         while ( fIt->more() )
1305           myHelper->AddTLinks( dynamic_cast<const SMDS_MeshFace*>( fIt->next() ));
1306       }
1307     }
1308   }
1309
1310   return true;
1311 }
1312
1313 //=======================================================================
1314 //function : Evaluate
1315 //purpose  : 
1316 //=======================================================================
1317
1318 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1319                                    const TopoDS_Shape& theShape,
1320                                    MapShapeNbElems&    aResMap)
1321 {
1322   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1323   {
1324     bool ok = true;
1325     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1326       ok &= Evaluate( theMesh, it.Value(), aResMap );
1327     return ok;
1328   }
1329   SMESH_MesherHelper helper( theMesh );
1330   myHelper = &helper;
1331   myHelper->SetSubShape( theShape );
1332
1333   // find face contains only triangles
1334   vector < SMESH_subMesh * >meshFaces;
1335   TopTools_SequenceOfShape aFaces;
1336   int NumBase = 0, i = 0, NbQFs = 0;
1337   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1338     i++;
1339     aFaces.Append(exp.Current());
1340     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1341     meshFaces.push_back(aSubMesh);
1342     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1343     if( anIt==aResMap.end() )
1344       return toSM( error( "Submesh can not be evaluated"));
1345
1346     std::vector<int> aVec = (*anIt).second;
1347     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1348     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1349     if( nbtri==0 && nbqua>0 ) {
1350       NbQFs++;
1351     }
1352     if( nbtri>0 ) {
1353       NumBase = i;
1354     }
1355   }
1356
1357   if(NbQFs<4) {
1358     std::vector<int> aResVec(SMDSEntity_Last);
1359     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1360     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1361     aResMap.insert(std::make_pair(sm,aResVec));
1362     return toSM( error( "Submesh can not be evaluated" ));
1363   }
1364
1365   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1366
1367   // find number of 1d elems for base face
1368   int nb1d = 0;
1369   TopTools_MapOfShape Edges1;
1370   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1371     Edges1.Add(exp.Current());
1372     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1373     if( sm ) {
1374       MapShapeNbElemsItr anIt = aResMap.find(sm);
1375       if( anIt == aResMap.end() ) continue;
1376       std::vector<int> aVec = (*anIt).second;
1377       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1378     }
1379   }
1380   // find face opposite to base face
1381   int OppNum = 0;
1382   for(i=1; i<=6; i++) {
1383     if(i==NumBase) continue;
1384     bool IsOpposite = true;
1385     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1386       if( Edges1.Contains(exp.Current()) ) {
1387         IsOpposite = false;
1388         break;
1389       }
1390     }
1391     if(IsOpposite) {
1392       OppNum = i;
1393       break;
1394     }
1395   }
1396   // find number of 2d elems on side faces
1397   int nb2d = 0;
1398   for(i=1; i<=6; i++) {
1399     if( i==OppNum || i==NumBase ) continue;
1400     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1401     if( anIt == aResMap.end() ) continue;
1402     std::vector<int> aVec = (*anIt).second;
1403     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1404   }
1405   
1406   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
1407   std::vector<int> aVec = (*anIt).second;
1408   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
1409                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
1410   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1411   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1412   int nb0d_face0 = aVec[SMDSEntity_Node];
1413   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
1414
1415   std::vector<int> aResVec(SMDSEntity_Last);
1416   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1417   if(IsQuadratic) {
1418     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1419     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1420     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
1421   }
1422   else {
1423     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
1424     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1425     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1426   }
1427   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1428   aResMap.insert(std::make_pair(sm,aResVec));
1429
1430   return true;
1431 }
1432
1433 //================================================================================
1434 /*!
1435  * \brief Create prisms
1436  * \param columns - columns of nodes generated from nodes of a mesh face
1437  * \param helper - helper initialized by mesh and shape to add prisms to
1438  */
1439 //================================================================================
1440
1441 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
1442                                      SMESH_MesherHelper*          helper)
1443 {
1444   int nbNodes = columns.size();
1445   int nbZ     = columns[0]->size();
1446   if ( nbZ < 2 ) return;
1447
1448   // find out orientation
1449   bool isForward = true;
1450   SMDS_VolumeTool vTool;
1451   int z = 1;
1452   switch ( nbNodes ) {
1453   case 3: {
1454     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
1455                                   (*columns[1])[z-1],
1456                                   (*columns[2])[z-1],
1457                                   (*columns[0])[z],   // top
1458                                   (*columns[1])[z],
1459                                   (*columns[2])[z] );
1460     vTool.Set( &tmpPenta );
1461     isForward  = vTool.IsForward();
1462     break;
1463   }
1464   case 4: {
1465     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
1466                                (*columns[2])[z-1], (*columns[3])[z-1],
1467                                (*columns[0])[z],   (*columns[1])[z],   // top
1468                                (*columns[2])[z],   (*columns[3])[z] );
1469     vTool.Set( &tmpHex );
1470     isForward  = vTool.IsForward();
1471     break;
1472   }
1473   default:
1474     const int di = (nbNodes+1) / 3;
1475     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
1476                                 (*columns[di]  )[z-1],
1477                                 (*columns[2*di])[z-1],
1478                                 (*columns[0]   )[z],
1479                                 (*columns[di]  )[z],
1480                                 (*columns[2*di])[z] );
1481     vTool.Set( &tmpVol );
1482     isForward  = vTool.IsForward();
1483   }
1484
1485   // vertical loop on columns
1486
1487   helper->SetElementsOnShape( true );
1488
1489   switch ( nbNodes ) {
1490
1491   case 3: { // ---------- pentahedra
1492     const int i1 = isForward ? 1 : 2;
1493     const int i2 = isForward ? 2 : 1;
1494     for ( z = 1; z < nbZ; ++z )
1495       helper->AddVolume( (*columns[0 ])[z-1], // bottom
1496                          (*columns[i1])[z-1],
1497                          (*columns[i2])[z-1],
1498                          (*columns[0 ])[z],   // top
1499                          (*columns[i1])[z],
1500                          (*columns[i2])[z] );
1501     break;
1502   }
1503   case 4: { // ---------- hexahedra
1504     const int i1 = isForward ? 1 : 3;
1505     const int i3 = isForward ? 3 : 1;
1506     for ( z = 1; z < nbZ; ++z )
1507       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
1508                          (*columns[2])[z-1], (*columns[i3])[z-1],
1509                          (*columns[0])[z],   (*columns[i1])[z],     // top
1510                          (*columns[2])[z],   (*columns[i3])[z] );
1511     break;
1512   }
1513   case 6: { // ---------- octahedra
1514     const int iBase1 = isForward ? -1 : 0;
1515     const int iBase2 = isForward ?  0 :-1;
1516     for ( z = 1; z < nbZ; ++z )
1517       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
1518                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
1519                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
1520                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
1521                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
1522                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
1523     break;
1524   }
1525   default: // ---------- polyhedra
1526     vector<int> quantities( 2 + nbNodes, 4 );
1527     quantities[0] = quantities[1] = nbNodes;
1528     columns.resize( nbNodes + 1 );
1529     columns[ nbNodes ] = columns[ 0 ];
1530     const int i1 = isForward ? 1 : 3;
1531     const int i3 = isForward ? 3 : 1;
1532     const int iBase1 = isForward ? -1 : 0;
1533     const int iBase2 = isForward ?  0 :-1;
1534     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
1535     for ( z = 1; z < nbZ; ++z )
1536     {
1537       for ( int i = 0; i < nbNodes; ++i ) {
1538         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
1539         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
1540         // side
1541         int di = 2*nbNodes + 4*i;
1542         nodes[ di+0 ] = (*columns[i  ])[z  ];
1543         nodes[ di+i1] = (*columns[i+1])[z  ];
1544         nodes[ di+2 ] = (*columns[i+1])[z-1];
1545         nodes[ di+i3] = (*columns[i  ])[z-1];
1546       }
1547       helper->AddPolyhedralVolume( nodes, quantities );
1548     }
1549
1550   } // switch ( nbNodes )
1551 }
1552
1553 //================================================================================
1554 /*!
1555  * \brief Find correspondence between bottom and top nodes
1556  *  If elements on the bottom and top faces are topologically different,
1557  *  and projection is possible and allowed, perform the projection
1558  *  \retval bool - is a success or not
1559  */
1560 //================================================================================
1561
1562 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
1563 {
1564   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1565   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1566
1567   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1568   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1569
1570   if ( !botSMDS || botSMDS->NbElements() == 0 )
1571   {
1572     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape() );
1573     botSMDS = botSM->GetSubMeshDS();
1574     if ( !botSMDS || botSMDS->NbElements() == 0 )
1575       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
1576   }
1577
1578   bool needProject = !topSM->IsMeshComputed();
1579   if ( !needProject && 
1580        (botSMDS->NbElements() != topSMDS->NbElements() ||
1581         botSMDS->NbNodes()    != topSMDS->NbNodes()))
1582   {
1583     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
1584             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
1585     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
1586             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
1587     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1588                        <<" and #"<< topSM->GetId() << " seems different" ));
1589   }
1590
1591   if ( 0/*needProject && !myProjectTriangles*/ )
1592     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1593                        <<" and #"<< topSM->GetId() << " seems different" ));
1594   ///RETURN_BAD_RESULT("Need to project but not allowed");
1595
1596   if ( needProject )
1597   {
1598     return projectBottomToTop();
1599   }
1600
1601   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
1602   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
1603   // associate top and bottom faces
1604   TAssocTool::TShapeShapeMap shape2ShapeMap;
1605   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
1606                                              topFace, myBlock.Mesh(),
1607                                              shape2ShapeMap) )
1608     return toSM( error(TCom("Topology of faces #") << botSM->GetId()
1609                        <<" and #"<< topSM->GetId() << " seems different" ));
1610
1611   // Find matching nodes of top and bottom faces
1612   TNodeNodeMap n2nMap;
1613   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
1614                                                topFace, myBlock.Mesh(),
1615                                                shape2ShapeMap, n2nMap ))
1616     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1617                        <<" and #"<< topSM->GetId() << " seems different" ));
1618
1619   // Fill myBotToColumnMap
1620
1621   int zSize = myBlock.VerticalSize();
1622   //TNode prevTNode;
1623   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
1624   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
1625   {
1626     const SMDS_MeshNode* botNode = bN_tN->first;
1627     const SMDS_MeshNode* topNode = bN_tN->second;
1628     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1629       continue; // wall columns are contained in myBlock
1630     // create node column
1631     Prism_3D::TNode bN( botNode );
1632     TNode2ColumnMap::iterator bN_col = 
1633       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1634     TNodeColumn & column = bN_col->second;
1635     column.resize( zSize );
1636     column.front() = botNode;
1637     column.back()  = topNode;
1638   }
1639   return true;
1640 }
1641
1642 //================================================================================
1643 /*!
1644  * \brief Remove quadrangles from the top face and
1645  * create triangles there by projection from the bottom
1646  * \retval bool - a success or not
1647  */
1648 //================================================================================
1649
1650 bool StdMeshers_Prism_3D::projectBottomToTop()
1651 {
1652   SMESHDS_Mesh*  meshDS = myBlock.MeshDS();
1653   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1654   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1655
1656   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1657   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1658
1659   if ( topSMDS && topSMDS->NbElements() > 0 )
1660     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1661
1662   const TopoDS_Shape& botFace = myBlock.Shape( ID_BOT_FACE ); // oriented within the 3D SHAPE
1663   const TopoDS_Shape& topFace = myBlock.Shape( ID_TOP_FACE);
1664   int topFaceID = meshDS->ShapeToIndex( topFace );
1665
1666   // Fill myBotToColumnMap
1667
1668   int zSize = myBlock.VerticalSize();
1669   Prism_3D::TNode prevTNode;
1670   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
1671   while ( nIt->more() )
1672   {
1673     const SMDS_MeshNode* botNode = nIt->next();
1674     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1675       continue; // strange
1676     // compute bottom node params
1677     Prism_3D::TNode bN( botNode );
1678     gp_XYZ paramHint(-1,-1,-1);
1679     if ( prevTNode.IsNeighbor( bN ))
1680       paramHint = prevTNode.GetParams();
1681     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
1682                                      ID_BOT_FACE, paramHint ))
1683       return toSM( error(TCom("Can't compute normalized parameters for node ")
1684                          << botNode->GetID() << " on the face #"<< botSM->GetId() ));
1685     prevTNode = bN;
1686     // compute top node coords
1687     gp_XYZ topXYZ; gp_XY topUV;
1688     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
1689          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
1690       return toSM( error(TCom("Can't compute coordinates "
1691                               "by normalized parameters on the face #")<< topSM->GetId() ));
1692     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
1693     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
1694     // create node column
1695     TNode2ColumnMap::iterator bN_col = 
1696       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1697     TNodeColumn & column = bN_col->second;
1698     column.resize( zSize );
1699     column.front() = botNode;
1700     column.back()  = topNode;
1701   }
1702
1703   // Create top faces
1704
1705   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
1706
1707   // care of orientation;
1708   // if the bottom faces is orienetd OK then top faces must be reversed
1709   bool reverseTop = true;
1710   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
1711     reverseTop = ! myHelper->IsReversedSubMesh( TopoDS::Face( botFace ));
1712   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
1713
1714   // loop on bottom mesh faces
1715   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
1716   vector< const SMDS_MeshNode* > nodes;
1717   while ( faceIt->more() )
1718   {
1719     const SMDS_MeshElement* face = faceIt->next();
1720     if ( !face || face->GetType() != SMDSAbs_Face )
1721       continue;
1722
1723     // find top node in columns for each bottom node
1724     int nbNodes = face->NbCornerNodes();
1725     nodes.resize( nbNodes );
1726     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
1727     {
1728       const SMDS_MeshNode* n = face->GetNode( *iPtr );
1729       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1730         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1731         if ( bot_column == myBotToColumnMap.end() )
1732           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1733         nodes[ iFrw ] = bot_column->second.back();
1734       }
1735       else {
1736         const TNodeColumn* column = myBlock.GetNodeColumn( n );
1737         if ( !column )
1738           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1739         nodes[ iFrw ] = column->back();
1740       }
1741     }
1742     SMDS_MeshElement* newFace = 0;
1743     switch ( nbNodes ) {
1744
1745     case 3: {
1746       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
1747       break;
1748       }
1749     case 4: {
1750       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
1751       break;
1752       }
1753     default:
1754       newFace = meshDS->AddPolygonalFace( nodes );
1755     }
1756     if ( newFace )
1757       meshDS->SetMeshElementOnShape( newFace, topFaceID );
1758   }
1759
1760   myHelper->SetElementsOnShape( oldSetElemsOnShape );  
1761
1762   return true;
1763 }
1764
1765 //=======================================================================
1766 //function : project2dMesh
1767 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
1768 //           to a source FACE of another prism (theTgtFace)
1769 //=======================================================================
1770
1771 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
1772                                         const TopoDS_Face& theTgtFace)
1773 {
1774   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
1775   projector2D->myHyp.SetSourceFace( theSrcFace );
1776   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
1777
1778   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
1779   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
1780   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1781
1782   return ok;
1783 }
1784
1785 //================================================================================
1786 /*!
1787  * \brief Set projection coordinates of a node to a face and it's sub-shapes
1788  * \param faceID - the face given by in-block ID
1789  * \param params - node normalized parameters
1790  * \retval bool - is a success
1791  */
1792 //================================================================================
1793
1794 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
1795 {
1796   // find base and top edges of the face
1797   enum { BASE = 0, TOP, LEFT, RIGHT };
1798   vector< int > edgeVec; // 0-base, 1-top
1799   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
1800
1801   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
1802   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
1803
1804   SHOWYXZ("\nparams ", params);
1805   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
1806   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
1807
1808   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
1809   {
1810     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
1811     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
1812
1813     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
1814     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
1815   }
1816   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
1817   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
1818
1819   return true;
1820 }
1821
1822 //=======================================================================
1823 //function : toSM
1824 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
1825 //=======================================================================
1826
1827 bool StdMeshers_Prism_3D::toSM( bool isOK )
1828 {
1829   if ( mySetErrorToSM &&
1830        !isOK &&
1831        myHelper &&
1832        !myHelper->GetSubShape().IsNull() &&
1833        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
1834   {
1835     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
1836     sm->GetComputeError() = this->GetComputeError();
1837     // clear error in order not to return it twice
1838     _error = COMPERR_OK;
1839     _comment.clear();
1840   }
1841   return isOK;
1842 }
1843
1844 //=======================================================================
1845 //function : shapeID
1846 //purpose  : Return index of a shape
1847 //=======================================================================
1848
1849 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
1850 {
1851   if ( S.IsNull() ) return 0;
1852   if ( !myHelper  ) return -3;
1853   return myHelper->GetMeshDS()->ShapeToIndex( S );
1854 }
1855
1856 namespace Prism_3D
1857 {
1858   //================================================================================
1859   /*!
1860    * \brief Return true if this node and other one belong to one face
1861    */
1862   //================================================================================
1863
1864   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
1865   {
1866     if ( !other.myNode || !myNode ) return false;
1867
1868     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
1869     while ( fIt->more() )
1870       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
1871         return true;
1872     return false;
1873   }
1874
1875   //================================================================================
1876   /*!
1877    * \brief Prism initialization
1878    */
1879   //================================================================================
1880
1881   void TPrismTopo::Clear()
1882   {
1883     myShape3D.Nullify();
1884     myTop.Nullify();
1885     myBottom.Nullify();
1886     myWallQuads.clear();
1887     myBottomEdges.clear();
1888     myNbEdgesInWires.clear();
1889     myWallQuads.clear();
1890   }
1891
1892 } // namespace Prism_3D
1893
1894 //================================================================================
1895 /*!
1896  * \brief Constructor. Initialization is needed
1897  */
1898 //================================================================================
1899
1900 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
1901 {
1902   mySide = 0;
1903 }
1904
1905 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
1906 {
1907   Clear();
1908 }
1909 void StdMeshers_PrismAsBlock::Clear()
1910 {
1911   myHelper = 0;
1912   myShapeIDMap.Clear();
1913   myError.reset();
1914
1915   if ( mySide ) {
1916     delete mySide; mySide = 0;
1917   }
1918   myParam2ColumnMaps.clear();
1919   myShapeIndex2ColumnMap.clear();
1920 }
1921
1922 //=======================================================================
1923 //function : initPrism
1924 //purpose  : Analyse shape geometry and mesh.
1925 //           If there are triangles on one of faces, it becomes 'bottom'.
1926 //           thePrism.myBottom can be already set up.
1927 //=======================================================================
1928
1929 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
1930                                     const TopoDS_Shape&   shape3D)
1931 {
1932   myHelper->SetSubShape( shape3D );
1933
1934   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
1935   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
1936
1937   // detect not-quad FACE sub-meshes of the 3D SHAPE
1938   list< SMESH_subMesh* > notQuadGeomSubMesh;
1939   list< SMESH_subMesh* > notQuadElemSubMesh;
1940   int nbFaces = 0;
1941   //
1942   SMESH_subMesh* anyFaceSM = 0;
1943   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
1944   while ( smIt->more() )
1945   {
1946     SMESH_subMesh* sm = smIt->next();
1947     const TopoDS_Shape& face = sm->GetSubShape();
1948     if      ( face.ShapeType() > TopAbs_FACE ) break;
1949     else if ( face.ShapeType() < TopAbs_FACE ) continue;
1950     nbFaces++;
1951     anyFaceSM = sm;
1952
1953     // is quadrangle FACE?
1954     list< TopoDS_Edge > orderedEdges;
1955     list< int >         nbEdgesInWires;
1956     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
1957                                                 nbEdgesInWires );
1958     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
1959       notQuadGeomSubMesh.push_back( sm );
1960
1961     // look for not quadrangle mesh elements
1962     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
1963       if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
1964         notQuadElemSubMesh.push_back( sm );
1965   }
1966
1967   int nbNotQuadMeshed = notQuadElemSubMesh.size();
1968   int       nbNotQuad = notQuadGeomSubMesh.size();
1969   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1970
1971   // detect bad cases
1972   if ( nbNotQuadMeshed > 2 )
1973   {
1974     return toSM( error(COMPERR_BAD_INPUT_MESH,
1975                        TCom("More than 2 faces with not quadrangle elements: ")
1976                        <<nbNotQuadMeshed));
1977   }
1978   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
1979   {
1980     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
1981     // Remove from notQuadGeomSubMesh faces meshed with regular grid
1982     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
1983                                          TQuadrangleAlgo::instance(this,myHelper) );
1984     nbNotQuad -= nbQuasiQuads;
1985     if ( nbNotQuad > 2 )
1986       return toSM( error(COMPERR_BAD_SHAPE,
1987                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
1988     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1989   }
1990
1991   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
1992   // If there are not quadrangle FACEs, they are top and bottom ones.
1993   // Not quadrangle FACEs must be only on top and bottom.
1994
1995   SMESH_subMesh * botSM = 0;
1996   SMESH_subMesh * topSM = 0;
1997
1998   if ( hasNotQuad ) // can chose a bottom FACE
1999   {
2000     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
2001     else                       botSM = notQuadGeomSubMesh.front();
2002     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
2003     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
2004
2005     if ( topSM == botSM ) {
2006       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
2007       else                       topSM = notQuadGeomSubMesh.front();
2008     }
2009
2010     // detect mesh triangles on wall FACEs
2011     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
2012       bool ok = false;
2013       if ( nbNotQuadMeshed == 1 )
2014         ok = ( find( notQuadGeomSubMesh.begin(),
2015                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
2016       else
2017         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
2018       if ( !ok )
2019         return toSM( error(COMPERR_BAD_INPUT_MESH,
2020                            "Side face meshed with not quadrangle elements"));
2021     }
2022   }
2023
2024   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
2025
2026   // use thePrism.myBottom
2027   if ( !thePrism.myBottom.IsNull() )
2028   {
2029     if ( botSM ) {
2030       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
2031         std::swap( botSM, topSM );
2032         if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom ))
2033           return toSM( error( COMPERR_BAD_INPUT_MESH,
2034                               "Incompatible non-structured sub-meshes"));
2035       }
2036     }
2037     else {
2038       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2039     }
2040   }
2041   else if ( !botSM ) // find a proper bottom
2042   {
2043     // composite walls or not prism shape
2044     for ( TopExp_Explorer f( shape3D, TopAbs_FACE ); f.More(); f.Next() )
2045     {
2046       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
2047       if ( nbFaces >= minNbFaces)
2048       {
2049         thePrism.Clear();
2050         thePrism.myBottom = TopoDS::Face( f.Current() );
2051         if ( initPrism( thePrism, shape3D ))
2052           return true;
2053       }
2054       return toSM( error( COMPERR_BAD_SHAPE ));
2055     }
2056   }
2057
2058   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
2059   TopoDS_Vertex V000;
2060   double minVal = DBL_MAX, minX, val;
2061   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
2062         exp.More(); exp.Next() )
2063   {
2064     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
2065     gp_Pnt P = BRep_Tool::Pnt( v );
2066     val = P.X() + P.Y() + P.Z();
2067     if ( val < minVal || ( val == minVal && P.X() < minX )) {
2068       V000 = v;
2069       minVal = val;
2070       minX = P.X();
2071     }
2072   }
2073
2074   thePrism.myShape3D = shape3D;
2075   if ( thePrism.myBottom.IsNull() )
2076     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
2077   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( shape3D,
2078                                                            thePrism.myBottom ));
2079   // Get ordered bottom edges
2080   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
2081     TopoDS::Face( thePrism.myBottom.Reversed() );
2082   SMESH_Block::GetOrderedEdges( reverseBottom,
2083                                 thePrism.myBottomEdges,
2084                                 thePrism.myNbEdgesInWires, V000 );
2085
2086   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
2087   if ( !getWallFaces( thePrism, nbFaces ))
2088     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
2089
2090   if ( topSM )
2091   {
2092     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
2093       return toSM( error
2094                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2095                     "Non-quadrilateral faces are not opposite"));
2096
2097     // check that the found top and bottom FACEs are opposite
2098     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
2099     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
2100       if ( myHelper->IsSubShape( *edge, thePrism.myTop ))
2101         return toSM( error
2102                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
2103                       "Non-quadrilateral faces are not opposite"));
2104   }
2105
2106   return true;
2107 }
2108
2109 //================================================================================
2110 /*!
2111  * \brief Initialization.
2112  * \param helper - helper loaded with mesh and 3D shape
2113  * \param thePrism - a prosm data
2114  * \retval bool - false if a mesh or a shape are KO
2115  */
2116 //================================================================================
2117
2118 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
2119                                    const Prism_3D::TPrismTopo& thePrism)
2120 {
2121   myHelper = helper;
2122   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2123   SMESH_Mesh*     mesh = myHelper->GetMesh();
2124
2125   if ( mySide ) {
2126     delete mySide; mySide = 0;
2127   }
2128   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
2129   vector< pair< double, double> > params( NB_WALL_FACES );
2130   mySide = new TSideFace( *mesh, sideFaces, params );
2131
2132
2133   SMESH_Block::init();
2134   myShapeIDMap.Clear();
2135   myShapeIndex2ColumnMap.clear();
2136   
2137   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
2138     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
2139     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
2140   };
2141
2142   myError = SMESH_ComputeError::New();
2143
2144   myNotQuadOnTop = thePrism.myNotQuadOnTop;
2145
2146   // Find columns of wall nodes and calculate edges' lengths
2147   // --------------------------------------------------------
2148
2149   myParam2ColumnMaps.clear();
2150   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
2151
2152   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
2153   vector< double >    edgeLength( nbEdges );
2154   multimap< double, int > len2edgeMap;
2155
2156   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
2157   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
2158   {
2159     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2160
2161     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2162     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2163     {
2164       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge( 0 );
2165       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2166         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2167                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2168     }
2169     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2170     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2171     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2172
2173     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
2174
2175     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
2176     {
2177       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
2178       if ( !smDS )
2179         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
2180                      << MeshDS()->ShapeToIndex( *edgeIt ));
2181       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE ));
2182     }
2183   }
2184   // Load columns of internal edges (forming holes)
2185   // and fill map ShapeIndex to TParam2ColumnMap for them
2186   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
2187   {
2188     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2189
2190     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2191     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2192     {
2193       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge( 0 );
2194       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2195         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2196                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2197     }
2198     // edge columns
2199     int id = MeshDS()->ShapeToIndex( *edgeIt );
2200     bool isForward = true; // meaningless for intenal wires
2201     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2202     // columns for vertices
2203     // 1
2204     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
2205     id = n0->getshapeId();
2206     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2207     // 2
2208     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
2209     id = n1->getshapeId();
2210     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2211
2212     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2213     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2214     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2215   }
2216
2217   // Create 4 wall faces of a block
2218   // -------------------------------
2219
2220   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
2221   {
2222     map< int, int > iE2nbSplit;
2223     if ( nbEdges != NB_WALL_FACES ) // define how to split
2224     {
2225       if ( len2edgeMap.size() != nbEdges )
2226         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
2227
2228       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
2229       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
2230
2231       double maxLen = maxLen_i->first;
2232       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
2233       switch ( nbEdges ) {
2234       case 1: // 0-th edge is split into 4 parts
2235         iE2nbSplit.insert( make_pair( 0, 4 )); break;
2236       case 2: // either the longest edge is split into 3 parts, or both edges into halves
2237         if ( maxLen / 3 > midLen / 2 ) {
2238           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
2239         }
2240         else {
2241           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
2242           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
2243         }
2244         break;
2245       case 3:
2246         // split longest into halves
2247         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
2248       }
2249     }
2250     // Create TSideFace's
2251     int iSide = 0;
2252     list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2253     for ( iE = 0; iE < nbEdges; ++iE, ++botE )
2254     {
2255       TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
2256       // split?
2257       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
2258       if ( i_nb != iE2nbSplit.end() ) {
2259         // split!
2260         int nbSplit = i_nb->second;
2261         vector< double > params;
2262         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
2263         const bool isForward =
2264           StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
2265                                                   myParam2ColumnMaps[iE],
2266                                                   *botE, SMESH_Block::ID_Fx0z );
2267         for ( int i = 0; i < nbSplit; ++i ) {
2268           double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
2269           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
2270           TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
2271                                            thePrism.myWallQuads[ iE ], *botE,
2272                                            &myParam2ColumnMaps[ iE ], f, l );
2273           mySide->SetComponent( iSide++, comp );
2274         }
2275       }
2276       else {
2277         TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
2278                                          thePrism.myWallQuads[ iE ], *botE,
2279                                          &myParam2ColumnMaps[ iE ]);
2280         mySide->SetComponent( iSide++, comp );
2281       }
2282     }
2283   }
2284   else { // **************************** Unite faces
2285
2286     // unite first faces
2287     int nbExraFaces = nbEdges - 3;
2288     int iSide = 0, iE;
2289     double u0 = 0, sumLen = 0;
2290     for ( iE = 0; iE < nbExraFaces; ++iE )
2291       sumLen += edgeLength[ iE ];
2292
2293     vector< TSideFace* >        components( nbExraFaces );
2294     vector< pair< double, double> > params( nbExraFaces );
2295     list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2296     for ( iE = 0; iE < nbExraFaces; ++iE, ++botE )
2297     {
2298       components[ iE ] = new TSideFace( *mesh, wallFaceIds[ iSide ],
2299                                         thePrism.myWallQuads[ iE ], *botE,
2300                                         &myParam2ColumnMaps[ iE ]);
2301       double u1 = u0 + edgeLength[ iE ] / sumLen;
2302       params[ iE ] = make_pair( u0 , u1 );
2303       u0 = u1;
2304     }
2305     mySide->SetComponent( iSide++, new TSideFace( *mesh, components, params ));
2306
2307     // fill the rest faces
2308     for ( ; iE < nbEdges; ++iE, ++botE )
2309     {
2310       TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
2311                                        thePrism.myWallQuads[ iE ], *botE,
2312                                        &myParam2ColumnMaps[ iE ]);
2313       mySide->SetComponent( iSide++, comp );
2314     }
2315   }
2316
2317
2318   // Fill geometry fields of SMESH_Block
2319   // ------------------------------------
2320
2321   vector< int > botEdgeIdVec;
2322   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
2323
2324   bool isForward[NB_WALL_FACES] = { true, true, true, true };
2325   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
2326   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
2327
2328   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
2329   {
2330     TSideFace * sideFace = mySide->GetComponent( iF );
2331     if ( !sideFace )
2332       RETURN_BAD_RESULT("NULL TSideFace");
2333     int fID = sideFace->FaceID(); // in-block ID
2334
2335     // fill myShapeIDMap
2336     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
2337          !sideFace->IsComplex())
2338       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
2339
2340     // side faces geometry
2341     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
2342     if ( !sideFace->GetPCurves( pcurves ))
2343       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
2344
2345     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
2346     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
2347
2348     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
2349     // edges 3D geometry
2350     vector< int > edgeIdVec;
2351     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
2352     for ( int isMax = 0; isMax < 2; ++isMax ) {
2353       {
2354         int eID = edgeIdVec[ isMax ];
2355         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
2356         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
2357         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
2358         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
2359       }
2360       {
2361         int eID = edgeIdVec[ isMax+2 ];
2362         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
2363         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
2364         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
2365         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
2366
2367         // corner points
2368         vector< int > vertexIdVec;
2369         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
2370         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
2371         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
2372       }
2373     }
2374     // pcurves on horizontal faces
2375     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
2376       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
2377         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
2378         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
2379         break;
2380       }
2381     }
2382     //sideFace->dumpNodes( 4 ); // debug
2383   }
2384   // horizontal faces geometry
2385   {
2386     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
2387     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
2388     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
2389   }
2390   {
2391     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
2392     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
2393     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
2394   }
2395
2396   // Fill map ShapeIndex to TParam2ColumnMap
2397   // ----------------------------------------
2398
2399   list< TSideFace* > fList;
2400   list< TSideFace* >::iterator fListIt;
2401   fList.push_back( mySide );
2402   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
2403   {
2404     int nb = (*fListIt)->NbComponents();
2405     for ( int i = 0; i < nb; ++i ) {
2406       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
2407         fList.push_back( comp );
2408     }
2409     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
2410       // columns for a base edge
2411       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
2412       bool isForward = (*fListIt)->IsForward();
2413       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
2414
2415       // columns for vertices
2416       const SMDS_MeshNode* n0 = cols->begin()->second.front();
2417       id = n0->getshapeId();
2418       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
2419
2420       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
2421       id = n1->getshapeId();
2422       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
2423     }
2424   }
2425
2426 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
2427 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
2428 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
2429 //   SHOWYXZ("IN TEST PARAM" , testPar);
2430 //   SHOWYXZ("OUT TEST CORD" , testCoord);
2431 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
2432 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
2433 //   SHOWYXZ("OUT TEST PARAM" , testPar);
2434
2435   return true;
2436 }
2437
2438 //================================================================================
2439 /*!
2440  * \brief Return pointer to column of nodes
2441  * \param node - bottom node from which the returned column goes up
2442  * \retval const TNodeColumn* - the found column
2443  */
2444 //================================================================================
2445
2446 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
2447 {
2448   int sID = node->getshapeId();
2449
2450   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
2451     myShapeIndex2ColumnMap.find( sID );
2452   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
2453     const TParam2ColumnMap* cols = col_frw->second.first;
2454     TParam2ColumnIt u_col = cols->begin();
2455     for ( ; u_col != cols->end(); ++u_col )
2456       if ( u_col->second[ 0 ] == node )
2457         return & u_col->second;
2458   }
2459   return 0;
2460 }
2461
2462 //=======================================================================
2463 //function : GetLayersTransformation
2464 //purpose  : Return transformations to get coordinates of nodes of each layer
2465 //           by nodes of the bottom. Layer is a set of nodes at a certain step
2466 //           from bottom to top.
2467 //=======================================================================
2468
2469 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
2470                                                       const Prism_3D::TPrismTopo& prism) const
2471 {
2472   const int zSize = VerticalSize();
2473   if ( zSize < 3 ) return true;
2474   trsf.resize( zSize - 2 );
2475
2476   // Select some node columns by which we will define coordinate system of layers
2477
2478   vector< const TNodeColumn* > columns;
2479   {
2480     bool isReverse;
2481     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
2482     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
2483     {
2484       if ( BRep_Tool::Degenerated( *edgeIt )) continue;
2485       const TParam2ColumnMap* u2colMap =
2486         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
2487       if ( !u2colMap ) return false;
2488       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
2489       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
2490       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
2491       const int nbCol = 5;
2492       for ( int i = 0; i < nbCol; ++i )
2493       {
2494         double u = f + i/double(nbCol) * ( l - f );
2495         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
2496         if ( columns.empty() || col != columns.back() )
2497           columns.push_back( col );
2498       }
2499     }
2500   }
2501
2502   // Find tolerance to check transformations
2503
2504   double tol2;
2505   {
2506     Bnd_B3d bndBox;
2507     for ( int i = 0; i < columns.size(); ++i )
2508       bndBox.Add( gpXYZ( columns[i]->front() ));
2509     tol2 = bndBox.SquareExtent() * 1e-5;
2510   }
2511
2512   // Compute transformations
2513
2514   int xCol = -1;
2515   gp_Trsf fromCsZ, toCs0;
2516   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
2517   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
2518   toCs0.SetTransformation( cs0 );
2519   for ( int z = 1; z < zSize-1; ++z )
2520   {
2521     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
2522     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
2523     fromCsZ.SetTransformation( csZ );
2524     fromCsZ.Invert();
2525     gp_Trsf& t = trsf[ z-1 ];
2526     t = fromCsZ * toCs0;
2527     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
2528
2529     // check a transformation
2530     for ( int i = 0; i < columns.size(); ++i )
2531     {
2532       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
2533       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
2534       t.Transforms( p0.ChangeCoord() );
2535       if ( p0.SquareDistance( pz ) > tol2 )
2536         return false;
2537     }
2538   }
2539   return true;
2540 }
2541
2542 //================================================================================
2543 /*!
2544  * \brief Check curve orientation of a bootom edge
2545   * \param meshDS - mesh DS
2546   * \param columnsMap - node columns map of side face
2547   * \param bottomEdge - the bootom edge
2548   * \param sideFaceID - side face in-block ID
2549   * \retval bool - true if orientation coinside with in-block forward orientation
2550  */
2551 //================================================================================
2552
2553 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
2554                                             const TParam2ColumnMap& columnsMap,
2555                                             const TopoDS_Edge &     bottomEdge,
2556                                             const int               sideFaceID)
2557 {
2558   bool isForward = false;
2559   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
2560   {
2561     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
2562   }
2563   else
2564   {
2565     const TNodeColumn&     firstCol = columnsMap.begin()->second;
2566     const SMDS_MeshNode* bottomNode = firstCol[0];
2567     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
2568     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
2569   }
2570   // on 2 of 4 sides first vertex is end
2571   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
2572     isForward = !isForward;
2573   return isForward;
2574 }
2575
2576 //================================================================================
2577 /*!
2578  * \brief Constructor
2579   * \param faceID - in-block ID
2580   * \param face - geom FACE
2581   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
2582   * \param columnsMap - map of node columns
2583   * \param first - first normalized param
2584   * \param last - last normalized param
2585  */
2586 //================================================================================
2587
2588 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_Mesh&                mesh,
2589                                               const int                  faceID,
2590                                               const Prism_3D::TQuadList& quadList,
2591                                               const TopoDS_Edge&         baseEdge,
2592                                               TParam2ColumnMap*          columnsMap,
2593                                               const double               first,
2594                                               const double               last):
2595   myID( faceID ),
2596   myParamToColumnMap( columnsMap ),
2597   myHelper( mesh )
2598 {
2599   myParams.resize( 1 );
2600   myParams[ 0 ] = make_pair( first, last );
2601   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
2602   myBaseEdge    = baseEdge;
2603   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper.GetMeshDS(),
2604                                                           *myParamToColumnMap,
2605                                                           myBaseEdge, myID );
2606   if ( quadList.size() > 1 ) // side is vertically composite
2607   {
2608     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
2609
2610     SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
2611
2612     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
2613     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
2614     for ( ; quad != quadList.end(); ++quad )
2615     {
2616       const TopoDS_Face& face = (*quad)->face;
2617       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
2618       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
2619       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
2620                                         PSurface( new BRepAdaptor_Surface( face ))));
2621     }
2622     for ( int i = 1; i <= subToFaces.Extent(); ++i )
2623     {
2624       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
2625       TopTools_ListOfShape& faces = subToFaces( i );
2626       int subID  = meshDS->ShapeToIndex( sub );
2627       int faceID = meshDS->ShapeToIndex( faces.First() );
2628       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
2629     }
2630   }
2631 }
2632
2633 //================================================================================
2634 /*!
2635  * \brief Constructor of a complex side face
2636  */
2637 //================================================================================
2638
2639 StdMeshers_PrismAsBlock::TSideFace::
2640 TSideFace(SMESH_Mesh&                             mesh,
2641           const vector< TSideFace* >&             components,
2642           const vector< pair< double, double> > & params)
2643   :myID( components[0] ? components[0]->myID : 0 ),
2644    myParamToColumnMap( 0 ),
2645    myParams( params ),
2646    myIsForward( true ),
2647    myComponents( components ),
2648    myHelper( mesh )
2649 {}
2650 //================================================================================
2651 /*!
2652  * \brief Copy constructor
2653   * \param other - other side
2654  */
2655 //================================================================================
2656
2657 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other ):
2658   myID               ( other.myID ),
2659   myParamToColumnMap ( other.myParamToColumnMap ),
2660   mySurface          ( other.mySurface ),
2661   myBaseEdge         ( other.myBaseEdge ),
2662   myShapeID2Surf     ( other.myShapeID2Surf ),
2663   myParams           ( other.myParams ),
2664   myIsForward        ( other.myIsForward ),
2665   myComponents       ( other.myComponents.size() ),
2666   myHelper           ( *other.myHelper.GetMesh() )
2667 {
2668   for (int i = 0 ; i < myComponents.size(); ++i )
2669     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
2670 }
2671
2672 //================================================================================
2673 /*!
2674  * \brief Deletes myComponents
2675  */
2676 //================================================================================
2677
2678 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
2679 {
2680   for (int i = 0 ; i < myComponents.size(); ++i )
2681     if ( myComponents[ i ] )
2682       delete myComponents[ i ];
2683 }
2684
2685 //================================================================================
2686 /*!
2687  * \brief Return geometry of the vertical curve
2688   * \param isMax - true means curve located closer to (1,1,1) block point
2689   * \retval Adaptor3d_Curve* - curve adaptor
2690  */
2691 //================================================================================
2692
2693 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
2694 {
2695   if ( !myComponents.empty() ) {
2696     if ( isMax )
2697       return myComponents.back()->VertiCurve(isMax);
2698     else
2699       return myComponents.front()->VertiCurve(isMax);
2700   }
2701   double f = myParams[0].first, l = myParams[0].second;
2702   if ( !myIsForward ) std::swap( f, l );
2703   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
2704 }
2705
2706 //================================================================================
2707 /*!
2708  * \brief Return geometry of the top or bottom curve
2709   * \param isTop - 
2710   * \retval Adaptor3d_Curve* - 
2711  */
2712 //================================================================================
2713
2714 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
2715 {
2716   return new THorizontalEdgeAdaptor( this, isTop );
2717 }
2718
2719 //================================================================================
2720 /*!
2721  * \brief Return pcurves
2722   * \param pcurv - array of 4 pcurves
2723   * \retval bool - is a success
2724  */
2725 //================================================================================
2726
2727 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
2728 {
2729   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
2730
2731   for ( int i = 0 ; i < 4 ; ++i ) {
2732     Handle(Geom2d_Line) line;
2733     switch ( iEdge[ i ] ) {
2734     case TOP_EDGE:
2735       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
2736     case BOTTOM_EDGE:
2737       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
2738     case V0_EDGE:
2739       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
2740     case V1_EDGE:
2741       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
2742     }
2743     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
2744   }
2745   return true;
2746 }
2747
2748 //================================================================================
2749 /*!
2750  * \brief Returns geometry of pcurve on a horizontal face
2751   * \param isTop - is top or bottom face
2752   * \param horFace - a horizontal face
2753   * \retval Adaptor2d_Curve2d* - curve adaptor
2754  */
2755 //================================================================================
2756
2757 Adaptor2d_Curve2d*
2758 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
2759                                                 const TopoDS_Face& horFace) const
2760 {
2761   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
2762 }
2763
2764 //================================================================================
2765 /*!
2766  * \brief Return a component corresponding to parameter
2767   * \param U - parameter along a horizontal size
2768   * \param localU - parameter along a horizontal size of a component
2769   * \retval TSideFace* - found component
2770  */
2771 //================================================================================
2772
2773 StdMeshers_PrismAsBlock::TSideFace*
2774 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
2775 {
2776   localU = U;
2777   if ( myComponents.empty() )
2778     return const_cast<TSideFace*>( this );
2779
2780   int i;
2781   for ( i = 0; i < myComponents.size(); ++i )
2782     if ( U < myParams[ i ].second )
2783       break;
2784   if ( i >= myComponents.size() )
2785     i = myComponents.size() - 1;
2786
2787   double f = myParams[ i ].first, l = myParams[ i ].second;
2788   localU = ( U - f ) / ( l - f );
2789   return myComponents[ i ];
2790 }
2791
2792 //================================================================================
2793 /*!
2794  * \brief Find node columns for a parameter
2795   * \param U - parameter along a horizontal edge
2796   * \param col1 - the 1st found column
2797   * \param col2 - the 2nd found column
2798   * \retval r - normalized position of U between the found columns
2799  */
2800 //================================================================================
2801
2802 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
2803                                                       TParam2ColumnIt & col1,
2804                                                       TParam2ColumnIt & col2) const
2805 {
2806   double u = U, r = 0;
2807   if ( !myComponents.empty() ) {
2808     TSideFace * comp = GetComponent(U,u);
2809     return comp->GetColumns( u, col1, col2 );
2810   }
2811
2812   if ( !myIsForward )
2813     u = 1 - u;
2814   double f = myParams[0].first, l = myParams[0].second;
2815   u = f + u * ( l - f );
2816
2817   col1 = col2 = getColumn( myParamToColumnMap, u );
2818   if ( ++col2 == myParamToColumnMap->end() ) {
2819     --col2;
2820     r = 0.5;
2821   }
2822   else {
2823     double uf = col1->first;
2824     double ul = col2->first;
2825     r = ( u - uf ) / ( ul - uf );
2826   }
2827   return r;
2828 }
2829
2830 //================================================================================
2831 /*!
2832  * \brief Return coordinates by normalized params
2833   * \param U - horizontal param
2834   * \param V - vertical param
2835   * \retval gp_Pnt - result point
2836  */
2837 //================================================================================
2838
2839 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
2840                                                  const Standard_Real V) const
2841 {
2842   if ( !myComponents.empty() ) {
2843     double u;
2844     TSideFace * comp = GetComponent(U,u);
2845     return comp->Value( u, V );
2846   }
2847
2848   TParam2ColumnIt u_col1, u_col2;
2849   double vR, hR = GetColumns( U, u_col1, u_col2 );
2850
2851   const SMDS_MeshNode* nn[4];
2852
2853   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
2854   // Workaround for a wrongly located point returned by mySurface.Value() for
2855   // UV located near boundary of BSpline surface.
2856   // To bypass the problem, we take point from 3D curve of EDGE.
2857   // It solves pb of the bloc_fiss_new.py
2858   const double tol = 1e-3;
2859   if ( V < tol || V+tol >= 1. )
2860   {
2861     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
2862     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
2863     TopoDS_Edge edge;
2864     if ( V < tol )
2865     {
2866       edge = myBaseEdge;
2867     }
2868     else
2869     {
2870       TopoDS_Shape s = myHelper.GetSubShapeByNode( nn[0], myHelper.GetMeshDS() );
2871       if ( s.ShapeType() != TopAbs_EDGE )
2872         s = myHelper.GetSubShapeByNode( nn[2], myHelper.GetMeshDS() );
2873       if ( s.ShapeType() == TopAbs_EDGE )
2874         edge = TopoDS::Edge( s );
2875     }
2876     if ( !edge.IsNull() )
2877     {
2878       double u1 = myHelper.GetNodeU( edge, nn[0] );
2879       double u3 = myHelper.GetNodeU( edge, nn[2] );
2880       double u = u1 * ( 1 - hR ) + u3 * hR;
2881       TopLoc_Location loc; double f,l;
2882       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
2883       return curve->Value( u ).Transformed( loc );
2884     }
2885   }
2886   // END issue 0020680: Bad cell created by Radial prism in center of torus
2887
2888   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
2889   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
2890
2891   if ( !myShapeID2Surf.empty() ) // side is vertically composite
2892   {
2893     // find a FACE on which the 4 nodes lie
2894     TSideFace* me = (TSideFace*) this;
2895     int notFaceID1 = 0, notFaceID2 = 0;
2896     for ( int i = 0; i < 4; ++i )
2897       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
2898       {
2899         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
2900         notFaceID2 = 0;
2901         break;
2902       }
2903       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
2904       {
2905         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
2906         notFaceID1 = nn[i]->getshapeId();
2907       }
2908       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
2909       {
2910         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
2911           notFaceID2 = nn[i]->getshapeId();
2912       }
2913     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
2914     {
2915       SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
2916       TopoDS_Shape face = myHelper.GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
2917                                                        meshDS->IndexToShape( notFaceID2 ),
2918                                                        *myHelper.GetMesh(),
2919                                                        TopAbs_FACE );
2920       if ( face.IsNull() ) 
2921         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
2922       int faceID = meshDS->ShapeToIndex( face );
2923       me->mySurface = me->myShapeID2Surf[ faceID ];
2924       if ( !mySurface )
2925         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
2926     }
2927   }
2928   
2929   gp_XY uv1 = myHelper.GetNodeUV( mySurface->Face(), nn[0], nn[2]);
2930   gp_XY uv2 = myHelper.GetNodeUV( mySurface->Face(), nn[1], nn[3]);
2931   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
2932
2933   gp_XY uv3 = myHelper.GetNodeUV( mySurface->Face(), nn[2], nn[0]);
2934   gp_XY uv4 = myHelper.GetNodeUV( mySurface->Face(), nn[3], nn[1]);
2935   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
2936
2937   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
2938
2939   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
2940   return p;
2941 }
2942
2943
2944 //================================================================================
2945 /*!
2946  * \brief Return boundary edge
2947   * \param edge - edge index
2948   * \retval TopoDS_Edge - found edge
2949  */
2950 //================================================================================
2951
2952 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
2953 {
2954   if ( !myComponents.empty() ) {
2955     switch ( iEdge ) {
2956     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
2957     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
2958     default: return TopoDS_Edge();
2959     }
2960   }
2961   TopoDS_Shape edge;
2962   const SMDS_MeshNode* node = 0;
2963   SMESHDS_Mesh * meshDS = myHelper.GetMesh()->GetMeshDS();
2964   TNodeColumn* column;
2965
2966   switch ( iEdge ) {
2967   case TOP_EDGE:
2968   case BOTTOM_EDGE:
2969     column = & (( ++myParamToColumnMap->begin())->second );
2970     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2971     edge = myHelper.GetSubShapeByNode ( node, meshDS );
2972     if ( edge.ShapeType() == TopAbs_VERTEX ) {
2973       column = & ( myParamToColumnMap->begin()->second );
2974       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2975     }
2976     break;
2977   case V0_EDGE:
2978   case V1_EDGE: {
2979     bool back = ( iEdge == V1_EDGE );
2980     if ( !myIsForward ) back = !back;
2981     if ( back )
2982       column = & ( myParamToColumnMap->rbegin()->second );
2983     else
2984       column = & ( myParamToColumnMap->begin()->second );
2985     if ( column->size() > 0 )
2986       edge = myHelper.GetSubShapeByNode( (*column)[ 1 ], meshDS );
2987     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
2988       node = column->front();
2989     break;
2990   }
2991   default:;
2992   }
2993   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
2994     return TopoDS::Edge( edge );
2995
2996   // find edge by 2 vertices
2997   TopoDS_Shape V1 = edge;
2998   TopoDS_Shape V2 = myHelper.GetSubShapeByNode( node, meshDS );
2999   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
3000   {
3001     TopoDS_Shape ancestor = myHelper.GetCommonAncestor( V1, V2, *myHelper.GetMesh(), TopAbs_EDGE);
3002     if ( !ancestor.IsNull() )
3003       return TopoDS::Edge( ancestor );
3004   }
3005   return TopoDS_Edge();
3006 }
3007
3008 //================================================================================
3009 /*!
3010  * \brief Fill block sub-shapes
3011   * \param shapeMap - map to fill in
3012   * \retval int - nb inserted sub-shapes
3013  */
3014 //================================================================================
3015
3016 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
3017 {
3018   int nbInserted = 0;
3019
3020   // Insert edges
3021   vector< int > edgeIdVec;
3022   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
3023
3024   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
3025     TopoDS_Edge e = GetEdge( i );
3026     if ( !e.IsNull() ) {
3027       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
3028     }
3029   }
3030
3031   // Insert corner vertices
3032
3033   TParam2ColumnIt col1, col2 ;
3034   vector< int > vertIdVec;
3035
3036   // from V0 column
3037   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
3038   GetColumns(0, col1, col2 );
3039   const SMDS_MeshNode* node0 = col1->second.front();
3040   const SMDS_MeshNode* node1 = col1->second.back();
3041   TopoDS_Shape v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
3042   TopoDS_Shape v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
3043   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3044     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3045   }
3046   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3047     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3048   }
3049   
3050   // from V1 column
3051   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
3052   GetColumns(1, col1, col2 );
3053   node0 = col2->second.front();
3054   node1 = col2->second.back();
3055   v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
3056   v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
3057   if ( v0.ShapeType() == TopAbs_VERTEX ) {
3058     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
3059   }
3060   if ( v1.ShapeType() == TopAbs_VERTEX ) {
3061     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
3062   }
3063
3064 //   TopoDS_Vertex V0, V1, Vcom;
3065 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
3066 //   if ( !myIsForward ) std::swap( V0, V1 );
3067
3068 //   // bottom vertex IDs
3069 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
3070 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
3071 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
3072
3073 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
3074 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
3075 //     return false;
3076
3077 //   // insert one side edge
3078 //   int edgeID;
3079 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
3080 //   else                    edgeID = edgeIdVec[ _v1 ];
3081 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3082
3083 //   // top vertex of the side edge
3084 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
3085 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
3086 //   if ( Vcom.IsSame( Vtop ))
3087 //     Vtop = TopExp::LastVertex( sideEdge );
3088 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
3089
3090 //   // other side edge
3091 //   sideEdge = GetEdge( V1_EDGE );
3092 //   if ( sideEdge.IsNull() )
3093 //     return false;
3094 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
3095 //   else                            edgeID = edgeIdVec[ _v1 ];
3096 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
3097   
3098 //   // top edge
3099 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
3100 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
3101
3102 //   // top vertex of the other side edge
3103 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
3104 //     return false;
3105 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
3106 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
3107
3108   return nbInserted;
3109 }
3110
3111 //================================================================================
3112 /*!
3113  * \brief Dump ids of nodes of sides
3114  */
3115 //================================================================================
3116
3117 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
3118 {
3119 #ifdef _DEBUG_
3120   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
3121   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
3122   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
3123   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
3124   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
3125   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
3126   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
3127   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
3128   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
3129   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
3130 #endif
3131 }
3132
3133 //================================================================================
3134 /*!
3135  * \brief Creates TVerticalEdgeAdaptor 
3136   * \param columnsMap - node column map
3137   * \param parameter - normalized parameter
3138  */
3139 //================================================================================
3140
3141 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
3142 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
3143 {
3144   myNodeColumn = & getColumn( columnsMap, parameter )->second;
3145 }
3146
3147 //================================================================================
3148 /*!
3149  * \brief Return coordinates for the given normalized parameter
3150   * \param U - normalized parameter
3151   * \retval gp_Pnt - coordinates
3152  */
3153 //================================================================================
3154
3155 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
3156 {
3157   const SMDS_MeshNode* n1;
3158   const SMDS_MeshNode* n2;
3159   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
3160   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
3161 }
3162
3163 //================================================================================
3164 /*!
3165  * \brief Dump ids of nodes
3166  */
3167 //================================================================================
3168
3169 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
3170 {
3171 #ifdef _DEBUG_
3172   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
3173     cout << (*myNodeColumn)[i]->GetID() << " ";
3174   if ( nbNodes < myNodeColumn->size() )
3175     cout << myNodeColumn->back()->GetID();
3176 #endif
3177 }
3178
3179 //================================================================================
3180 /*!
3181  * \brief Return coordinates for the given normalized parameter
3182   * \param U - normalized parameter
3183   * \retval gp_Pnt - coordinates
3184  */
3185 //================================================================================
3186
3187 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
3188 {
3189   return mySide->TSideFace::Value( U, myV );
3190 }
3191
3192 //================================================================================
3193 /*!
3194  * \brief Dump ids of <nbNodes> first nodes and the last one
3195  */
3196 //================================================================================
3197
3198 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
3199 {
3200 #ifdef _DEBUG_
3201   // Not bedugged code. Last node is sometimes incorrect
3202   const TSideFace* side = mySide;
3203   double u = 0;
3204   if ( mySide->IsComplex() )
3205     side = mySide->GetComponent(0,u);
3206
3207   TParam2ColumnIt col, col2;
3208   TParam2ColumnMap* u2cols = side->GetColumns();
3209   side->GetColumns( u , col, col2 );
3210   
3211   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
3212
3213   const SMDS_MeshNode* n = 0;
3214   const SMDS_MeshNode* lastN
3215     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
3216   for ( j = 0; j < nbNodes && n != lastN; ++j )
3217   {
3218     n = col->second[ i ];
3219     cout << n->GetID() << " ";
3220     if ( side->IsForward() )
3221       ++col;
3222     else
3223       --col;
3224   }
3225
3226   // last node
3227   u = 1;
3228   if ( mySide->IsComplex() )
3229     side = mySide->GetComponent(1,u);
3230
3231   side->GetColumns( u , col, col2 );
3232   if ( n != col->second[ i ] )
3233     cout << col->second[ i ]->GetID();
3234 #endif
3235 }
3236 //================================================================================
3237 /*!
3238  * \brief Return UV on pcurve for the given normalized parameter
3239   * \param U - normalized parameter
3240   * \retval gp_Pnt - coordinates
3241  */
3242 //================================================================================
3243
3244 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
3245 {
3246   TParam2ColumnIt u_col1, u_col2;
3247   double r = mySide->GetColumns( U, u_col1, u_col2 );
3248   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ], u_col2->second[ myZ ]);
3249   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ], u_col1->second[ myZ ]);
3250   return uv1 * ( 1 - r ) + uv2 * r;
3251 }