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