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