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