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