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