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