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