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