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