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