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