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