Salome HOME
Merge branch 'V8_5_asterstudy'
[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   // If all "vertical" EDGEs are straight, then all nodes of an internal node column
1174   // are located on a line connecting the top node and the bottom node.
1175   bool isStrightColunm = allVerticalEdgesStraight( thePrism );
1176   if ( isStrightColunm )
1177     myUseBlock = false;
1178
1179   // Create nodes inside the block
1180
1181   if ( !myUseBlock )
1182   {
1183     // use transformation (issue 0020680, IPAL0052499) or a "straight line" approach
1184     StdMeshers_Sweeper sweeper;
1185     sweeper.myHelper  = myHelper;
1186     sweeper.myBotFace = thePrism.myBottom;
1187     sweeper.myTopFace = thePrism.myTop;
1188
1189     // load boundary nodes into sweeper
1190     bool dummy;
1191     std::set< const SMDS_MeshNode* > usedEndNodes;
1192     list< TopoDS_Edge >::const_iterator edge = thePrism.myBottomEdges.begin();
1193     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
1194     {
1195       int edgeID = meshDS->ShapeToIndex( *edge );
1196       TParam2ColumnMap* u2col = const_cast<TParam2ColumnMap*>
1197         ( myBlock.GetParam2ColumnMap( edgeID, dummy ));
1198
1199       TParam2ColumnMap::iterator u2colIt = u2col->begin(), u2colEnd = u2col->end();
1200       const SMDS_MeshNode* n0 = u2colIt->second[0];
1201       const SMDS_MeshNode* n1 = u2col->rbegin()->second[0];
1202       if ( !usedEndNodes.insert ( n0 ).second ) ++u2colIt;
1203       if ( !usedEndNodes.insert ( n1 ).second ) --u2colEnd;
1204
1205       for ( ; u2colIt != u2colEnd; ++u2colIt )
1206         sweeper.myBndColumns.push_back( & u2colIt->second );
1207     }
1208     // load node columns inside the bottom FACE
1209     sweeper.myIntColumns.reserve( myBotToColumnMap.size() );
1210     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1211     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1212       sweeper.myIntColumns.push_back( & bot_column->second );
1213
1214     myHelper->SetElementsOnShape( true );
1215
1216     if ( !isStrightColunm )
1217     {
1218       double tol = getSweepTolerance( thePrism );
1219       bool allowHighBndError = !isSimpleBottom( thePrism );
1220       myUseBlock = !sweeper.ComputeNodesByTrsf( tol, allowHighBndError );
1221     }
1222     else if ( sweeper.CheckSameZ() )
1223     {
1224       myUseBlock = !sweeper.ComputeNodesOnStraightSameZ();
1225     }
1226     else
1227     {
1228       myUseBlock = !sweeper.ComputeNodesOnStraight();
1229     }
1230     myHelper->SetElementsOnShape( false );
1231   }
1232
1233   if ( myUseBlock ) // use block approach
1234   {
1235     // loop on nodes inside the bottom face
1236     Prism_3D::TNode prevBNode;
1237     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
1238     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
1239     {
1240       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
1241       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE &&
1242            myBlock.HasNodeColumn( tBotNode.myNode ))
1243         continue; // node is not inside the FACE
1244
1245       // column nodes; middle part of the column are zero pointers
1246       TNodeColumn& column = bot_column->second;
1247
1248       // check if a column is already computed using non-block approach
1249       size_t i;
1250       for ( i = 0; i < column.size(); ++i )
1251         if ( !column[ i ])
1252           break;
1253       if ( i == column.size() )
1254         continue; // all nodes created
1255
1256       gp_XYZ botParams, topParams;
1257       if ( !tBotNode.HasParams() )
1258       {
1259         // compute bottom node parameters
1260         gp_XYZ paramHint(-1,-1,-1);
1261         if ( prevBNode.IsNeighbor( tBotNode ))
1262           paramHint = prevBNode.GetParams();
1263         if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
1264                                          ID_BOT_FACE, paramHint ))
1265           return toSM( error(TCom("Can't compute normalized parameters for node ")
1266                              << tBotNode.myNode->GetID() << " on the face #"
1267                              << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
1268         prevBNode = tBotNode;
1269
1270         botParams = topParams = tBotNode.GetParams();
1271         topParams.SetZ( 1 );
1272
1273         // compute top node parameters
1274         if ( column.size() > 2 ) {
1275           gp_Pnt topCoords = gpXYZ( column.back() );
1276           if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
1277             return toSM( error(TCom("Can't compute normalized parameters ")
1278                                << "for node " << column.back()->GetID()
1279                                << " on the face #"<< column.back()->getshapeId() ));
1280         }
1281       }
1282       else // top nodes are created by projection using parameters
1283       {
1284         botParams = topParams = tBotNode.GetParams();
1285         topParams.SetZ( 1 );
1286       }
1287
1288       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
1289       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
1290
1291       // vertical loop
1292       TNodeColumn::iterator columnNodes = column.begin();
1293       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
1294       {
1295         const SMDS_MeshNode* & node = *columnNodes;
1296         if ( node ) continue; // skip bottom or top node
1297
1298         // params of a node to create
1299         double rz = (double) z / (double) ( column.size() - 1 );
1300         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
1301
1302         // set coords on all faces and nodes
1303         const int nbSideFaces = 4;
1304         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
1305                                          SMESH_Block::ID_Fx1z,
1306                                          SMESH_Block::ID_F0yz,
1307                                          SMESH_Block::ID_F1yz };
1308         for ( int iF = 0; iF < nbSideFaces; ++iF )
1309           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
1310             return false;
1311
1312         // compute coords for a new node
1313         gp_XYZ coords;
1314         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
1315           return toSM( error("Can't compute coordinates by normalized parameters"));
1316
1317         // if ( !meshDS->MeshElements( volumeID ) ||
1318         //      meshDS->MeshElements( volumeID )->NbNodes() == 0 )
1319         //   pointsToPython(myShapeXYZ);
1320         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
1321         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
1322         SHOWYXZ("ShellPoint ",coords);
1323
1324         // create a node
1325         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
1326         meshDS->SetNodeInVolume( node, volumeID );
1327
1328         if ( _computeCanceled )
1329           return false;
1330       }
1331     } // loop on bottom nodes
1332   }
1333
1334   // Create volumes
1335
1336   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
1337   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
1338
1339   // loop on bottom mesh faces
1340   vector< const TNodeColumn* > columns;
1341   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1342   while ( faceIt->more() )
1343   {
1344     const SMDS_MeshElement* face = faceIt->next();
1345     if ( !face || face->GetType() != SMDSAbs_Face )
1346       continue;
1347
1348     // find node columns for each node
1349     int nbNodes = face->NbCornerNodes();
1350     columns.resize( nbNodes );
1351     for ( int i = 0; i < nbNodes; ++i )
1352     {
1353       const SMDS_MeshNode* n = face->GetNode( i );
1354       columns[ i ] = NULL;
1355
1356       if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1357         columns[ i ] = myBlock.GetNodeColumn( n );
1358
1359       if ( !columns[ i ] )
1360       {
1361         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1362         if ( bot_column == myBotToColumnMap.end() )
1363           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1364         columns[ i ] = & bot_column->second;
1365       }
1366     }
1367     // create prisms
1368     if ( !AddPrisms( columns, myHelper ))
1369       return toSM( error("Different 'vertical' discretization"));
1370
1371   } // loop on bottom mesh faces
1372
1373   // clear data
1374   myBotToColumnMap.clear();
1375   myBlock.Clear();
1376
1377   // update state of sub-meshes (mostly in order to erase improper errors)
1378   SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( thePrism.myShape3D );
1379   SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1380   while ( smIt->more() )
1381   {
1382     sm = smIt->next();
1383     sm->GetComputeError().reset();
1384     sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1385   }
1386
1387   return true;
1388 }
1389
1390 //=======================================================================
1391 //function : computeBase
1392 //purpose  : Compute the base face of a prism
1393 //=======================================================================
1394
1395 bool StdMeshers_Prism_3D::computeBase(const Prism_3D::TPrismTopo& thePrism)
1396 {
1397   SMESH_Mesh*     mesh = myHelper->GetMesh();
1398   SMESH_subMesh* botSM = mesh->GetSubMesh( thePrism.myBottom );
1399   if (( botSM->IsEmpty() ) &&
1400       ( ! botSM->GetAlgo() ||
1401         ! _gen->Compute( *botSM->GetFather(), botSM->GetSubShape(), /*shapeOnly=*/true )))
1402   {
1403     // find any applicable algorithm assigned to any FACE of the main shape
1404     std::vector< TopoDS_Shape > faces;
1405     if ( myPrevBottomSM &&
1406          myPrevBottomSM->GetAlgo()->IsApplicableToShape( thePrism.myBottom, /*all=*/false ))
1407       faces.push_back( myPrevBottomSM->GetSubShape() );
1408
1409     TopExp_Explorer faceIt( mesh->GetShapeToMesh(), TopAbs_FACE );
1410     for ( ; faceIt.More(); faceIt.Next() )
1411       faces.push_back( faceIt.Current() );
1412
1413     faces.push_back( TopoDS_Shape() ); // to try quadrangle algorithm
1414
1415     SMESH_Algo* algo = 0;
1416     for ( size_t i = 0; i < faces.size() &&  botSM->IsEmpty(); ++i )
1417     {
1418       if ( faces[i].IsNull() ) algo = TQuadrangleAlgo::instance( this, myHelper );
1419       else                     algo = mesh->GetSubMesh( faces[i] )->GetAlgo();
1420       if ( algo && algo->IsApplicableToShape( thePrism.myBottom, /*all=*/false ))
1421       {
1422         // try to compute the bottom FACE
1423         if ( algo->NeedDiscreteBoundary() )
1424         {
1425           // compute sub-shapes
1426           SMESH_subMeshIteratorPtr smIt = botSM->getDependsOnIterator(false,false);
1427           bool subOK = true;
1428           while ( smIt->more() && subOK )
1429           {
1430             SMESH_subMesh* sub = smIt->next();
1431             sub->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1432             subOK = sub->IsMeshComputed();
1433           }
1434           if ( !subOK )
1435             continue;
1436         }
1437         try {
1438           OCC_CATCH_SIGNALS;
1439           algo->InitComputeError();
1440           algo->Compute( *mesh, botSM->GetSubShape() );
1441         }
1442         catch (...) {
1443         }
1444       }
1445     }
1446   }
1447
1448   if ( botSM->IsEmpty() )
1449     return error( COMPERR_BAD_INPUT_MESH,
1450                   TCom( "No mesher defined to compute the base face #")
1451                   << shapeID( thePrism.myBottom ));
1452
1453   if ( botSM->GetAlgo() )
1454     myPrevBottomSM = botSM;
1455
1456   return true;
1457 }
1458
1459 //=======================================================================
1460 //function : computeWalls
1461 //purpose  : Compute 2D mesh on walls FACEs of a prism
1462 //=======================================================================
1463
1464 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
1465 {
1466   SMESH_Mesh*     mesh = myHelper->GetMesh();
1467   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
1468   DBGOUT( endl << "COMPUTE Prism " << meshDS->ShapeToIndex( thePrism.myShape3D ));
1469
1470   TProjction1dAlgo*      projector1D = TProjction1dAlgo::instance( this );
1471   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, myHelper );
1472
1473   // SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
1474   // hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
1475   // hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
1476
1477   // Discretize equally 'vertical' EDGEs
1478   // -----------------------------------
1479   // find source FACE sides for projection: either already computed ones or
1480   // the 'most composite' ones
1481   const size_t nbWalls = thePrism.myWallQuads.size();
1482   vector< int > wgt( nbWalls, 0 ); // "weight" of a wall
1483   for ( size_t iW = 0; iW != nbWalls; ++iW )
1484   {
1485     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1486     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1487     {
1488       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1489       lftSide->Reverse(); // to go up
1490       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1491       {
1492         ++wgt[ iW ];
1493         const TopoDS_Edge& E = lftSide->Edge(i);
1494         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
1495         {
1496           wgt[ iW ] += 100;
1497           wgt[ myHelper->WrapIndex( iW+1, nbWalls)] += 10;
1498           wgt[ myHelper->WrapIndex( iW-1, nbWalls)] += 10;
1499         }
1500         // else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
1501         //   wgt += 100;
1502       }
1503     }
1504     // in quadratic mesh, pass ignoreMediumNodes to quad sides
1505     if ( myHelper->GetIsQuadratic() )
1506     {
1507       quad = thePrism.myWallQuads[iW].begin();
1508       for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1509         for ( int i = 0; i < NB_QUAD_SIDES; ++i )
1510           (*quad)->side[ i ].grid->SetIgnoreMediumNodes( true );
1511     }
1512   }
1513   multimap< int, int > wgt2quad;
1514   for ( size_t iW = 0; iW != nbWalls; ++iW )
1515     wgt2quad.insert( make_pair( wgt[ iW ], iW ));
1516
1517   // artificial quads to do outer <-> inner wall projection
1518   std::map< int, FaceQuadStruct > iW2oiQuads;
1519   std::map< int, FaceQuadStruct >::iterator w2oiq;
1520   makeQuadsForOutInProjection( thePrism, wgt2quad, iW2oiQuads );
1521
1522   // Project 'vertical' EDGEs, from left to right
1523   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1524   for ( ; w2q != wgt2quad.rend(); ++w2q )
1525   {
1526     const int iW = w2q->second;
1527     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1528     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1529     for ( ; quad != quads.end(); ++quad )
1530     {
1531       StdMeshers_FaceSidePtr rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1532       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1533       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1534                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1535       if ( swapLeftRight )
1536         std::swap( lftSide, rgtSide );
1537
1538       bool isArtificialQuad = (( w2oiq = iW2oiQuads.find( iW )) != iW2oiQuads.end() );
1539       if ( isArtificialQuad )
1540       {
1541         // reset sides to perform the outer <-> inner projection
1542         FaceQuadStruct& oiQuad = w2oiq->second;
1543         rgtSide = oiQuad.side[ QUAD_RIGHT_SIDE ];
1544         lftSide = oiQuad.side[ QUAD_LEFT_SIDE ];
1545         iW2oiQuads.erase( w2oiq );
1546       }
1547
1548       // assure that all the source (left) EDGEs are meshed
1549       int nbSrcSegments = 0;
1550       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1551       {
1552         if ( isArtificialQuad )
1553         {
1554           nbSrcSegments = lftSide->NbPoints()-1;
1555           continue;
1556         }
1557         const TopoDS_Edge& srcE = lftSide->Edge(i);
1558         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1559         if ( !srcSM->IsMeshComputed() ) {
1560           DBGOUT( "COMPUTE V edge " << srcSM->GetId() );
1561           TopoDS_Edge prpgSrcE = findPropagationSource( srcE );
1562           if ( !prpgSrcE.IsNull() ) {
1563             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1564             projector1D->myHyp.SetSourceEdge( prpgSrcE );
1565             projector1D->Compute( *mesh, srcE );
1566             srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1567           }
1568           else {
1569             srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1570             srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1571           }
1572           if ( !srcSM->IsMeshComputed() )
1573             return toSM( error( "Can't compute 1D mesh" ));
1574         }
1575         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1576       }
1577       // check target EDGEs
1578       int nbTgtMeshed = 0, nbTgtSegments = 0;
1579       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1580       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1581       {
1582         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1583         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1584         if ( !( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1585           tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1586           tgtSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1587         }
1588         if ( tgtSM->IsMeshComputed() ) {
1589           ++nbTgtMeshed;
1590           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1591         }
1592       }
1593       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1594       {
1595         if ( nbTgtSegments != nbSrcSegments )
1596         {
1597           bool badMeshRemoved = false;
1598           // remove just computed segments
1599           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1600             if ( !isTgtEdgeComputed[ i ])
1601             {
1602               const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1603               SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1604               tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1605               badMeshRemoved = true;
1606               nbTgtMeshed--;
1607             }
1608           if ( !badMeshRemoved )
1609           {
1610             for ( int i = 0; i < lftSide->NbEdges(); ++i )
1611               addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1612             for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1613               addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1614             return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1615                                 << shapeID( lftSide->Edge(0) ) << " and #"
1616                                 << shapeID( rgtSide->Edge(0) ) << ": "
1617                                 << nbSrcSegments << " != " << nbTgtSegments ));
1618           }
1619         }
1620         else // if ( nbTgtSegments == nbSrcSegments )
1621         {
1622           continue;
1623         }
1624       }
1625       // Compute 'vertical projection'
1626       if ( nbTgtMeshed == 0 )
1627       {
1628         // compute nodes on target VERTEXes
1629         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1630         if ( srcNodeStr.size() == 0 )
1631           return toSM( error( TCom("Invalid node positions on edge #") <<
1632                               lftSide->EdgeID(0) ));
1633         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1634         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1635         {
1636           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1637           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1638           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1639           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1640           newNodes[ is2ndV ? newNodes.size()-1 : 0 ] = (SMDS_MeshNode*) n;
1641         }
1642
1643         // compute nodes on target EDGEs
1644         DBGOUT( "COMPUTE V edge (proj) " << shapeID( lftSide->Edge(0)));
1645         //rgtSide->Reverse(); // direct it same as the lftSide
1646         myHelper->SetElementsOnShape( false ); // myHelper holds the prism shape
1647         TopoDS_Edge tgtEdge;
1648         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1649         {
1650           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1651           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1652           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1653           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1654         }
1655         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1656         {
1657           // find an EDGE to set a new segment
1658           std::pair<int, TopAbs_ShapeEnum> id2type = 
1659             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1660           if ( id2type.second != TopAbs_EDGE )
1661           {
1662             // new nodes are on different EDGEs; put one of them on VERTEX
1663             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1664             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1665             TopoDS_Vertex     vertex = rgtSide->LastVertex( edgeIndex );
1666             const SMDS_MeshNode*  vn = SMESH_Algo::VertexNode( vertex, meshDS );
1667             const gp_Pnt           p = BRep_Tool::Pnt( vertex );
1668             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1669                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1670             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1671             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], vertex );
1672             meshDS->MoveNode        ( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1673             id2type.first = newNodes[ iN-(1-isPrev) ]->getshapeId();
1674             if ( vn )
1675             {
1676               SMESH_MeshEditor::TListOfListOfNodes lln( 1, list< const SMDS_MeshNode* >() );
1677               lln.back().push_back ( vn );
1678               lln.back().push_front( newNodes[ iN-isPrev ] ); // to keep 
1679               SMESH_MeshEditor( mesh ).MergeNodes( lln );
1680             }
1681           }
1682           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1683           meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1684         }
1685         myHelper->SetElementsOnShape( true );
1686         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1687         {
1688           const TopoDS_Edge& E = rgtSide->Edge( i );
1689           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1690           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1691         }
1692
1693         // to continue projection from the just computed side as a source
1694         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1695         {
1696           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1697           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1698           wgt2quad.insert( wgt2quadKeyVal );
1699           w2q = wgt2quad.rbegin();
1700         }
1701       }
1702       else
1703       {
1704         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1705         //return toSM( error("Partial projection not implemented"));
1706       }
1707     } // loop on quads of a composite wall side
1708   } // loop on the ordered wall sides
1709
1710
1711
1712   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1713   {
1714     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1715     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1716     {
1717       const TopoDS_Face& face = (*quad)->face;
1718       SMESH_subMesh*      fSM = mesh->GetSubMesh( face );
1719       if ( ! fSM->IsMeshComputed() )
1720       {
1721         // Top EDGEs must be projections from the bottom ones
1722         // to compute structured quad mesh on wall FACEs
1723         // ---------------------------------------------------
1724         const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0);
1725         const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ].grid->Edge(0);
1726         SMESH_subMesh*    botSM = mesh->GetSubMesh( botE );
1727         SMESH_subMesh*    topSM = mesh->GetSubMesh( topE );
1728         SMESH_subMesh*    srcSM = botSM;
1729         SMESH_subMesh*    tgtSM = topSM;
1730         srcSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1731         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1732         if ( !srcSM->IsMeshComputed() && tgtSM->IsMeshComputed() )
1733           std::swap( srcSM, tgtSM );
1734
1735         if ( !srcSM->IsMeshComputed() )
1736         {
1737           DBGOUT( "COMPUTE H edge " << srcSM->GetId());
1738           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE ); // nodes on VERTEXes
1739           srcSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );        // segments on the EDGE
1740         }
1741
1742         if ( tgtSM->IsMeshComputed() &&
1743              tgtSM->GetSubMeshDS()->NbNodes() != srcSM->GetSubMeshDS()->NbNodes() )
1744         {
1745           // the top EDGE is computed differently than the bottom one,
1746           // try to clear a wrong mesh
1747           bool isAdjFaceMeshed = false;
1748           PShapeIteratorPtr fIt = myHelper->GetAncestors( tgtSM->GetSubShape(),
1749                                                           *mesh, TopAbs_FACE );
1750           while ( const TopoDS_Shape* f = fIt->next() )
1751             if (( isAdjFaceMeshed = mesh->GetSubMesh( *f )->IsMeshComputed() ))
1752               break;
1753           if ( isAdjFaceMeshed )
1754             return toSM( error( TCom("Different nb of segment on logically horizontal edges #")
1755                                 << shapeID( botE ) << " and #"
1756                                 << shapeID( topE ) << ": "
1757                                 << tgtSM->GetSubMeshDS()->NbElements() << " != "
1758                                 << srcSM->GetSubMeshDS()->NbElements() ));
1759           tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1760         }
1761         if ( !tgtSM->IsMeshComputed() )
1762         {
1763           // compute nodes on VERTEXes
1764           SMESH_subMeshIteratorPtr smIt = tgtSM->getDependsOnIterator(/*includeSelf=*/false);
1765           while ( smIt->more() )
1766             smIt->next()->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1767           // project segments
1768           DBGOUT( "COMPUTE H edge (proj) " << tgtSM->GetId());
1769           projector1D->myHyp.SetSourceEdge( TopoDS::Edge( srcSM->GetSubShape() ));
1770           projector1D->InitComputeError();
1771           bool ok = projector1D->Compute( *mesh, tgtSM->GetSubShape() );
1772           if ( !ok )
1773           {
1774             SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1775             if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1776             tgtSM->GetComputeError() = err;
1777             return false;
1778           }
1779         }
1780         tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1781
1782
1783         // Compute quad mesh on wall FACEs
1784         // -------------------------------
1785
1786         // make all EDGES meshed
1787         fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1788         if ( !fSM->SubMeshesComputed() )
1789           return toSM( error( COMPERR_BAD_INPUT_MESH,
1790                               "Not all edges have valid algorithm and hypothesis"));
1791         // mesh the <face>
1792         quadAlgo->InitComputeError();
1793         DBGOUT( "COMPUTE Quad face " << fSM->GetId());
1794         bool ok = quadAlgo->Compute( *mesh, face );
1795         fSM->GetComputeError() = quadAlgo->GetComputeError();
1796         if ( !ok )
1797           return false;
1798         fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1799       }
1800       if ( myHelper->GetIsQuadratic() )
1801       {
1802         // fill myHelper with medium nodes built by quadAlgo
1803         for ( SMDS_ElemIteratorPtr fIt = fSM->GetSubMeshDS()->GetElements(); fIt->more(); )
1804           myHelper->AddTLinks( SMDS_Mesh::DownCast<SMDS_MeshFace>( fIt->next() ));
1805       }
1806     }
1807   }
1808
1809   return true;
1810 }
1811
1812 //=======================================================================
1813 //function : findPropagationSource
1814 //purpose  : Returns a source EDGE of propagation to a given EDGE
1815 //=======================================================================
1816
1817 TopoDS_Edge StdMeshers_Prism_3D::findPropagationSource( const TopoDS_Edge& E )
1818 {
1819   if ( myPropagChains )
1820     for ( size_t i = 0; !myPropagChains[i].IsEmpty(); ++i )
1821       if ( myPropagChains[i].Contains( E ))
1822         return TopoDS::Edge( myPropagChains[i].FindKey( 1 ));
1823
1824   return TopoDS_Edge();
1825 }
1826
1827 //=======================================================================
1828 //function : makeQuadsForOutInProjection
1829 //purpose  : Create artificial wall quads for vertical projection between
1830 //           the outer and inner walls
1831 //=======================================================================
1832
1833 void StdMeshers_Prism_3D::makeQuadsForOutInProjection( const Prism_3D::TPrismTopo& thePrism,
1834                                                        multimap< int, int >&       wgt2quad,
1835                                                        map< int, FaceQuadStruct >& iQ2oiQuads)
1836 {
1837   if ( thePrism.NbWires() <= 1 )
1838     return;
1839
1840   std::set< int > doneWires; // processed wires
1841
1842   SMESH_Mesh*      mesh = myHelper->GetMesh();
1843   const bool  isForward = true;
1844   const bool skipMedium = myHelper->GetIsQuadratic();
1845
1846   // make a source side for all projections
1847
1848   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1849   const int iQuad = w2q->second;
1850   const int iWire = getWireIndex( thePrism.myWallQuads[ iQuad ].front() );
1851   doneWires.insert( iWire );
1852
1853   UVPtStructVec srcNodes;
1854
1855   Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iQuad ].begin();
1856   for ( ; quad != thePrism.myWallQuads[ iQuad ].end(); ++quad )
1857   {
1858     StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1859
1860     // assure that all the source (left) EDGEs are meshed
1861     for ( int i = 0; i < lftSide->NbEdges(); ++i )
1862     {
1863       const TopoDS_Edge& srcE = lftSide->Edge(i);
1864       SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1865       if ( !srcSM->IsMeshComputed() ) {
1866         srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1867         srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1868       }
1869       if ( !srcSM->IsMeshComputed() )
1870         return;
1871     }
1872     const UVPtStructVec& subNodes = lftSide->GetUVPtStruct();
1873     UVPtStructVec::const_iterator subBeg = subNodes.begin(), subEnd = subNodes.end();
1874     if ( !srcNodes.empty() ) ++subBeg;
1875     srcNodes.insert( srcNodes.end(), subBeg, subEnd );
1876   }
1877   StdMeshers_FaceSidePtr srcSide = StdMeshers_FaceSide::New( srcNodes );
1878
1879   // make the quads
1880
1881   list< TopoDS_Edge > sideEdges;
1882   TopoDS_Face face;
1883   for ( ++w2q; w2q != wgt2quad.rend(); ++w2q )
1884   {
1885     const int                  iQuad = w2q->second;
1886     const Prism_3D::TQuadList& quads = thePrism.myWallQuads[ iQuad ];
1887     const int                  iWire = getWireIndex( quads.front() );
1888     if ( !doneWires.insert( iWire ).second )
1889       continue;
1890
1891     sideEdges.clear();
1892     for ( quad = quads.begin(); quad != quads.end(); ++quad )
1893     {
1894       StdMeshers_FaceSidePtr lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
1895       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1896         sideEdges.push_back( lftSide->Edge( i ));
1897       face = lftSide->Face();
1898     }
1899     StdMeshers_FaceSidePtr tgtSide =
1900       StdMeshers_FaceSide::New( face, sideEdges, mesh, isForward, skipMedium, myHelper );
1901
1902     FaceQuadStruct& newQuad = iQ2oiQuads[ iQuad ];
1903     newQuad.side.resize( 4 );
1904     newQuad.side[ QUAD_LEFT_SIDE  ] = srcSide;
1905     newQuad.side[ QUAD_RIGHT_SIDE ] = tgtSide;
1906
1907     wgt2quad.insert( *w2q ); // to process this quad after processing the newQuad
1908   }
1909 }
1910
1911 //=======================================================================
1912 //function : Evaluate
1913 //purpose  :
1914 //=======================================================================
1915
1916 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1917                                    const TopoDS_Shape& theShape,
1918                                    MapShapeNbElems&    aResMap)
1919 {
1920   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1921   {
1922     bool ok = true;
1923     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1924       ok &= Evaluate( theMesh, it.Value(), aResMap );
1925     return ok;
1926   }
1927   SMESH_MesherHelper helper( theMesh );
1928   myHelper = &helper;
1929   myHelper->SetSubShape( theShape );
1930
1931   // find face contains only triangles
1932   vector < SMESH_subMesh * >meshFaces;
1933   TopTools_SequenceOfShape aFaces;
1934   int NumBase = 0, i = 0, NbQFs = 0;
1935   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1936     i++;
1937     aFaces.Append(exp.Current());
1938     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1939     meshFaces.push_back(aSubMesh);
1940     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1941     if( anIt==aResMap.end() )
1942       return toSM( error( "Submesh can not be evaluated"));
1943
1944     std::vector<int> aVec = (*anIt).second;
1945     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1946     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1947     if( nbtri==0 && nbqua>0 ) {
1948       NbQFs++;
1949     }
1950     if( nbtri>0 ) {
1951       NumBase = i;
1952     }
1953   }
1954
1955   if(NbQFs<4) {
1956     std::vector<int> aResVec(SMDSEntity_Last);
1957     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1958     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1959     aResMap.insert(std::make_pair(sm,aResVec));
1960     return toSM( error( "Submesh can not be evaluated" ));
1961   }
1962
1963   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1964
1965   // find number of 1d elems for base face
1966   int nb1d = 0;
1967   TopTools_MapOfShape Edges1;
1968   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1969     Edges1.Add(exp.Current());
1970     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1971     if( sm ) {
1972       MapShapeNbElemsItr anIt = aResMap.find(sm);
1973       if( anIt == aResMap.end() ) continue;
1974       std::vector<int> aVec = (*anIt).second;
1975       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1976     }
1977   }
1978   // find face opposite to base face
1979   int OppNum = 0;
1980   for(i=1; i<=6; i++) {
1981     if(i==NumBase) continue;
1982     bool IsOpposite = true;
1983     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1984       if( Edges1.Contains(exp.Current()) ) {
1985         IsOpposite = false;
1986         break;
1987       }
1988     }
1989     if(IsOpposite) {
1990       OppNum = i;
1991       break;
1992     }
1993   }
1994   // find number of 2d elems on side faces
1995   int nb2d = 0;
1996   for(i=1; i<=6; i++) {
1997     if( i==OppNum || i==NumBase ) continue;
1998     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1999     if( anIt == aResMap.end() ) continue;
2000     std::vector<int> aVec = (*anIt).second;
2001     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2002   }
2003   
2004   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
2005   std::vector<int> aVec = (*anIt).second;
2006   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
2007                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
2008   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2009   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2010   int nb0d_face0 = aVec[SMDSEntity_Node];
2011   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
2012
2013   std::vector<int> aResVec(SMDSEntity_Last);
2014   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
2015   if(IsQuadratic) {
2016     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
2017     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
2018     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
2019   }
2020   else {
2021     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
2022     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
2023     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
2024   }
2025   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2026   aResMap.insert(std::make_pair(sm,aResVec));
2027
2028   return true;
2029 }
2030
2031 //================================================================================
2032 /*!
2033  * \brief Create prisms
2034  * \param columns - columns of nodes generated from nodes of a mesh face
2035  * \param helper - helper initialized by mesh and shape to add prisms to
2036  */
2037 //================================================================================
2038
2039 bool StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
2040                                      SMESH_MesherHelper*          helper)
2041 {
2042   size_t nbNodes = columns.size();
2043   size_t nbZ     = columns[0]->size();
2044   if ( nbZ < 2 ) return false;
2045   for ( size_t i = 1; i < nbNodes; ++i )
2046     if ( columns[i]->size() != nbZ )
2047       return false;
2048
2049   // find out orientation
2050   bool isForward = true;
2051   SMDS_VolumeTool vTool;
2052   size_t z = 1;
2053   switch ( nbNodes ) {
2054   case 3: {
2055     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
2056                                   (*columns[1])[z-1],
2057                                   (*columns[2])[z-1],
2058                                   (*columns[0])[z],   // top
2059                                   (*columns[1])[z],
2060                                   (*columns[2])[z] );
2061     vTool.Set( &tmpPenta );
2062     isForward  = vTool.IsForward();
2063     break;
2064   }
2065   case 4: {
2066     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
2067                                (*columns[2])[z-1], (*columns[3])[z-1],
2068                                (*columns[0])[z],   (*columns[1])[z],   // top
2069                                (*columns[2])[z],   (*columns[3])[z] );
2070     vTool.Set( &tmpHex );
2071     isForward  = vTool.IsForward();
2072     break;
2073   }
2074   default:
2075     const int di = (nbNodes+1) / 3;
2076     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
2077                                 (*columns[di]  )[z-1],
2078                                 (*columns[2*di])[z-1],
2079                                 (*columns[0]   )[z],
2080                                 (*columns[di]  )[z],
2081                                 (*columns[2*di])[z] );
2082     vTool.Set( &tmpVol );
2083     isForward  = vTool.IsForward();
2084   }
2085
2086   // vertical loop on columns
2087
2088   helper->SetElementsOnShape( true );
2089
2090   switch ( nbNodes ) {
2091
2092   case 3: { // ---------- pentahedra
2093     const int i1 = isForward ? 1 : 2;
2094     const int i2 = isForward ? 2 : 1;
2095     for ( z = 1; z < nbZ; ++z )
2096       helper->AddVolume( (*columns[0 ])[z-1], // bottom
2097                          (*columns[i1])[z-1],
2098                          (*columns[i2])[z-1],
2099                          (*columns[0 ])[z],   // top
2100                          (*columns[i1])[z],
2101                          (*columns[i2])[z] );
2102     break;
2103   }
2104   case 4: { // ---------- hexahedra
2105     const int i1 = isForward ? 1 : 3;
2106     const int i3 = isForward ? 3 : 1;
2107     for ( z = 1; z < nbZ; ++z )
2108       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
2109                          (*columns[2])[z-1], (*columns[i3])[z-1],
2110                          (*columns[0])[z],   (*columns[i1])[z],     // top
2111                          (*columns[2])[z],   (*columns[i3])[z] );
2112     break;
2113   }
2114   case 6: { // ---------- octahedra
2115     const int iBase1 = isForward ? -1 : 0;
2116     const int iBase2 = isForward ?  0 :-1;
2117     for ( z = 1; z < nbZ; ++z )
2118       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
2119                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
2120                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
2121                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
2122                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
2123                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
2124     break;
2125   }
2126   default: // ---------- polyhedra
2127     vector<int> quantities( 2 + nbNodes, 4 );
2128     quantities[0] = quantities[1] = nbNodes;
2129     columns.resize( nbNodes + 1 );
2130     columns[ nbNodes ] = columns[ 0 ];
2131     const int i1 = isForward ? 1 : 3;
2132     const int i3 = isForward ? 3 : 1;
2133     const int iBase1 = isForward ? -1 : 0;
2134     const int iBase2 = isForward ?  0 :-1;
2135     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
2136     for ( z = 1; z < nbZ; ++z )
2137     {
2138       for ( size_t i = 0; i < nbNodes; ++i ) {
2139         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
2140         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
2141         // side
2142         int di = 2*nbNodes + 4*i;
2143         nodes[ di+0 ] = (*columns[i  ])[z  ];
2144         nodes[ di+i1] = (*columns[i+1])[z  ];
2145         nodes[ di+2 ] = (*columns[i+1])[z-1];
2146         nodes[ di+i3] = (*columns[i  ])[z-1];
2147       }
2148       helper->AddPolyhedralVolume( nodes, quantities );
2149     }
2150
2151   } // switch ( nbNodes )
2152
2153   return true;
2154 }
2155
2156 //================================================================================
2157 /*!
2158  * \brief Find correspondence between bottom and top nodes
2159  *  If elements on the bottom and top faces are topologically different,
2160  *  and projection is possible and allowed, perform the projection
2161  *  \retval bool - is a success or not
2162  */
2163 //================================================================================
2164
2165 bool StdMeshers_Prism_3D::assocOrProjBottom2Top( const gp_Trsf & bottomToTopTrsf,
2166                                                  const Prism_3D::TPrismTopo& thePrism)
2167 {
2168   SMESH_subMesh * botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2169   SMESH_subMesh * topSM = myHelper->GetMesh()->GetSubMesh( thePrism.myTop    );
2170
2171   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
2172   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
2173
2174   if ( !botSMDS || botSMDS->NbElements() == 0 )
2175   {
2176     _gen->Compute( *myHelper->GetMesh(), botSM->GetSubShape(), /*aShapeOnly=*/true );
2177     botSMDS = botSM->GetSubMeshDS();
2178     if ( !botSMDS || botSMDS->NbElements() == 0 )
2179       return toSM( error(TCom("No elements on face #") << botSM->GetId() ));
2180   }
2181
2182   bool needProject = !topSM->IsMeshComputed();
2183   if ( !needProject &&
2184        (botSMDS->NbElements() != topSMDS->NbElements() ||
2185         botSMDS->NbNodes()    != topSMDS->NbNodes()))
2186   {
2187     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
2188             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
2189     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
2190             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
2191     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
2192                        <<" and #"<< topSM->GetId() << " seems different" ));
2193   }
2194
2195   if ( 0/*needProject && !myProjectTriangles*/ )
2196     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
2197                        <<" and #"<< topSM->GetId() << " seems different" ));
2198   ///RETURN_BAD_RESULT("Need to project but not allowed");
2199
2200   NSProjUtils::TNodeNodeMap n2nMap;
2201   const NSProjUtils::TNodeNodeMap* n2nMapPtr = & n2nMap;
2202   if ( needProject )
2203   {
2204     if ( !projectBottomToTop( bottomToTopTrsf, thePrism ))
2205       return false;
2206     n2nMapPtr = & TProjction2dAlgo::instance( this )->GetNodesMap();
2207   }
2208
2209   if ( !n2nMapPtr || (int) n2nMapPtr->size() < botSMDS->NbNodes() )
2210   {
2211     // associate top and bottom faces
2212     NSProjUtils::TShapeShapeMap shape2ShapeMap;
2213     const bool sameTopo =
2214       NSProjUtils::FindSubShapeAssociation( thePrism.myBottom, myHelper->GetMesh(),
2215                                             thePrism.myTop,    myHelper->GetMesh(),
2216                                             shape2ShapeMap);
2217     if ( !sameTopo )
2218       for ( size_t iQ = 0; iQ < thePrism.myWallQuads.size(); ++iQ )
2219       {
2220         const Prism_3D::TQuadList& quadList = thePrism.myWallQuads[iQ];
2221         StdMeshers_FaceSidePtr      botSide = quadList.front()->side[ QUAD_BOTTOM_SIDE ];
2222         StdMeshers_FaceSidePtr      topSide = quadList.back ()->side[ QUAD_TOP_SIDE ];
2223         if ( botSide->NbEdges() == topSide->NbEdges() )
2224         {
2225           for ( int iE = 0; iE < botSide->NbEdges(); ++iE )
2226           {
2227             NSProjUtils::InsertAssociation( botSide->Edge( iE ),
2228                                             topSide->Edge( iE ), shape2ShapeMap );
2229             NSProjUtils::InsertAssociation( myHelper->IthVertex( 0, botSide->Edge( iE )),
2230                                             myHelper->IthVertex( 0, topSide->Edge( iE )),
2231                                             shape2ShapeMap );
2232           }
2233         }
2234         else
2235         {
2236           TopoDS_Vertex vb, vt;
2237           StdMeshers_FaceSidePtr sideB, sideT;
2238           vb = myHelper->IthVertex( 0, botSide->Edge( 0 ));
2239           vt = myHelper->IthVertex( 0, topSide->Edge( 0 ));
2240           sideB = quadList.front()->side[ QUAD_LEFT_SIDE ];
2241           sideT = quadList.back ()->side[ QUAD_LEFT_SIDE ];
2242           if ( vb.IsSame( sideB->FirstVertex() ) &&
2243                vt.IsSame( sideT->LastVertex() ))
2244           {
2245             NSProjUtils::InsertAssociation( botSide->Edge( 0 ),
2246                                             topSide->Edge( 0 ), shape2ShapeMap );
2247             NSProjUtils::InsertAssociation( vb, vt, shape2ShapeMap );
2248           }
2249           vb = myHelper->IthVertex( 1, botSide->Edge( botSide->NbEdges()-1 ));
2250           vt = myHelper->IthVertex( 1, topSide->Edge( topSide->NbEdges()-1 ));
2251           sideB = quadList.front()->side[ QUAD_RIGHT_SIDE ];
2252           sideT = quadList.back ()->side[ QUAD_RIGHT_SIDE ];
2253           if ( vb.IsSame( sideB->FirstVertex() ) &&
2254                vt.IsSame( sideT->LastVertex() ))
2255           {
2256             NSProjUtils::InsertAssociation( botSide->Edge( botSide->NbEdges()-1 ),
2257                                             topSide->Edge( topSide->NbEdges()-1 ),
2258                                             shape2ShapeMap );
2259             NSProjUtils::InsertAssociation( vb, vt, shape2ShapeMap );
2260           }
2261         }
2262       }
2263
2264     // Find matching nodes of top and bottom faces
2265     n2nMapPtr = & n2nMap;
2266     if ( ! NSProjUtils::FindMatchingNodesOnFaces( thePrism.myBottom, myHelper->GetMesh(),
2267                                                   thePrism.myTop,    myHelper->GetMesh(),
2268                                                   shape2ShapeMap, n2nMap ))
2269     {
2270       if ( sameTopo )
2271         return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
2272                            <<" and #"<< topSM->GetId() << " seems different" ));
2273       else
2274         return toSM( error(TCom("Topology of faces #") << botSM->GetId()
2275                            <<" and #"<< topSM->GetId() << " seems different" ));
2276     }
2277   }
2278
2279   // Fill myBotToColumnMap
2280
2281   int zSize = myBlock.VerticalSize();
2282   TNodeNodeMap::const_iterator bN_tN = n2nMapPtr->begin();
2283   for ( ; bN_tN != n2nMapPtr->end(); ++bN_tN )
2284   {
2285     const SMDS_MeshNode* botNode = bN_tN->first;
2286     const SMDS_MeshNode* topNode = bN_tN->second;
2287     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
2288          myBlock.HasNodeColumn( botNode ))
2289       continue; // wall columns are contained in myBlock
2290     // create node column
2291     Prism_3D::TNode bN( botNode );
2292     TNode2ColumnMap::iterator bN_col =
2293       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
2294     TNodeColumn & column = bN_col->second;
2295     column.resize( zSize, 0 );
2296     column.front() = botNode;
2297     column.back()  = topNode;
2298   }
2299   return true;
2300 }
2301
2302 //================================================================================
2303 /*!
2304  * \brief Remove faces from the top face and re-create them by projection from the bottom
2305  * \retval bool - a success or not
2306  */
2307 //================================================================================
2308
2309 bool StdMeshers_Prism_3D::projectBottomToTop( const gp_Trsf &             bottomToTopTrsf,
2310                                               const Prism_3D::TPrismTopo& thePrism )
2311 {
2312   if ( project2dMesh( thePrism.myBottom, thePrism.myTop ))
2313   {
2314     return true;
2315   }
2316   NSProjUtils::TNodeNodeMap& n2nMap = 
2317     (NSProjUtils::TNodeNodeMap&) TProjction2dAlgo::instance( this )->GetNodesMap();
2318   n2nMap.clear();
2319
2320   myUseBlock = true;
2321
2322   SMESHDS_Mesh*  meshDS = myHelper->GetMeshDS();
2323   SMESH_subMesh * botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
2324   SMESH_subMesh * topSM = myHelper->GetMesh()->GetSubMesh( thePrism.myTop );
2325
2326   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
2327   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
2328
2329   if ( topSMDS && topSMDS->NbElements() > 0 )
2330   {
2331     //topSM->ComputeStateEngine( SMESH_subMesh::CLEAN ); -- avoid propagation of events
2332     for ( SMDS_ElemIteratorPtr eIt = topSMDS->GetElements(); eIt->more(); )
2333       meshDS->RemoveFreeElement( eIt->next(), topSMDS, /*fromGroups=*/false );
2334     for ( SMDS_NodeIteratorPtr nIt = topSMDS->GetNodes(); nIt->more(); )
2335       meshDS->RemoveFreeNode( nIt->next(), topSMDS, /*fromGroups=*/false );
2336   }
2337
2338   const TopoDS_Face& botFace = thePrism.myBottom; // oriented within
2339   const TopoDS_Face& topFace = thePrism.myTop;    //    the 3D SHAPE
2340   int topFaceID = meshDS->ShapeToIndex( thePrism.myTop );
2341
2342   SMESH_MesherHelper botHelper( *myHelper->GetMesh() );
2343   botHelper.SetSubShape( botFace );
2344   botHelper.ToFixNodeParameters( true );
2345   bool checkUV;
2346   SMESH_MesherHelper topHelper( *myHelper->GetMesh() );
2347   topHelper.SetSubShape( topFace );
2348   topHelper.ToFixNodeParameters( true );
2349   double distXYZ[4], fixTol = 10 * topHelper.MaxTolerance( topFace );
2350
2351   // Fill myBotToColumnMap
2352
2353   int zSize = myBlock.VerticalSize();
2354   Prism_3D::TNode prevTNode;
2355   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
2356   while ( nIt->more() )
2357   {
2358     const SMDS_MeshNode* botNode = nIt->next();
2359     const SMDS_MeshNode* topNode = 0;
2360     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
2361       continue; // strange
2362
2363     Prism_3D::TNode bN( botNode );
2364     if ( bottomToTopTrsf.Form() == gp_Identity )
2365     {
2366       // compute bottom node params
2367       gp_XYZ paramHint(-1,-1,-1);
2368       if ( prevTNode.IsNeighbor( bN ))
2369       {
2370         paramHint = prevTNode.GetParams();
2371         // double tol = 1e-2 * ( prevTNode.GetCoords() - bN.GetCoords() ).Modulus();
2372         // myBlock.SetTolerance( Min( myBlock.GetTolerance(), tol ));
2373       }
2374       if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
2375                                        ID_BOT_FACE, paramHint ))
2376         return toSM( error(TCom("Can't compute normalized parameters for node ")
2377                            << botNode->GetID() << " on the face #"<< botSM->GetId() ));
2378       prevTNode = bN;
2379       // compute top node coords
2380       gp_XYZ topXYZ; gp_XY topUV;
2381       if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
2382            !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
2383         return toSM( error(TCom("Can't compute coordinates "
2384                                 "by normalized parameters on the face #")<< topSM->GetId() ));
2385       topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
2386       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2387     }
2388     else // use bottomToTopTrsf
2389     {
2390       gp_XYZ coords = bN.GetCoords();
2391       bottomToTopTrsf.Transforms( coords );
2392       topNode = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
2393       gp_XY topUV = botHelper.GetNodeUV( botFace, botNode, 0, &checkUV );
2394       meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
2395       distXYZ[0] = -1;
2396       if ( topHelper.CheckNodeUV( topFace, topNode, topUV, fixTol, /*force=*/false, distXYZ ) &&
2397            distXYZ[0] > fixTol && distXYZ[0] < fixTol * 1e+3 )
2398         meshDS->MoveNode( topNode, distXYZ[1], distXYZ[2], distXYZ[3] ); // transform can be inaccurate
2399     }
2400     // create node column
2401     TNode2ColumnMap::iterator bN_col = 
2402       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
2403     TNodeColumn & column = bN_col->second;
2404     column.resize( zSize );
2405     column.front() = botNode;
2406     column.back()  = topNode;
2407
2408     n2nMap.insert( n2nMap.end(), make_pair( botNode, topNode ));
2409
2410     if ( _computeCanceled )
2411       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
2412   }
2413
2414   // Create top faces
2415
2416   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
2417
2418   // care of orientation;
2419   // if the bottom faces is orienetd OK then top faces must be reversed
2420   bool reverseTop = true;
2421   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
2422     reverseTop = ! myHelper->IsReversedSubMesh( botFace );
2423   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
2424
2425   // loop on bottom mesh faces
2426   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
2427   vector< const SMDS_MeshNode* > nodes;
2428   while ( faceIt->more() )
2429   {
2430     const SMDS_MeshElement* face = faceIt->next();
2431     if ( !face || face->GetType() != SMDSAbs_Face )
2432       continue;
2433
2434     // find top node in columns for each bottom node
2435     int nbNodes = face->NbCornerNodes();
2436     nodes.resize( nbNodes );
2437     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
2438     {
2439       const SMDS_MeshNode* n = face->GetNode( *iPtr );
2440       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
2441         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
2442         if ( bot_column == myBotToColumnMap.end() )
2443           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
2444         nodes[ iFrw ] = bot_column->second.back();
2445       }
2446       else {
2447         const TNodeColumn* column = myBlock.GetNodeColumn( n );
2448         if ( !column )
2449           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
2450         nodes[ iFrw ] = column->back();
2451       }
2452     }
2453     SMDS_MeshElement* newFace = 0;
2454     switch ( nbNodes ) {
2455
2456     case 3: {
2457       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
2458       break;
2459     }
2460     case 4: {
2461       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
2462       break;
2463     }
2464     default:
2465       newFace = meshDS->AddPolygonalFace( nodes );
2466     }
2467     if ( newFace )
2468       meshDS->SetMeshElementOnShape( newFace, topFaceID );
2469   }
2470
2471   myHelper->SetElementsOnShape( oldSetElemsOnShape );
2472
2473   // Check the projected mesh
2474
2475   if ( thePrism.NbWires() > 1 && // there are holes
2476        topHelper.IsDistorted2D( topSM, /*checkUV=*/false ))
2477   {
2478     SMESH_MeshEditor editor( topHelper.GetMesh() );
2479
2480     // smooth in 2D or 3D?
2481     TopLoc_Location loc;
2482     Handle(Geom_Surface) surface = BRep_Tool::Surface( topFace, loc );
2483     bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
2484
2485     set<const SMDS_MeshNode*> fixedNodes;
2486     TIDSortedElemSet faces;
2487     for ( faceIt = topSMDS->GetElements(); faceIt->more(); )
2488       faces.insert( faces.end(), faceIt->next() );
2489
2490     bool isOk = false;
2491     for ( int isCentroidal = 0; isCentroidal < 2; ++isCentroidal )
2492     {
2493       SMESH_MeshEditor::SmoothMethod algo =
2494         isCentroidal ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
2495
2496       int nbAttempts = isCentroidal ? 1 : 10;
2497       for ( int iAttemp = 0; iAttemp < nbAttempts; ++iAttemp )
2498       {
2499         TIDSortedElemSet workFaces = faces;
2500
2501         // smoothing
2502         editor.Smooth( workFaces, fixedNodes, algo, /*nbIterations=*/ 10,
2503                        /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
2504
2505         if (( isOk = !topHelper.IsDistorted2D( topSM, /*checkUV=*/true )) &&
2506             ( !isCentroidal ))
2507           break;
2508       }
2509     }
2510     if ( !isOk )
2511       return toSM( error( TCom("Projection from face #") << botSM->GetId()
2512                           << " to face #" << topSM->GetId()
2513                           << " failed: inverted elements created"));
2514   }
2515
2516   TProjction2dAlgo::instance( this )->SetEventListener( topSM );
2517
2518   return true;
2519 }
2520
2521 //=======================================================================
2522 //function : getSweepTolerance
2523 //purpose  : Compute tolerance to pass to StdMeshers_Sweeper
2524 //=======================================================================
2525
2526 double StdMeshers_Prism_3D::getSweepTolerance( const Prism_3D::TPrismTopo& thePrism )
2527 {
2528   SMESHDS_Mesh*    meshDS = myHelper->GetMeshDS();
2529   SMESHDS_SubMesh * sm[2] = { meshDS->MeshElements( thePrism.myBottom ),
2530                               meshDS->MeshElements( thePrism.myTop )    };
2531   double minDist = 1e100;
2532
2533   vector< SMESH_TNodeXYZ > nodes;
2534   for ( int iSM = 0; iSM < 2; ++iSM )
2535   {
2536     if ( !sm[ iSM ]) continue;
2537
2538     SMDS_ElemIteratorPtr fIt = sm[ iSM ]->GetElements();
2539     while ( fIt->more() )
2540     {
2541       const SMDS_MeshElement* face = fIt->next();
2542       const int            nbNodes = face->NbCornerNodes();
2543       SMDS_ElemIteratorPtr     nIt = face->nodesIterator();
2544
2545       nodes.resize( nbNodes + 1 );
2546       for ( int iN = 0; iN < nbNodes; ++iN )
2547         nodes[ iN ] = nIt->next();
2548       nodes.back() = nodes[0];
2549       
2550       // loop on links
2551       double dist2;
2552       for ( int iN = 0; iN < nbNodes; ++iN )
2553       {
2554         if ( nodes[ iN   ]._node->GetPosition()->GetDim() < 2 &&
2555              nodes[ iN+1 ]._node->GetPosition()->GetDim() < 2 )
2556         {
2557           // it's a boundary link; measure distance of other
2558           // nodes to this link
2559           gp_XYZ linkDir = nodes[ iN ] - nodes[ iN+1 ];
2560           double linkLen = linkDir.Modulus();
2561           bool   isDegen = ( linkLen < numeric_limits<double>::min() );
2562           if ( !isDegen ) linkDir /= linkLen;
2563           for ( int iN2 = 0; iN2 < nbNodes; ++iN2 ) // loop on other nodes
2564           {
2565             if ( nodes[ iN2 ] == nodes[ iN ] ||
2566                  nodes[ iN2 ] == nodes[ iN+1 ]) continue;
2567             if ( isDegen )
2568             {
2569               dist2 = ( nodes[ iN ] - nodes[ iN2 ]).SquareModulus();
2570             }
2571             else
2572             {
2573               dist2 = linkDir.CrossSquareMagnitude( nodes[ iN ] - nodes[ iN2 ]);
2574             }
2575             if ( dist2 > numeric_limits<double>::min() )
2576               minDist = Min ( minDist, dist2 );
2577           }
2578         }
2579         // measure length link
2580         else if ( nodes[ iN ]._node < nodes[ iN+1 ]._node ) // not to measure same link twice
2581         {
2582           dist2 = ( nodes[ iN ] - nodes[ iN+1 ]).SquareModulus();
2583           if ( dist2 > numeric_limits<double>::min() )
2584             minDist = Min ( minDist, dist2 );
2585         }
2586       }
2587     }
2588   }
2589   return 0.1 * Sqrt ( minDist );
2590 }
2591
2592 //=======================================================================
2593 //function : isSimpleQuad
2594 //purpose  : check if the bottom FACE is meshable with nice quadrangles,
2595 //           if so the block aproach can work rather fast.
2596 //           This is a temporary mean caused by problems in StdMeshers_Sweeper
2597 //=======================================================================
2598
2599 bool StdMeshers_Prism_3D::isSimpleBottom( const Prism_3D::TPrismTopo& thePrism )
2600 {
2601   if ( thePrism.myNbEdgesInWires.front() != 4 )
2602     return false;
2603
2604   // analyse angles between edges
2605   double nbConcaveAng = 0, nbConvexAng = 0;
2606   TopoDS_Face reverseBottom = TopoDS::Face( thePrism.myBottom.Reversed() ); // see initPrism()
2607   TopoDS_Vertex commonV;
2608   const list< TopoDS_Edge >& botEdges = thePrism.myBottomEdges;
2609   list< TopoDS_Edge >::const_iterator edge = botEdges.begin();
2610   while ( edge != botEdges.end() )
2611   {
2612     if ( SMESH_Algo::isDegenerated( *edge ))
2613       return false;
2614     TopoDS_Edge e1 = *edge++;
2615     TopoDS_Edge e2 = ( edge == botEdges.end() ? botEdges.front() : *edge );
2616     if ( ! TopExp::CommonVertex( e1, e2,  commonV ))
2617     {
2618       e2 = botEdges.front();
2619       if ( ! TopExp::CommonVertex( e1, e2,  commonV ))
2620         break;
2621     }
2622     double angle = myHelper->GetAngle( e1, e2, reverseBottom, commonV );
2623     if ( angle < -5 * M_PI/180 )
2624       if ( ++nbConcaveAng > 1 )
2625         return false;
2626     if ( angle > 85 * M_PI/180 )
2627       if ( ++nbConvexAng > 4 )
2628         return false;
2629   }
2630   return true;
2631 }
2632
2633 //=======================================================================
2634 //function : allVerticalEdgesStraight
2635 //purpose  : Defines if all "vertical" EDGEs are straight
2636 //=======================================================================
2637
2638 bool StdMeshers_Prism_3D::allVerticalEdgesStraight( const Prism_3D::TPrismTopo& thePrism )
2639 {
2640   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
2641   {
2642     const Prism_3D::TQuadList& quads = thePrism.myWallQuads[i];
2643     Prism_3D::TQuadList::const_iterator quadIt = quads.begin();
2644     TopoDS_Edge prevQuadEdge;
2645     for ( ; quadIt != quads.end(); ++quadIt )
2646     {
2647       StdMeshers_FaceSidePtr rightSide = (*quadIt)->side[ QUAD_RIGHT_SIDE ];
2648
2649       if ( !prevQuadEdge.IsNull() &&
2650            !SMESH_Algo::IsContinuous( rightSide->Edge( 0 ), prevQuadEdge ))
2651         return false;
2652
2653       for ( int iE = 0; iE < rightSide->NbEdges(); ++iE )
2654       {
2655         const TopoDS_Edge & rightE = rightSide->Edge( iE );
2656         if ( !SMESH_Algo::IsStraight( rightE, /*degenResult=*/true ))
2657           return false;
2658
2659         if ( iE > 0 &&
2660              !SMESH_Algo::IsContinuous( rightSide->Edge( iE-1 ), rightE ))
2661           return false;
2662
2663         prevQuadEdge = rightE;
2664       }
2665     }
2666   }
2667   return true;
2668 }
2669
2670 //=======================================================================
2671 //function : project2dMesh
2672 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
2673 //           to a source FACE of another prism (theTgtFace)
2674 //=======================================================================
2675
2676 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
2677                                         const TopoDS_Face& theTgtFace)
2678 {
2679   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
2680   projector2D->myHyp.SetSourceFace( theSrcFace );
2681   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
2682
2683   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
2684   if ( !ok && tgtSM->GetSubMeshDS() ) {
2685     //tgtSM->ComputeStateEngine( SMESH_subMesh::CLEAN ); -- avoid propagation of events
2686     SMESHDS_Mesh*     meshDS = myHelper->GetMeshDS();
2687     SMESHDS_SubMesh* tgtSMDS = tgtSM->GetSubMeshDS();
2688     for ( SMDS_ElemIteratorPtr eIt = tgtSMDS->GetElements(); eIt->more(); )
2689       meshDS->RemoveFreeElement( eIt->next(), tgtSMDS, /*fromGroups=*/false );
2690     for ( SMDS_NodeIteratorPtr nIt = tgtSMDS->GetNodes(); nIt->more(); )
2691       meshDS->RemoveFreeNode( nIt->next(), tgtSMDS, /*fromGroups=*/false );
2692   }
2693   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
2694   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2695
2696   projector2D->SetEventListener( tgtSM );
2697
2698   return ok;
2699 }
2700
2701 //================================================================================
2702 /*!
2703  * \brief Set projection coordinates of a node to a face and it's sub-shapes
2704  * \param faceID - the face given by in-block ID
2705  * \param params - node normalized parameters
2706  * \retval bool - is a success
2707  */
2708 //================================================================================
2709
2710 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
2711 {
2712   // find base and top edges of the face
2713   enum { BASE = 0, TOP, LEFT, RIGHT };
2714   vector< int > edgeVec; // 0-base, 1-top
2715   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
2716
2717   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
2718   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
2719
2720   SHOWYXZ("\nparams ", params);
2721   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
2722   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
2723
2724   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
2725   {
2726     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
2727     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
2728
2729     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
2730     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
2731   }
2732   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
2733   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
2734
2735   return true;
2736 }
2737
2738 //=======================================================================
2739 //function : toSM
2740 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
2741 //=======================================================================
2742
2743 bool StdMeshers_Prism_3D::toSM( bool isOK )
2744 {
2745   if ( mySetErrorToSM &&
2746        !isOK &&
2747        myHelper &&
2748        !myHelper->GetSubShape().IsNull() &&
2749        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
2750   {
2751     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
2752     sm->GetComputeError() = this->GetComputeError();
2753     // clear error in order not to return it twice
2754     _error = COMPERR_OK;
2755     _comment.clear();
2756   }
2757   return isOK;
2758 }
2759
2760 //=======================================================================
2761 //function : shapeID
2762 //purpose  : Return index of a shape
2763 //=======================================================================
2764
2765 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
2766 {
2767   if ( S.IsNull() ) return 0;
2768   if ( !myHelper  ) return -3;
2769   return myHelper->GetMeshDS()->ShapeToIndex( S );
2770 }
2771
2772 namespace // utils used by StdMeshers_Prism_3D::IsApplicable()
2773 {
2774   struct EdgeWithNeighbors
2775   {
2776     TopoDS_Edge _edge;
2777     int         _iBase;   /* index in a WIRE with non-base EDGEs excluded */
2778     int         _iL, _iR; /* used to connect edges in a base FACE */
2779     bool        _isBase;  /* is used in a base FACE */
2780     EdgeWithNeighbors(const TopoDS_Edge& E, int iE, int nbE, int shift, bool isBase ):
2781       _edge( E ), _iBase( iE + shift ),
2782       _iL( SMESH_MesherHelper::WrapIndex( iE-1, Max( 1, nbE )) + shift ),
2783       _iR( SMESH_MesherHelper::WrapIndex( iE+1, Max( 1, nbE )) + shift ),
2784       _isBase( isBase )
2785     {
2786     }
2787     EdgeWithNeighbors() {}
2788     bool IsInternal() const { return !_edge.IsNull() && _edge.Orientation() == TopAbs_INTERNAL; }
2789   };
2790   // PrismSide contains all FACEs linking a bottom EDGE with a top one. 
2791   struct PrismSide 
2792   {
2793     TopoDS_Face                 _face;    // a currently treated upper FACE
2794     TopTools_IndexedMapOfShape *_faces;   // all FACEs (pointer because of a private copy constructor)
2795     TopoDS_Edge                 _topEdge; // a current top EDGE
2796     vector< EdgeWithNeighbors >*_edges;   // all EDGEs of _face
2797     int                         _iBotEdge;       // index of _topEdge within _edges
2798     vector< bool >              _isCheckedEdge;  // mark EDGEs whose two owner FACEs found
2799     int                         _nbCheckedEdges; // nb of EDGEs whose location is defined
2800     PrismSide                  *_leftSide;       // neighbor sides
2801     PrismSide                  *_rightSide;
2802     bool                        _isInternal; // whether this side raises from an INTERNAL EDGE
2803     void SetExcluded() { _leftSide = _rightSide = NULL; }
2804     bool IsExcluded() const { return !_leftSide; }
2805     const TopoDS_Edge& Edge( int i ) const
2806     {
2807       return (*_edges)[ i ]._edge;
2808     }
2809     int FindEdge( const TopoDS_Edge& E ) const
2810     {
2811       for ( size_t i = 0; i < _edges->size(); ++i )
2812         if ( E.IsSame( Edge( i ))) return i;
2813       return -1;
2814     }
2815     bool IsSideFace( const TopoDS_Shape& face, const bool checkNeighbors ) const
2816     {
2817       if ( _faces->Contains( face )) // avoid returning true for a prism top FACE
2818         return ( !_face.IsNull() || !( face.IsSame( _faces->FindKey( _faces->Extent() ))));
2819
2820       if ( checkNeighbors )
2821         return (( _leftSide  && _leftSide->IsSideFace ( face, false )) ||
2822                 ( _rightSide && _rightSide->IsSideFace( face, false )));
2823
2824       return false;
2825     }
2826   };
2827   //--------------------------------------------------------------------------------
2828   /*!
2829    * \brief Return another faces sharing an edge
2830    */
2831   const TopoDS_Face & getAnotherFace( const TopoDS_Face& face,
2832                                       const TopoDS_Edge& edge,
2833                                       TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge)
2834   {
2835     TopTools_ListIteratorOfListOfShape faceIt( facesOfEdge.FindFromKey( edge ));
2836     for ( ; faceIt.More(); faceIt.Next() )
2837       if ( !face.IsSame( faceIt.Value() ))
2838         return TopoDS::Face( faceIt.Value() );
2839     return face;
2840   }
2841
2842   //--------------------------------------------------------------------------------
2843   /*!
2844    * \brief Return ordered edges of a face
2845    */
2846   bool getEdges( const TopoDS_Face&                         face,
2847                  vector< EdgeWithNeighbors > &              edges,
2848                  TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge,
2849                  const bool                                 noHolesAllowed)
2850   {
2851     TopoDS_Face f = face;
2852     if ( f.Orientation() != TopAbs_FORWARD &&
2853          f.Orientation() != TopAbs_REVERSED )
2854       f.Orientation( TopAbs_FORWARD );
2855     list< TopoDS_Edge > ee;
2856     list< int >         nbEdgesInWires;
2857     int nbW = SMESH_Block::GetOrderedEdges( f, ee, nbEdgesInWires );
2858     if ( nbW > 1 && noHolesAllowed )
2859       return false;
2860
2861     int iE, nbTot = 0, nbBase, iBase;
2862     list< TopoDS_Edge >::iterator   e = ee.begin();
2863     list< int         >::iterator nbE = nbEdgesInWires.begin();
2864     for ( ; nbE != nbEdgesInWires.end(); ++nbE )
2865       for ( iE = 0; iE < *nbE; ++e, ++iE )
2866         if ( SMESH_Algo::isDegenerated( *e )) // degenerated EDGE is never used
2867         {
2868           e = --ee.erase( e );
2869           --(*nbE);
2870           --iE;
2871         }
2872
2873     vector<int> isBase;
2874     edges.clear();
2875     e = ee.begin();
2876     for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
2877     {
2878       nbBase = 0;
2879       isBase.resize( *nbE );
2880       list< TopoDS_Edge >::iterator eIt = e;
2881       for ( iE = 0; iE < *nbE; ++eIt, ++iE )
2882       {
2883         isBase[ iE ] = ( getAnotherFace( face, *eIt, facesOfEdge ) != face );
2884         nbBase += isBase[ iE ];
2885       }
2886       for ( iBase = 0, iE = 0; iE < *nbE; ++e, ++iE )
2887       {
2888         edges.push_back( EdgeWithNeighbors( *e, iBase, nbBase, nbTot, isBase[ iE ] ));
2889         iBase += isBase[ iE ];
2890       }
2891       nbTot += nbBase;
2892     }
2893     if ( nbTot == 0 )
2894       return false;
2895
2896     // IPAL53099. Set correct neighbors to INTERNAL EDGEs, which can be connected to
2897     // EDGEs of the outer WIRE but this fact can't be detected by their order.
2898     if ( nbW > 1 )
2899     {
2900       int iFirst = 0, iLast;
2901       for ( nbE = nbEdgesInWires.begin(); nbE != nbEdgesInWires.end(); ++nbE )
2902       {
2903         iLast = iFirst + *nbE - 1;
2904         TopoDS_Vertex vv[2] = { SMESH_MesherHelper::IthVertex( 0, edges[ iFirst ]._edge ),
2905                                 SMESH_MesherHelper::IthVertex( 1, edges[ iLast  ]._edge ) };
2906         bool isConnectOk = ( vv[0].IsSame( vv[1] ));
2907         if ( !isConnectOk )
2908         {
2909           edges[ iFirst ]._iL = edges[ iFirst ]._iBase; // connect to self
2910           edges[ iLast  ]._iR = edges[ iLast ]._iBase;
2911
2912           // look for an EDGE of the outer WIREs connected to vv
2913           TopoDS_Vertex v0, v1;
2914           for ( iE = 0; iE < iFirst; ++iE )
2915           {
2916             v0 = SMESH_MesherHelper::IthVertex( 0, edges[ iE ]._edge );
2917             v1 = SMESH_MesherHelper::IthVertex( 1, edges[ iE ]._edge );
2918             if ( vv[0].IsSame( v0 ) || vv[0].IsSame( v1 ))
2919               edges[ iFirst ]._iL = edges[ iE ]._iBase;
2920             if ( vv[1].IsSame( v0 ) || vv[1].IsSame( v1 ))
2921               edges[ iLast  ]._iR = edges[ iE ]._iBase;
2922           }
2923         }
2924         iFirst += *nbE;
2925       }
2926     }
2927     return edges.size();
2928   }
2929   
2930   //--------------------------------------------------------------------------------
2931   /*!
2932    * \brief Return number of faces sharing given edges
2933    */
2934   // int nbAdjacentFaces( const std::vector< EdgeWithNeighbors >&          edges,
2935   //                      const TopTools_IndexedDataMapOfShapeListOfShape& facesOfEdge )
2936   // {
2937   //   TopTools_MapOfShape adjFaces;
2938
2939   //   for ( size_t i = 0; i < edges.size(); ++i )
2940   //   {
2941   //     TopTools_ListIteratorOfListOfShape faceIt( facesOfEdge.FindFromKey( edges[i]._edge ));
2942   //     for ( ; faceIt.More(); faceIt.Next() )
2943   //       adjFaces.Add( faceIt.Value() );
2944   //   }
2945   //   return adjFaces.Extent();
2946   // }
2947 }
2948
2949 //================================================================================
2950 /*!
2951  * \brief Return true if the algorithm can mesh this shape
2952  *  \param [in] aShape - shape to check
2953  *  \param [in] toCheckAll - if true, this check returns OK if all shapes are OK,
2954  *              else, returns OK if at least one shape is OK
2955  */
2956 //================================================================================
2957
2958 bool StdMeshers_Prism_3D::IsApplicable(const TopoDS_Shape & shape, bool toCheckAll)
2959 {
2960   TopExp_Explorer sExp( shape, TopAbs_SOLID );
2961   if ( !sExp.More() )
2962     return false;
2963
2964   for ( ; sExp.More(); sExp.Next() )
2965   {
2966     // check nb shells
2967     TopoDS_Shape shell;
2968     TopExp_Explorer shExp( sExp.Current(), TopAbs_SHELL );
2969     while ( shExp.More() ) {
2970       shell = shExp.Current();
2971       shExp.Next();
2972       if ( shExp.More() && BRep_Tool::IsClosed( shExp.Current() ))
2973         shell.Nullify();
2974     }
2975     if ( shell.IsNull() ) {
2976       if ( toCheckAll ) return false;
2977       continue;
2978     }
2979     // get all faces
2980     TopTools_IndexedMapOfShape allFaces;
2981     TopExp::MapShapes( sExp.Current(), TopAbs_FACE, allFaces );
2982     if ( allFaces.Extent() < 3 ) {
2983       if ( toCheckAll ) return false;
2984       continue;
2985     }
2986     // is a box?
2987     if ( allFaces.Extent() == 6 )
2988     {
2989       TopTools_IndexedMapOfOrientedShape map;
2990       bool isBox = SMESH_Block::FindBlockShapes( TopoDS::Shell( shell ),
2991                                                  TopoDS_Vertex(), TopoDS_Vertex(), map );
2992       if ( isBox ) {
2993         if ( !toCheckAll ) return true;
2994         continue;
2995       }
2996     }
2997 #ifdef _DEBUG_
2998     TopTools_IndexedMapOfShape allShapes; // usage: allShapes.FindIndex( s )
2999     TopExp::MapShapes( shape, allShapes );
3000 #endif
3001
3002     TopTools_IndexedDataMapOfShapeListOfShape facesOfEdge;
3003     TopTools_ListIteratorOfListOfShape faceIt;
3004     TopExp::MapShapesAndAncestors( sExp.Current(), TopAbs_EDGE, TopAbs_FACE , facesOfEdge );
3005     if ( facesOfEdge.IsEmpty() ) {
3006       if ( toCheckAll ) return false;
3007       continue;
3008     }
3009
3010     typedef vector< EdgeWithNeighbors > TEdgeWithNeighborsVec;
3011     vector< TEdgeWithNeighborsVec > faceEdgesVec( allFaces.Extent() + 1 );
3012     const size_t nbEdgesMax = facesOfEdge.Extent() * 2; // there can be seam EDGEs
3013     TopTools_IndexedMapOfShape* facesOfSide = new TopTools_IndexedMapOfShape[ nbEdgesMax ];
3014     SMESHUtils::ArrayDeleter<TopTools_IndexedMapOfShape> delFacesOfSide( facesOfSide );
3015
3016     // try to use each face as a bottom one
3017     bool prismDetected = false;
3018     vector< PrismSide > sides;
3019     for ( int iF = 1; iF < allFaces.Extent() && !prismDetected; ++iF )
3020     {
3021       const TopoDS_Face& botF = TopoDS::Face( allFaces( iF ));
3022
3023       TEdgeWithNeighborsVec& botEdges = faceEdgesVec[ iF ];
3024       if ( botEdges.empty() )
3025         if ( !getEdges( botF, botEdges, facesOfEdge, /*noHoles=*/false ))
3026           break;
3027
3028       int nbBase = 0;
3029       for ( size_t iS = 0; iS < botEdges.size(); ++iS )
3030         nbBase += botEdges[ iS ]._isBase;
3031
3032       if ( allFaces.Extent()-1 <= nbBase )
3033         continue; // all faces are adjacent to botF - no top FACE
3034
3035       // init data of side FACEs
3036       sides.clear();
3037       sides.resize( nbBase );
3038       size_t iS = 0;
3039       for ( size_t iE = 0; iE < botEdges.size(); ++iE )
3040       {
3041         if ( !botEdges[ iE ]._isBase )
3042           continue;
3043         sides[ iS ]._topEdge    = botEdges[ iE ]._edge;
3044         sides[ iS ]._face       = botF;
3045         sides[ iS ]._leftSide   = & sides[ botEdges[ iE ]._iR ];
3046         sides[ iS ]._rightSide  = & sides[ botEdges[ iE ]._iL ];
3047         sides[ iS ]._isInternal = botEdges[ iE ].IsInternal();
3048         sides[ iS ]._faces      = & facesOfSide[ iS ];
3049         sides[ iS ]._faces->Clear();
3050         ++iS;
3051       }
3052
3053       bool isOK = true; // ok for a current botF
3054       bool isAdvanced = true; // is new data found in a current loop
3055       int  nbFoundSideFaces = 0;
3056       for ( int iLoop = 0; isOK && isAdvanced; ++iLoop )
3057       {
3058         isAdvanced = false;
3059         for ( size_t iS = 0; iS < sides.size() && isOK; ++iS )
3060         {
3061           PrismSide& side = sides[ iS ];
3062           if ( side._face.IsNull() )
3063             continue; // probably the prism top face is the last of side._faces
3064
3065           if ( side._topEdge.IsNull() )
3066           {
3067             // find vertical EDGEs --- EDGEs shared with neighbor side FACEs
3068             for ( int is2nd = 0; is2nd < 2 && isOK; ++is2nd ) // 2 adjacent neighbors
3069             {
3070               int di = is2nd ? 1 : -1;
3071               const PrismSide* adjSide = is2nd ? side._rightSide : side._leftSide;
3072               for ( size_t i = 1; i < side._edges->size(); ++i )
3073               {
3074                 int iE = SMESH_MesherHelper::WrapIndex( i*di + side._iBotEdge, side._edges->size());
3075                 if ( side._isCheckedEdge[ iE ] ) continue;
3076                 const TopoDS_Edge&      vertE = side.Edge( iE );
3077                 const TopoDS_Shape& neighborF = getAnotherFace( side._face, vertE, facesOfEdge );
3078                 bool isEdgeShared = (( adjSide->IsSideFace( neighborF, side._isInternal )) ||
3079                                      ( adjSide == &side && neighborF.IsSame( side._face )) );
3080                 if ( isEdgeShared ) // vertE is shared with adjSide
3081                 {
3082                   isAdvanced = true;
3083                   side._isCheckedEdge[ iE ] = true;
3084                   side._nbCheckedEdges++;
3085                   int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
3086                   if ( nbNotCheckedE == 1 )
3087                     break;
3088                 }
3089                 else
3090                 {
3091                   if ( i == 1 && iLoop == 0 ) isOK = false;
3092                   break;
3093                 }
3094               }
3095             }
3096             // find a top EDGE
3097             int nbNotCheckedE = side._edges->size() - side._nbCheckedEdges;
3098             if ( nbNotCheckedE == 1 )
3099             {
3100               vector<bool>::iterator ii = std::find( side._isCheckedEdge.begin(),
3101                                                      side._isCheckedEdge.end(), false );
3102               if ( ii != side._isCheckedEdge.end() )
3103               {
3104                 size_t iE = std::distance( side._isCheckedEdge.begin(), ii );
3105                 side._topEdge = side.Edge( iE );
3106               }
3107             }
3108             isOK = ( nbNotCheckedE >= 1 );
3109           }
3110           else //if ( !side._topEdge.IsNull() )
3111           {
3112             // get a next face of a side
3113             const TopoDS_Shape& f = getAnotherFace( side._face, side._topEdge, facesOfEdge );
3114             side._faces->Add( f );
3115             bool stop = false;
3116             if ( f.IsSame( side._face ) || // _topEdge is a seam
3117                  SMESH_MesherHelper::Count( f, TopAbs_WIRE, false ) != 1 )
3118             {
3119               stop = true;
3120             }
3121             else if ( side._leftSide != & side && // not closed side face
3122                       side._leftSide->_faces->Contains( f ))
3123             {
3124               stop = true; // probably f is the prism top face
3125               side._leftSide->_face.Nullify();
3126               side._leftSide->_topEdge.Nullify();
3127             }
3128             else if ( side._rightSide != & side &&
3129                       side._rightSide->_faces->Contains( f ))
3130             {
3131               stop = true; // probably f is the prism top face
3132               side._rightSide->_face.Nullify();
3133               side._rightSide->_topEdge.Nullify();
3134             }
3135             if ( stop )
3136             {
3137               side._face.Nullify();
3138               side._topEdge.Nullify();
3139               continue;
3140             }
3141             side._face  = TopoDS::Face( f );
3142             int faceID  = allFaces.FindIndex( side._face );
3143             side._edges = & faceEdgesVec[ faceID ];
3144             if ( side._edges->empty() )
3145               if ( !getEdges( side._face, * side._edges, facesOfEdge, /*noHoles=*/true ))
3146                 break;
3147             const int nbE = side._edges->size();
3148             if ( nbE >= 4 )
3149             {
3150               isAdvanced = true;
3151               ++nbFoundSideFaces;
3152               side._iBotEdge = side.FindEdge( side._topEdge );
3153               side._isCheckedEdge.clear();
3154               side._isCheckedEdge.resize( nbE, false );
3155               side._isCheckedEdge[ side._iBotEdge ] = true;
3156               side._nbCheckedEdges = 1; // bottom EDGE is known
3157             }
3158             else // probably a triangular top face found
3159             {
3160               side._face.Nullify();
3161             }
3162             side._topEdge.Nullify();
3163             isOK = ( !side._edges->empty() || side._faces->Extent() > 1 );
3164
3165           } //if ( !side._topEdge.IsNull() )
3166
3167         } // loop on prism sides
3168
3169         if ( nbFoundSideFaces > allFaces.Extent() )
3170         {
3171           isOK = false;
3172         }
3173         if ( iLoop > allFaces.Extent() * 10 )
3174         {
3175           isOK = false;
3176 #ifdef _DEBUG_
3177           cerr << "BUG: infinite loop in StdMeshers_Prism_3D::IsApplicable()" << endl;
3178 #endif
3179         }
3180       } // while isAdvanced
3181
3182       if ( isOK && sides[0]._faces->Extent() > 1 )
3183       {
3184         const int nbFaces = sides[0]._faces->Extent();
3185         if ( botEdges.size() == 1 ) // cylinder
3186         {
3187           prismDetected = ( nbFaces == allFaces.Extent()-1 );
3188         }
3189         else
3190         {
3191           const TopoDS_Shape& topFace = sides[0]._faces->FindKey( nbFaces );
3192           size_t iS;
3193           for ( iS = 1; iS < sides.size(); ++iS )
3194             if ( ! sides[ iS ]._faces->Contains( topFace ))
3195               break;
3196           prismDetected = ( iS == sides.size() );
3197         }
3198       }
3199     } // loop on allFaces
3200
3201     if ( !prismDetected && toCheckAll ) return false;
3202     if ( prismDetected && !toCheckAll ) return true;
3203
3204   } // loop on solids
3205
3206   return toCheckAll;
3207 }
3208
3209 namespace Prism_3D
3210 {
3211   //================================================================================
3212   /*!
3213    * \brief Return true if this node and other one belong to one face
3214    */
3215   //================================================================================
3216
3217   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
3218   {
3219     if ( !other.myNode || !myNode ) return false;
3220
3221     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
3222     while ( fIt->more() )
3223       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
3224         return true;
3225     return false;
3226   }
3227
3228   //================================================================================
3229   /*!
3230    * \brief Prism initialization
3231    */
3232   //================================================================================
3233
3234   void TPrismTopo::Clear()
3235   {
3236     myShape3D.Nullify();
3237     myTop.Nullify();
3238     myBottom.Nullify();
3239     myWallQuads.clear();
3240     myBottomEdges.clear();
3241     myNbEdgesInWires.clear();
3242     myWallQuads.clear();
3243   }
3244
3245   //================================================================================
3246   /*!
3247    * \brief Set upside-down
3248    */
3249   //================================================================================
3250
3251   void TPrismTopo::SetUpsideDown()
3252   {
3253     std::swap( myBottom, myTop );
3254     myBottomEdges.clear();
3255     std::reverse( myBottomEdges.begin(), myBottomEdges.end() );
3256     for ( size_t i = 0; i < myWallQuads.size(); ++i )
3257     {
3258       myWallQuads[i].reverse();
3259       TQuadList::iterator q = myWallQuads[i].begin();
3260       for ( ; q != myWallQuads[i].end(); ++q )
3261       {
3262         (*q)->shift( 2, /*keepUnitOri=*/true );
3263       }
3264       myBottomEdges.push_back( myWallQuads[i].front()->side[ QUAD_BOTTOM_SIDE ].grid->Edge(0) );
3265     }
3266   }
3267
3268 } // namespace Prism_3D
3269
3270 //================================================================================
3271 /*!
3272  * \brief Constructor. Initialization is needed
3273  */
3274 //================================================================================
3275
3276 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
3277 {
3278   mySide = 0;
3279 }
3280
3281 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
3282 {
3283   Clear();
3284 }
3285 void StdMeshers_PrismAsBlock::Clear()
3286 {
3287   myHelper = 0;
3288   myShapeIDMap.Clear();
3289   myError.reset();
3290
3291   if ( mySide ) {
3292     delete mySide; mySide = 0;
3293   }
3294   myParam2ColumnMaps.clear();
3295   myShapeIndex2ColumnMap.clear();
3296 }
3297
3298 //=======================================================================
3299 //function : initPrism
3300 //purpose  : Analyse shape geometry and mesh.
3301 //           If there are triangles on one of faces, it becomes 'bottom'.
3302 //           thePrism.myBottom can be already set up.
3303 //=======================================================================
3304
3305 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
3306                                     const TopoDS_Shape&   theShape3D,
3307                                     const bool            selectBottom)
3308 {
3309   myHelper->SetSubShape( theShape3D );
3310
3311   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( theShape3D );
3312   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
3313
3314   // detect not-quad FACE sub-meshes of the 3D SHAPE
3315   list< SMESH_subMesh* > notQuadGeomSubMesh;
3316   list< SMESH_subMesh* > notQuadElemSubMesh;
3317   list< SMESH_subMesh* > meshedSubMesh;
3318   int nbFaces = 0;
3319   //
3320   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
3321   while ( smIt->more() )
3322   {
3323     SMESH_subMesh* sm = smIt->next();
3324     const TopoDS_Shape& face = sm->GetSubShape();
3325     if      ( face.ShapeType() > TopAbs_FACE ) break;
3326     else if ( face.ShapeType() < TopAbs_FACE ) continue;
3327     nbFaces++;
3328
3329     // is quadrangle FACE?
3330     list< TopoDS_Edge > orderedEdges;
3331     list< int >         nbEdgesInWires;
3332     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
3333                                                 nbEdgesInWires );
3334     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
3335       notQuadGeomSubMesh.push_back( sm );
3336
3337     // look for a not structured sub-mesh
3338     if ( !sm->IsEmpty() )
3339     {
3340       meshedSubMesh.push_back( sm );
3341       if ( !myHelper->IsSameElemGeometry( sm->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
3342            !myHelper->IsStructured      ( sm ))
3343         notQuadElemSubMesh.push_back( sm );
3344     }
3345   }
3346
3347   int nbNotQuadMeshed = notQuadElemSubMesh.size();
3348   int       nbNotQuad = notQuadGeomSubMesh.size();
3349   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
3350
3351   // detect bad cases
3352   if ( nbNotQuadMeshed > 2 )
3353   {
3354     return toSM( error(COMPERR_BAD_INPUT_MESH,
3355                        TCom("More than 2 faces with not quadrangle elements: ")
3356                        <<nbNotQuadMeshed));
3357   }
3358   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
3359   {
3360     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
3361     // Remove from notQuadGeomSubMesh faces meshed with regular grid
3362     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
3363                                          TQuadrangleAlgo::instance(this,myHelper) );
3364     nbNotQuad -= nbQuasiQuads;
3365     if ( nbNotQuad > 2 )
3366       return toSM( error(COMPERR_BAD_SHAPE,
3367                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
3368     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
3369   }
3370
3371   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
3372   // If there are not quadrangle FACEs, they are top and bottom ones.
3373   // Not quadrangle FACEs must be only on top and bottom.
3374
3375   SMESH_subMesh * botSM = 0;
3376   SMESH_subMesh * topSM = 0;
3377
3378   if ( hasNotQuad ) // can choose a bottom FACE
3379   {
3380     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
3381     else                       botSM = notQuadGeomSubMesh.front();
3382     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
3383     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
3384
3385     if ( topSM == botSM ) {
3386       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
3387       else                       topSM = notQuadGeomSubMesh.front();
3388     }
3389
3390     // detect mesh triangles on wall FACEs
3391     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
3392       bool ok = false;
3393       if ( nbNotQuadMeshed == 1 )
3394         ok = ( find( notQuadGeomSubMesh.begin(),
3395                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
3396       else
3397         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
3398       if ( !ok )
3399         return toSM( error(COMPERR_BAD_INPUT_MESH,
3400                            "Side face meshed with not quadrangle elements"));
3401     }
3402   }
3403
3404   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
3405
3406   // use thePrism.myBottom
3407   if ( !thePrism.myBottom.IsNull() )
3408   {
3409     if ( botSM ) { // <-- not quad geom or mesh on botSM
3410       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
3411         std::swap( botSM, topSM );
3412         if ( !botSM || ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
3413           if ( !selectBottom )
3414             return toSM( error( COMPERR_BAD_INPUT_MESH,
3415                                 "Incompatible non-structured sub-meshes"));
3416           std::swap( botSM, topSM );
3417           thePrism.myBottom = TopoDS::Face( botSM->GetSubShape() );
3418         }
3419       }
3420     }
3421     else if ( !selectBottom ) {
3422       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
3423     }
3424   }
3425   if ( !botSM ) // find a proper bottom
3426   {
3427     bool savedSetErrorToSM = mySetErrorToSM;
3428     mySetErrorToSM = false; // ignore errors in initPrism()
3429
3430     // search among meshed FACEs
3431     list< SMESH_subMesh* >::iterator sm = meshedSubMesh.begin();
3432     for ( ; !botSM && sm != meshedSubMesh.end(); ++sm )
3433     {
3434       thePrism.Clear();
3435       botSM             = *sm;
3436       thePrism.myBottom = TopoDS::Face( botSM->GetSubShape() );
3437       if ( !initPrism( thePrism, theShape3D, /*selectBottom=*/false ))
3438         botSM = NULL;
3439     }
3440     // search among all FACEs
3441     for ( TopExp_Explorer f( theShape3D, TopAbs_FACE ); !botSM && f.More(); f.Next() )
3442     {
3443       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
3444       if ( nbFaces < minNbFaces) continue;
3445       thePrism.Clear();
3446       thePrism.myBottom = TopoDS::Face( f.Current() );
3447       botSM             = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
3448       if ( !initPrism( thePrism, theShape3D, /*selectBottom=*/false ))
3449         botSM = NULL;
3450     }
3451     mySetErrorToSM = savedSetErrorToSM;
3452     return botSM ? true : toSM( error( COMPERR_BAD_SHAPE ));
3453   }
3454
3455   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
3456   TopoDS_Vertex V000;
3457   double minVal = DBL_MAX, minX = 0, val;
3458   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
3459         exp.More(); exp.Next() )
3460   {
3461     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
3462     gp_Pnt P = BRep_Tool::Pnt( v );
3463     val = P.X() + P.Y() + P.Z();
3464     if ( val < minVal || ( val == minVal && P.X() < minX )) {
3465       V000 = v;
3466       minVal = val;
3467       minX = P.X();
3468     }
3469   }
3470
3471   thePrism.myShape3D = theShape3D;
3472   if ( thePrism.myBottom.IsNull() )
3473     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
3474   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( theShape3D, thePrism.myBottom ));
3475   thePrism.myTop.   Orientation( myHelper->GetSubShapeOri( theShape3D, thePrism.myTop ));
3476
3477   // Get ordered bottom edges
3478   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
3479     TopoDS::Face( thePrism.myBottom.Reversed() );
3480   SMESH_Block::GetOrderedEdges( reverseBottom,
3481                                 thePrism.myBottomEdges,
3482                                 thePrism.myNbEdgesInWires, V000 );
3483
3484   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
3485   if ( !getWallFaces( thePrism, nbFaces )) // it also sets thePrism.myTop
3486     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
3487
3488   if ( topSM )
3489   {
3490     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
3491       return toSM( error
3492                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
3493                     "Non-quadrilateral faces are not opposite"));
3494
3495     // check that the found top and bottom FACEs are opposite
3496     TopTools_IndexedMapOfShape topEdgesMap( thePrism.myBottomEdges.size() );
3497     TopExp::MapShapes( thePrism.myTop, topEdgesMap );
3498     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
3499     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
3500       if ( topEdgesMap.Contains( *edge ))
3501         return toSM( error
3502                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
3503                       "Non-quadrilateral faces are not opposite"));
3504   }
3505
3506   if ( thePrism.myBottomEdges.size() > thePrism.myWallQuads.size() )
3507   {
3508     // composite bottom sides => set thePrism upside-down
3509     thePrism.SetUpsideDown();
3510   }
3511
3512   return true;
3513 }
3514
3515 //================================================================================
3516 /*!
3517  * \brief Initialization.
3518  * \param helper - helper loaded with mesh and 3D shape
3519  * \param thePrism - a prism data
3520  * \retval bool - false if a mesh or a shape are KO
3521  */
3522 //================================================================================
3523
3524 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
3525                                    const Prism_3D::TPrismTopo& thePrism)
3526 {
3527   myHelper = helper;
3528   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
3529   SMESH_Mesh*     mesh = myHelper->GetMesh();
3530
3531   if ( mySide ) {
3532     delete mySide; mySide = 0;
3533   }
3534   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
3535   vector< pair< double, double> > params( NB_WALL_FACES );
3536   mySide = new TSideFace( *mesh, sideFaces, params );
3537
3538
3539   SMESH_Block::init();
3540   myShapeIDMap.Clear();
3541   myShapeIndex2ColumnMap.clear();
3542   
3543   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
3544     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
3545     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
3546   };
3547
3548   myError = SMESH_ComputeError::New();
3549
3550   myNotQuadOnTop = thePrism.myNotQuadOnTop;
3551
3552   // Find columns of wall nodes and calculate edges' lengths
3553   // --------------------------------------------------------
3554
3555   myParam2ColumnMaps.clear();
3556   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
3557
3558   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
3559   vector< double > edgeLength( nbEdges );
3560   multimap< double, int > len2edgeMap;
3561
3562   // for each EDGE: either split into several parts, or join with several next EDGEs
3563   vector<int> nbSplitPerEdge( nbEdges, 0 );
3564   vector<int> nbUnitePerEdge( nbEdges, 0 ); // -1 means "joined to a previous"
3565
3566   // consider continuous straight EDGEs as one side
3567   const int nbSides = countNbSides( thePrism, nbUnitePerEdge, edgeLength );
3568
3569   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
3570   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
3571   {
3572     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
3573
3574     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
3575     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
3576     {
3577       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
3578       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
3579         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
3580                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
3581     }
3582     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
3583     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
3584     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
3585
3586     if ( nbSides < NB_WALL_FACES ) // fill map used to split faces
3587       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE )); // sort edges by length
3588   }
3589   // Load columns of internal edges (forming holes)
3590   // and fill map ShapeIndex to TParam2ColumnMap for them
3591   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
3592   {
3593     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
3594
3595     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
3596     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
3597     {
3598       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ].grid->Edge( 0 );
3599       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
3600         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
3601                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
3602     }
3603     if ( !faceColumns.empty() && (int)faceColumns.begin()->second.size() != VerticalSize() )
3604       return error(COMPERR_BAD_INPUT_MESH, "Different 'vertical' discretization");
3605
3606     // edge columns
3607     int id = MeshDS()->ShapeToIndex( *edgeIt );
3608     bool isForward = true; // meaningless for intenal wires
3609     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3610     // columns for vertices
3611     // 1
3612     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
3613     id = n0->getshapeId();
3614     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3615     // 2
3616     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
3617     id = n1->getshapeId();
3618     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
3619
3620     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
3621     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
3622     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
3623   }
3624
3625   // Create 4 wall faces of a block
3626   // -------------------------------
3627
3628   if ( nbSides <= NB_WALL_FACES ) // ************* Split faces if necessary
3629   {
3630     if ( nbSides != NB_WALL_FACES ) // define how to split
3631     {
3632       if ( len2edgeMap.size() != nbEdges )
3633         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
3634
3635       multimap< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
3636       multimap< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
3637
3638       double maxLen = maxLen_i->first;
3639       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
3640       switch ( nbEdges ) {
3641       case 1: // 0-th edge is split into 4 parts
3642         nbSplitPerEdge[ 0 ] = 4;
3643         break;
3644       case 2: // either the longest edge is split into 3 parts, or both edges into halves
3645         if ( maxLen / 3 > midLen / 2 ) {
3646           nbSplitPerEdge[ maxLen_i->second ] = 3;
3647         }
3648         else {
3649           nbSplitPerEdge[ maxLen_i->second ] = 2;
3650           nbSplitPerEdge[ midLen_i->second ] = 2;
3651         }
3652         break;
3653       case 3:
3654         if ( nbSides == 2 )
3655           // split longest into 3 parts
3656           nbSplitPerEdge[ maxLen_i->second ] = 3;
3657         else
3658           // split longest into halves
3659           nbSplitPerEdge[ maxLen_i->second ] = 2;
3660       }
3661     }
3662   }
3663   else // **************************** Unite faces
3664   {
3665     int nbExraFaces = nbSides - 4; // nb of faces to fuse
3666     for ( iE = 0; iE < nbEdges; ++iE )
3667     {
3668       if ( nbUnitePerEdge[ iE ] < 0 )
3669         continue;
3670       // look for already united faces
3671       for ( size_t i = iE; i < iE + nbExraFaces; ++i )
3672       {
3673         if ( nbUnitePerEdge[ i ] > 0 ) // a side including nbUnitePerEdge[i]+1 edge
3674           nbExraFaces += nbUnitePerEdge[ i ];
3675         nbUnitePerEdge[ i ] = -1;
3676       }
3677       nbUnitePerEdge[ iE ] = nbExraFaces;
3678       break;
3679     }
3680   }
3681
3682   // Create TSideFace's
3683   int iSide = 0;
3684   list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
3685   for ( iE = 0; iE < nbEdges; ++iE, ++botE )
3686   {
3687     TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
3688     const int       nbSplit = nbSplitPerEdge[ iE ];
3689     const int   nbExraFaces = nbUnitePerEdge[ iE ] + 1;
3690     if ( nbSplit > 0 ) // split
3691     {
3692       vector< double > params;
3693       splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
3694       const bool isForward =
3695         StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
3696                                                 myParam2ColumnMaps[iE],
3697                                                 *botE, SMESH_Block::ID_Fx0z );
3698       for ( int i = 0; i < nbSplit; ++i ) {
3699         double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
3700         double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
3701         TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
3702                                          thePrism.myWallQuads[ iE ], *botE,
3703                                          &myParam2ColumnMaps[ iE ], f, l );
3704         mySide->SetComponent( iSide++, comp );
3705       }
3706     }
3707     else if ( nbExraFaces > 1 ) // unite
3708     {
3709       double u0 = 0, sumLen = 0;
3710       for ( size_t i = iE; i < iE + nbExraFaces; ++i )
3711         sumLen += edgeLength[ i ];
3712
3713       vector< TSideFace* >        components( nbExraFaces );
3714       vector< pair< double, double> > params( nbExraFaces );
3715       bool endReached = false;
3716       for ( int i = 0; i < nbExraFaces; ++i, ++botE, ++iE )
3717       {
3718         if ( iE == nbEdges )
3719         {
3720           endReached = true;
3721           botE = thePrism.myBottomEdges.begin();
3722           iE = 0;
3723         }
3724         components[ i ] = new TSideFace( *mesh, wallFaceIds[ iSide ],
3725                                          thePrism.myWallQuads[ iE ], *botE,
3726                                          &myParam2ColumnMaps[ iE ]);
3727         double u1 = u0 + edgeLength[ iE ] / sumLen;
3728         params[ i ] = make_pair( u0 , u1 );
3729         u0 = u1;
3730       }
3731       TSideFace* comp = new TSideFace( *mesh, components, params );
3732       mySide->SetComponent( iSide++, comp );
3733       if ( endReached )
3734         break;
3735       --iE; // for increment in an external loop on iE
3736       --botE;
3737     }
3738     else if ( nbExraFaces < 0 ) // skip already united face
3739     {
3740     }
3741     else // use as is
3742     {
3743       TSideFace* comp = new TSideFace( *mesh, wallFaceIds[ iSide ],
3744                                        thePrism.myWallQuads[ iE ], *botE,
3745                                        &myParam2ColumnMaps[ iE ]);
3746       mySide->SetComponent( iSide++, comp );
3747     }
3748   }
3749
3750
3751   // Fill geometry fields of SMESH_Block
3752   // ------------------------------------
3753
3754   vector< int > botEdgeIdVec;
3755   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
3756
3757   bool isForward[NB_WALL_FACES] = { true, true, true, true };
3758   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
3759   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
3760
3761   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
3762   {
3763     TSideFace * sideFace = mySide->GetComponent( iF );
3764     if ( !sideFace )
3765       RETURN_BAD_RESULT("NULL TSideFace");
3766     int fID = sideFace->FaceID(); // in-block ID
3767
3768     // fill myShapeIDMap
3769     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
3770          !sideFace->IsComplex())
3771       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
3772
3773     // side faces geometry
3774     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
3775     if ( !sideFace->GetPCurves( pcurves ))
3776       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
3777
3778     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
3779     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
3780
3781     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
3782     // edges 3D geometry
3783     vector< int > edgeIdVec;
3784     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
3785     for ( int isMax = 0; isMax < 2; ++isMax ) {
3786       {
3787         int eID = edgeIdVec[ isMax ];
3788         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
3789         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
3790         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
3791         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
3792       }
3793       {
3794         int eID = edgeIdVec[ isMax+2 ];
3795         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
3796         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
3797         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
3798         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
3799
3800         // corner points
3801         vector< int > vertexIdVec;
3802         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
3803         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
3804         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
3805       }
3806     }
3807     // pcurves on horizontal faces
3808     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
3809       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
3810         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
3811         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
3812         break;
3813       }
3814     }
3815     //sideFace->dumpNodes( 4 ); // debug
3816   }
3817   // horizontal faces geometry
3818   {
3819     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
3820     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
3821     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
3822   }
3823   {
3824     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
3825     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
3826     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
3827   }
3828   //faceGridToPythonDump( SMESH_Block::ID_Fxy0, 50 );
3829   //faceGridToPythonDump( SMESH_Block::ID_Fxy1 );
3830
3831   // Fill map ShapeIndex to TParam2ColumnMap
3832   // ----------------------------------------
3833
3834   list< TSideFace* > fList;
3835   list< TSideFace* >::iterator fListIt;
3836   fList.push_back( mySide );
3837   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
3838   {
3839     int nb = (*fListIt)->NbComponents();
3840     for ( int i = 0; i < nb; ++i ) {
3841       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
3842         fList.push_back( comp );
3843     }
3844     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
3845       // columns for a base edge
3846       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
3847       bool isForward = (*fListIt)->IsForward();
3848       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3849
3850       // columns for vertices
3851       const SMDS_MeshNode* n0 = cols->begin()->second.front();
3852       id = n0->getshapeId();
3853       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
3854
3855       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
3856       id = n1->getshapeId();
3857       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
3858     }
3859   }
3860
3861 // #define SHOWYXZ(msg, xyz) { gp_Pnt p(xyz); cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl; }
3862
3863 //   double _u[]={ 0.1, 0.1, 0.9, 0.9 };
3864 //   double _v[]={ 0.1, 0.9, 0.1, 0.9 };
3865 //   for ( int z = 0; z < 2; ++z )
3866 //     for ( int i = 0; i < 4; ++i )
3867 //     {
3868 //       //gp_XYZ testPar(0.25, 0.25, 0), testCoord;
3869 //       int iFace = (z ? ID_TOP_FACE : ID_BOT_FACE);
3870 //       gp_XYZ testPar(_u[i], _v[i], z), testCoord;
3871 //       if ( !FacePoint( iFace, testPar, testCoord ))
3872 //         RETURN_BAD_RESULT("TEST FacePoint() FAILED");
3873 //       SHOWYXZ("IN TEST PARAM" , testPar);
3874 //       SHOWYXZ("OUT TEST CORD" , testCoord);
3875 //       if ( !ComputeParameters( testCoord, testPar , iFace))
3876 //         RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
3877 //       SHOWYXZ("OUT TEST PARAM" , testPar);
3878 //     }
3879   return true;
3880 }
3881
3882 //================================================================================
3883 /*!
3884  * \brief Return pointer to column of nodes
3885  * \param node - bottom node from which the returned column goes up
3886  * \retval const TNodeColumn* - the found column
3887  */
3888 //================================================================================
3889
3890 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
3891 {
3892   int sID = node->getshapeId();
3893
3894   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
3895     myShapeIndex2ColumnMap.find( sID );
3896   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
3897     const TParam2ColumnMap* cols = col_frw->second.first;
3898     TParam2ColumnIt u_col = cols->begin();
3899     for ( ; u_col != cols->end(); ++u_col )
3900       if ( u_col->second[ 0 ] == node )
3901         return & u_col->second;
3902   }
3903   return 0;
3904 }
3905
3906 //=======================================================================
3907 //function : GetLayersTransformation
3908 //purpose  : Return transformations to get coordinates of nodes of each layer
3909 //           by nodes of the bottom. Layer is a set of nodes at a certain step
3910 //           from bottom to top.
3911 //           Transformation to get top node from bottom ones is computed
3912 //           only if the top FACE is not meshed.
3913 //=======================================================================
3914
3915 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> &           trsf,
3916                                                       const Prism_3D::TPrismTopo& prism) const
3917 {
3918   const bool itTopMeshed = !SubMesh( ID_BOT_FACE )->IsEmpty();
3919   const int zSize = VerticalSize();
3920   if ( zSize < 3 && !itTopMeshed ) return true;
3921   trsf.resize( zSize - 1 );
3922
3923   // Select some node columns by which we will define coordinate system of layers
3924
3925   vector< const TNodeColumn* > columns;
3926   {
3927     bool isReverse;
3928     list< TopoDS_Edge >::const_iterator edgeIt = prism.myBottomEdges.begin();
3929     for ( int iE = 0; iE < prism.myNbEdgesInWires.front(); ++iE, ++edgeIt )
3930     {
3931       if ( SMESH_Algo::isDegenerated( *edgeIt )) continue;
3932       const TParam2ColumnMap* u2colMap =
3933         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
3934       if ( !u2colMap ) return false;
3935       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
3936       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
3937       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
3938       const int nbCol = 5;
3939       for ( int i = 0; i < nbCol; ++i )
3940       {
3941         double u = f + i/double(nbCol) * ( l - f );
3942         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
3943         if ( columns.empty() || col != columns.back() )
3944           columns.push_back( col );
3945       }
3946     }
3947   }
3948
3949   // Find tolerance to check transformations
3950
3951   double tol2;
3952   {
3953     Bnd_B3d bndBox;
3954     for ( size_t i = 0; i < columns.size(); ++i )
3955       bndBox.Add( gpXYZ( columns[i]->front() ));
3956     tol2 = bndBox.SquareExtent() * 1e-5;
3957   }
3958
3959   // Compute transformations
3960
3961   int xCol = -1;
3962   gp_Trsf fromCsZ, toCs0;
3963   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
3964   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
3965   toCs0.SetTransformation( cs0 );
3966   for ( int z = 1; z < zSize; ++z )
3967   {
3968     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
3969     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
3970     fromCsZ.SetTransformation( csZ );
3971     fromCsZ.Invert();
3972     gp_Trsf& t = trsf[ z-1 ];
3973     t = fromCsZ * toCs0;
3974     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
3975
3976     // check a transformation
3977     for ( size_t i = 0; i < columns.size(); ++i )
3978     {
3979       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
3980       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
3981       t.Transforms( p0.ChangeCoord() );
3982       if ( p0.SquareDistance( pz ) > tol2 )
3983       {
3984         t = gp_Trsf();
3985         return ( z == zSize - 1 ); // OK if fails only botton->top trsf
3986       }
3987     }
3988   }
3989   return true;
3990 }
3991
3992 //================================================================================
3993 /*!
3994  * \brief Check curve orientation of a bootom edge
3995   * \param meshDS - mesh DS
3996   * \param columnsMap - node columns map of side face
3997   * \param bottomEdge - the bootom edge
3998   * \param sideFaceID - side face in-block ID
3999   * \retval bool - true if orientation coinside with in-block forward orientation
4000  */
4001 //================================================================================
4002
4003 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
4004                                             const TParam2ColumnMap& columnsMap,
4005                                             const TopoDS_Edge &     bottomEdge,
4006                                             const int               sideFaceID)
4007 {
4008   bool isForward = false;
4009   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
4010   {
4011     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
4012   }
4013   else
4014   {
4015     const TNodeColumn&     firstCol = columnsMap.begin()->second;
4016     const SMDS_MeshNode* bottomNode = firstCol[0];
4017     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
4018     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
4019   }
4020   // on 2 of 4 sides first vertex is end
4021   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
4022     isForward = !isForward;
4023   return isForward;
4024 }
4025
4026 //=======================================================================
4027 //function : faceGridToPythonDump
4028 //purpose  : Prints a script creating a normal grid on the prism side
4029 //=======================================================================
4030
4031 void StdMeshers_PrismAsBlock::faceGridToPythonDump(const SMESH_Block::TShapeID face,
4032                                                    const int                   nb)
4033 {
4034 #ifdef _DEBUG_
4035   gp_XYZ pOnF[6] = { gp_XYZ(0,0,0), gp_XYZ(0,0,1),
4036                      gp_XYZ(0,0,0), gp_XYZ(0,1,0),
4037                      gp_XYZ(0,0,0), gp_XYZ(1,0,0) };
4038   gp_XYZ p2;
4039   cout << "mesh = smesh.Mesh( 'Face " << face << "')" << endl;
4040   SMESH_Block::TFace& f = myFace[ face - ID_FirstF ];
4041   gp_XYZ params = pOnF[ face - ID_FirstF ];
4042   //const int nb = 10; // nb face rows
4043   for ( int j = 0; j <= nb; ++j )
4044   {
4045     params.SetCoord( f.GetVInd(), double( j )/ nb );
4046     for ( int i = 0; i <= nb; ++i )
4047     {
4048       params.SetCoord( f.GetUInd(), double( i )/ nb );
4049       gp_XYZ p = f.Point( params );
4050       gp_XY uv = f.GetUV( params );
4051       cout << "mesh.AddNode( " << p.X() << ", " << p.Y() << ", " << p.Z() << " )"
4052            << " # " << 1 + i + j * ( nb + 1 )
4053            << " ( " << i << ", " << j << " ) "
4054            << " UV( " << uv.X() << ", " << uv.Y() << " )" << endl;
4055       ShellPoint( params, p2 );
4056       double dist = ( p2 - p ).Modulus();
4057       if ( dist > 1e-4 )
4058         cout << "#### dist from ShellPoint " << dist
4059              << " (" << p2.X() << ", " << p2.Y() << ", " << p2.Z() << " ) " << endl;
4060     }
4061   }
4062   for ( int j = 0; j < nb; ++j )
4063     for ( int i = 0; i < nb; ++i )
4064     {
4065       int n = 1 + i + j * ( nb + 1 );
4066       cout << "mesh.AddFace([ "
4067            << n << ", " << n+1 << ", "
4068            << n+nb+2 << ", " << n+nb+1 << "]) " << endl;
4069     }
4070   
4071 #endif
4072 }
4073
4074 //================================================================================
4075 /*!
4076  * \brief Constructor
4077   * \param faceID - in-block ID
4078   * \param face - geom FACE
4079   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
4080   * \param columnsMap - map of node columns
4081   * \param first - first normalized param
4082   * \param last - last normalized param
4083  */
4084 //================================================================================
4085
4086 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_Mesh&                mesh,
4087                                               const int                  faceID,
4088                                               const Prism_3D::TQuadList& quadList,
4089                                               const TopoDS_Edge&         baseEdge,
4090                                               TParam2ColumnMap*          columnsMap,
4091                                               const double               first,
4092                                               const double               last):
4093   myID( faceID ),
4094   myParamToColumnMap( columnsMap ),
4095   myHelper( mesh )
4096 {
4097   myParams.resize( 1 );
4098   myParams[ 0 ] = make_pair( first, last );
4099   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
4100   myBaseEdge    = baseEdge;
4101   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper.GetMeshDS(),
4102                                                           *myParamToColumnMap,
4103                                                           myBaseEdge, myID );
4104   myHelper.SetSubShape( quadList.front()->face );
4105
4106   if ( quadList.size() > 1 ) // side is vertically composite
4107   {
4108     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
4109
4110     SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
4111
4112     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
4113     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
4114     for ( ; quad != quadList.end(); ++quad )
4115     {
4116       const TopoDS_Face& face = (*quad)->face;
4117       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
4118       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
4119       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
4120                                         PSurface( new BRepAdaptor_Surface( face ))));
4121     }
4122     for ( int i = 1; i <= subToFaces.Extent(); ++i )
4123     {
4124       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
4125       TopTools_ListOfShape& faces = subToFaces( i );
4126       int subID  = meshDS->ShapeToIndex( sub );
4127       int faceID = meshDS->ShapeToIndex( faces.First() );
4128       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
4129     }
4130   }
4131 }
4132
4133 //================================================================================
4134 /*!
4135  * \brief Constructor of a complex side face
4136  */
4137 //================================================================================
4138
4139 StdMeshers_PrismAsBlock::TSideFace::
4140 TSideFace(SMESH_Mesh&                             mesh,
4141           const vector< TSideFace* >&             components,
4142           const vector< pair< double, double> > & params)
4143   :myID( components[0] ? components[0]->myID : 0 ),
4144    myParamToColumnMap( 0 ),
4145    myParams( params ),
4146    myIsForward( true ),
4147    myComponents( components ),
4148    myHelper( mesh )
4149 {
4150   if ( myID == ID_Fx1z || myID == ID_F0yz )
4151   {
4152     // reverse components
4153     std::reverse( myComponents.begin(), myComponents.end() );
4154     std::reverse( myParams.begin(),     myParams.end() );
4155     for ( size_t i = 0; i < myParams.size(); ++i )
4156     {
4157       const double f = myParams[i].first;
4158       const double l = myParams[i].second;
4159       myParams[i] = make_pair( 1. - l, 1. - f );
4160     }
4161   }
4162 }
4163 //================================================================================
4164 /*!
4165  * \brief Copy constructor
4166   * \param other - other side
4167  */
4168 //================================================================================
4169
4170 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other ):
4171   myID               ( other.myID ),
4172   myParamToColumnMap ( other.myParamToColumnMap ),
4173   mySurface          ( other.mySurface ),
4174   myBaseEdge         ( other.myBaseEdge ),
4175   myShapeID2Surf     ( other.myShapeID2Surf ),
4176   myParams           ( other.myParams ),
4177   myIsForward        ( other.myIsForward ),
4178   myComponents       ( other.myComponents.size() ),
4179   myHelper           ( *other.myHelper.GetMesh() )
4180 {
4181   for ( size_t i = 0 ; i < myComponents.size(); ++i )
4182     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
4183 }
4184
4185 //================================================================================
4186 /*!
4187  * \brief Deletes myComponents
4188  */
4189 //================================================================================
4190
4191 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
4192 {
4193   for ( size_t i = 0 ; i < myComponents.size(); ++i )
4194     if ( myComponents[ i ] )
4195       delete myComponents[ i ];
4196 }
4197
4198 //================================================================================
4199 /*!
4200  * \brief Return geometry of the vertical curve
4201   * \param isMax - true means curve located closer to (1,1,1) block point
4202   * \retval Adaptor3d_Curve* - curve adaptor
4203  */
4204 //================================================================================
4205
4206 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
4207 {
4208   if ( !myComponents.empty() ) {
4209     if ( isMax )
4210       return myComponents.back()->VertiCurve(isMax);
4211     else
4212       return myComponents.front()->VertiCurve(isMax);
4213   }
4214   double f = myParams[0].first, l = myParams[0].second;
4215   if ( !myIsForward ) std::swap( f, l );
4216   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
4217 }
4218
4219 //================================================================================
4220 /*!
4221  * \brief Return geometry of the top or bottom curve
4222   * \param isTop - 
4223   * \retval Adaptor3d_Curve* - 
4224  */
4225 //================================================================================
4226
4227 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
4228 {
4229   return new THorizontalEdgeAdaptor( this, isTop );
4230 }
4231
4232 //================================================================================
4233 /*!
4234  * \brief Return pcurves
4235   * \param pcurv - array of 4 pcurves
4236   * \retval bool - is a success
4237  */
4238 //================================================================================
4239
4240 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
4241 {
4242   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
4243
4244   for ( int i = 0 ; i < 4 ; ++i ) {
4245     Handle(Geom2d_Line) line;
4246     switch ( iEdge[ i ] ) {
4247     case TOP_EDGE:
4248       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
4249     case BOTTOM_EDGE:
4250       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
4251     case V0_EDGE:
4252       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
4253     case V1_EDGE:
4254       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
4255     }
4256     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
4257   }
4258   return true;
4259 }
4260
4261 //================================================================================
4262 /*!
4263  * \brief Returns geometry of pcurve on a horizontal face
4264   * \param isTop - is top or bottom face
4265   * \param horFace - a horizontal face
4266   * \retval Adaptor2d_Curve2d* - curve adaptor
4267  */
4268 //================================================================================
4269
4270 Adaptor2d_Curve2d*
4271 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
4272                                                 const TopoDS_Face& horFace) const
4273 {
4274   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
4275 }
4276
4277 //================================================================================
4278 /*!
4279  * \brief Return a component corresponding to parameter
4280   * \param U - parameter along a horizontal size
4281   * \param localU - parameter along a horizontal size of a component
4282   * \retval TSideFace* - found component
4283  */
4284 //================================================================================
4285
4286 StdMeshers_PrismAsBlock::TSideFace*
4287 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
4288 {
4289   localU = U;
4290   if ( myComponents.empty() )
4291     return const_cast<TSideFace*>( this );
4292
4293   size_t i;
4294   for ( i = 0; i < myComponents.size(); ++i )
4295     if ( U < myParams[ i ].second )
4296       break;
4297   if ( i >= myComponents.size() )
4298     i = myComponents.size() - 1;
4299
4300   double f = myParams[ i ].first, l = myParams[ i ].second;
4301   localU = ( U - f ) / ( l - f );
4302   return myComponents[ i ];
4303 }
4304
4305 //================================================================================
4306 /*!
4307  * \brief Find node columns for a parameter
4308   * \param U - parameter along a horizontal edge
4309   * \param col1 - the 1st found column
4310   * \param col2 - the 2nd found column
4311   * \retval r - normalized position of U between the found columns
4312  */
4313 //================================================================================
4314
4315 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
4316                                                       TParam2ColumnIt & col1,
4317                                                       TParam2ColumnIt & col2) const
4318 {
4319   double u = U, r = 0;
4320   if ( !myComponents.empty() ) {
4321     TSideFace * comp = GetComponent(U,u);
4322     return comp->GetColumns( u, col1, col2 );
4323   }
4324
4325   if ( !myIsForward )
4326     u = 1 - u;
4327   double f = myParams[0].first, l = myParams[0].second;
4328   u = f + u * ( l - f );
4329
4330   col1 = col2 = getColumn( myParamToColumnMap, u );
4331   if ( ++col2 == myParamToColumnMap->end() ) {
4332     --col2;
4333     r = 0.5;
4334   }
4335   else {
4336     double uf = col1->first;
4337     double ul = col2->first;
4338     r = ( u - uf ) / ( ul - uf );
4339   }
4340   return r;
4341 }
4342
4343 //================================================================================
4344 /*!
4345  * \brief Return all nodes at a given height together with their normalized parameters
4346  *  \param [in] Z - the height of interest
4347  *  \param [out] nodes - map of parameter to node
4348  */
4349 //================================================================================
4350
4351 void StdMeshers_PrismAsBlock::
4352 TSideFace::GetNodesAtZ(const int Z,
4353                        map<double, const SMDS_MeshNode* >& nodes ) const
4354 {
4355   if ( !myComponents.empty() )
4356   {
4357     double u0 = 0.;
4358     for ( size_t i = 0; i < myComponents.size(); ++i )
4359     {
4360       map<double, const SMDS_MeshNode* > nn;
4361       myComponents[i]->GetNodesAtZ( Z, nn );
4362       map<double, const SMDS_MeshNode* >::iterator u2n = nn.begin();
4363       if ( !nodes.empty() && nodes.rbegin()->second == u2n->second )
4364         ++u2n;
4365       const double uRange = myParams[i].second - myParams[i].first;
4366       for ( ; u2n != nn.end(); ++u2n )
4367         nodes.insert( nodes.end(), make_pair( u0 + uRange * u2n->first, u2n->second ));
4368       u0 += uRange;
4369     }
4370   }
4371   else
4372   {
4373     double f = myParams[0].first, l = myParams[0].second;
4374     if ( !myIsForward )
4375       std::swap( f, l );
4376     const double uRange = l - f;
4377     if ( Abs( uRange ) < std::numeric_limits<double>::min() )
4378       return;
4379     TParam2ColumnIt u2col = getColumn( myParamToColumnMap, myParams[0].first + 1e-3 );
4380     for ( ; u2col != myParamToColumnMap->end(); ++u2col )
4381       if ( u2col->first > myParams[0].second + 1e-9 )
4382         break;
4383       else
4384         nodes.insert( nodes.end(),
4385                       make_pair( ( u2col->first - f ) / uRange, u2col->second[ Z ] ));
4386   }
4387 }
4388
4389 //================================================================================
4390 /*!
4391  * \brief Return coordinates by normalized params
4392   * \param U - horizontal param
4393   * \param V - vertical param
4394   * \retval gp_Pnt - result point
4395  */
4396 //================================================================================
4397
4398 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
4399                                                  const Standard_Real V) const
4400 {
4401   if ( !myComponents.empty() ) {
4402     double u;
4403     TSideFace * comp = GetComponent(U,u);
4404     return comp->Value( u, V );
4405   }
4406
4407   TParam2ColumnIt u_col1, u_col2;
4408   double vR, hR = GetColumns( U, u_col1, u_col2 );
4409
4410   const SMDS_MeshNode* nn[4];
4411
4412   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
4413   // Workaround for a wrongly located point returned by mySurface.Value() for
4414   // UV located near boundary of BSpline surface.
4415   // To bypass the problem, we take point from 3D curve of EDGE.
4416   // It solves pb of the bloc_fiss_new.py
4417   const double tol = 1e-3;
4418   if ( V < tol || V+tol >= 1. )
4419   {
4420     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
4421     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
4422     TopoDS_Edge edge;
4423     if ( V < tol )
4424     {
4425       edge = myBaseEdge;
4426     }
4427     else
4428     {
4429       TopoDS_Shape s = myHelper.GetSubShapeByNode( nn[0], myHelper.GetMeshDS() );
4430       if ( s.ShapeType() != TopAbs_EDGE )
4431         s = myHelper.GetSubShapeByNode( nn[2], myHelper.GetMeshDS() );
4432       if ( !s.IsNull() && s.ShapeType() == TopAbs_EDGE )
4433         edge = TopoDS::Edge( s );
4434     }
4435     if ( !edge.IsNull() )
4436     {
4437       double u1 = myHelper.GetNodeU( edge, nn[0], nn[2] );
4438       double u3 = myHelper.GetNodeU( edge, nn[2], nn[0] );
4439       double u = u1 * ( 1 - hR ) + u3 * hR;
4440       TopLoc_Location loc; double f,l;
4441       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
4442       return curve->Value( u ).Transformed( loc );
4443     }
4444   }
4445   // END issue 0020680: Bad cell created by Radial prism in center of torus
4446
4447   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
4448   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
4449
4450   if ( !myShapeID2Surf.empty() ) // side is vertically composite
4451   {
4452     // find a FACE on which the 4 nodes lie
4453     TSideFace* me = (TSideFace*) this;
4454     int notFaceID1 = 0, notFaceID2 = 0;
4455     for ( int i = 0; i < 4; ++i )
4456       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
4457       {
4458         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
4459         notFaceID2 = 0;
4460         break;
4461       }
4462       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
4463       {
4464         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
4465         notFaceID1 = nn[i]->getshapeId();
4466       }
4467       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
4468       {
4469         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
4470           notFaceID2 = nn[i]->getshapeId();
4471       }
4472     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
4473     {
4474       SMESHDS_Mesh* meshDS = myHelper.GetMeshDS();
4475       TopoDS_Shape face = myHelper.GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
4476                                                        meshDS->IndexToShape( notFaceID2 ),
4477                                                        *myHelper.GetMesh(),
4478                                                        TopAbs_FACE );
4479       if ( face.IsNull() ) 
4480         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
4481       int faceID = meshDS->ShapeToIndex( face );
4482       me->mySurface = me->myShapeID2Surf[ faceID ];
4483       if ( !mySurface )
4484         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
4485     }
4486   }
4487   ((TSideFace*) this)->myHelper.SetSubShape( mySurface->Face() );
4488
4489   gp_XY uv1 = myHelper.GetNodeUV( mySurface->Face(), nn[0], nn[2]);
4490   gp_XY uv2 = myHelper.GetNodeUV( mySurface->Face(), nn[1], nn[3]);
4491   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
4492
4493   gp_XY uv3 = myHelper.GetNodeUV( mySurface->Face(), nn[2], nn[0]);
4494   gp_XY uv4 = myHelper.GetNodeUV( mySurface->Face(), nn[3], nn[1]);
4495   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
4496
4497   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
4498
4499   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
4500   return p;
4501 }
4502
4503
4504 //================================================================================
4505 /*!
4506  * \brief Return boundary edge
4507   * \param edge - edge index
4508   * \retval TopoDS_Edge - found edge
4509  */
4510 //================================================================================
4511
4512 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
4513 {
4514   if ( !myComponents.empty() ) {
4515     switch ( iEdge ) {
4516     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
4517     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
4518     default: return TopoDS_Edge();
4519     }
4520   }
4521   TopoDS_Shape edge;
4522   const SMDS_MeshNode* node = 0;
4523   SMESHDS_Mesh * meshDS = myHelper.GetMesh()->GetMeshDS();
4524   TNodeColumn* column;
4525
4526   switch ( iEdge ) {
4527   case TOP_EDGE:
4528   case BOTTOM_EDGE:
4529     column = & (( ++myParamToColumnMap->begin())->second );
4530     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
4531     edge = myHelper.GetSubShapeByNode ( node, meshDS );
4532     if ( edge.ShapeType() == TopAbs_VERTEX ) {
4533       column = & ( myParamToColumnMap->begin()->second );
4534       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
4535     }
4536     break;
4537   case V0_EDGE:
4538   case V1_EDGE: {
4539     bool back = ( iEdge == V1_EDGE );
4540     if ( !myIsForward ) back = !back;
4541     if ( back )
4542       column = & ( myParamToColumnMap->rbegin()->second );
4543     else
4544       column = & ( myParamToColumnMap->begin()->second );
4545     if ( column->size() > 0 )
4546       edge = myHelper.GetSubShapeByNode( (*column)[ 1 ], meshDS );
4547     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
4548       node = column->front();
4549     break;
4550   }
4551   default:;
4552   }
4553   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
4554     return TopoDS::Edge( edge );
4555
4556   // find edge by 2 vertices
4557   TopoDS_Shape V1 = edge;
4558   TopoDS_Shape V2 = myHelper.GetSubShapeByNode( node, meshDS );
4559   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
4560   {
4561     TopoDS_Shape ancestor = myHelper.GetCommonAncestor( V1, V2, *myHelper.GetMesh(), TopAbs_EDGE);
4562     if ( !ancestor.IsNull() )
4563       return TopoDS::Edge( ancestor );
4564   }
4565   return TopoDS_Edge();
4566 }
4567
4568 //================================================================================
4569 /*!
4570  * \brief Fill block sub-shapes
4571   * \param shapeMap - map to fill in
4572   * \retval int - nb inserted sub-shapes
4573  */
4574 //================================================================================
4575
4576 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
4577 {
4578   int nbInserted = 0;
4579
4580   // Insert edges
4581   vector< int > edgeIdVec;
4582   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
4583
4584   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
4585     TopoDS_Edge e = GetEdge( i );
4586     if ( !e.IsNull() ) {
4587       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
4588     }
4589   }
4590
4591   // Insert corner vertices
4592
4593   TParam2ColumnIt col1, col2 ;
4594   vector< int > vertIdVec;
4595
4596   // from V0 column
4597   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
4598   GetColumns(0, col1, col2 );
4599   const SMDS_MeshNode* node0 = col1->second.front();
4600   const SMDS_MeshNode* node1 = col1->second.back();
4601   TopoDS_Shape v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
4602   TopoDS_Shape v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
4603   if ( v0.ShapeType() == TopAbs_VERTEX ) {
4604     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
4605   }
4606   if ( v1.ShapeType() == TopAbs_VERTEX ) {
4607     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
4608   }
4609   
4610   // from V1 column
4611   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
4612   GetColumns(1, col1, col2 );
4613   node0 = col2->second.front();
4614   node1 = col2->second.back();
4615   v0 = myHelper.GetSubShapeByNode( node0, myHelper.GetMeshDS());
4616   v1 = myHelper.GetSubShapeByNode( node1, myHelper.GetMeshDS());
4617   if ( v0.ShapeType() == TopAbs_VERTEX ) {
4618     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
4619   }
4620   if ( v1.ShapeType() == TopAbs_VERTEX ) {
4621     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
4622   }
4623
4624 //   TopoDS_Vertex V0, V1, Vcom;
4625 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
4626 //   if ( !myIsForward ) std::swap( V0, V1 );
4627
4628 //   // bottom vertex IDs
4629 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
4630 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
4631 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
4632
4633 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
4634 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
4635 //     return false;
4636
4637 //   // insert one side edge
4638 //   int edgeID;
4639 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
4640 //   else                    edgeID = edgeIdVec[ _v1 ];
4641 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
4642
4643 //   // top vertex of the side edge
4644 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
4645 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
4646 //   if ( Vcom.IsSame( Vtop ))
4647 //     Vtop = TopExp::LastVertex( sideEdge );
4648 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
4649
4650 //   // other side edge
4651 //   sideEdge = GetEdge( V1_EDGE );
4652 //   if ( sideEdge.IsNull() )
4653 //     return false;
4654 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
4655 //   else                            edgeID = edgeIdVec[ _v1 ];
4656 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
4657   
4658 //   // top edge
4659 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
4660 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
4661
4662 //   // top vertex of the other side edge
4663 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
4664 //     return false;
4665 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
4666 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
4667
4668   return nbInserted;
4669 }
4670
4671 //================================================================================
4672 /*!
4673  * \brief Dump ids of nodes of sides
4674  */
4675 //================================================================================
4676
4677 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
4678 {
4679 #ifdef _DEBUG_
4680   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
4681   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
4682   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
4683   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
4684   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
4685   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
4686   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
4687   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
4688   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
4689   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
4690 #endif
4691 }
4692
4693 //================================================================================
4694 /*!
4695  * \brief Creates TVerticalEdgeAdaptor 
4696   * \param columnsMap - node column map
4697   * \param parameter - normalized parameter
4698  */
4699 //================================================================================
4700
4701 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
4702 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
4703 {
4704   myNodeColumn = & getColumn( columnsMap, parameter )->second;
4705 }
4706
4707 //================================================================================
4708 /*!
4709  * \brief Return coordinates for the given normalized parameter
4710   * \param U - normalized parameter
4711   * \retval gp_Pnt - coordinates
4712  */
4713 //================================================================================
4714
4715 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
4716 {
4717   const SMDS_MeshNode* n1;
4718   const SMDS_MeshNode* n2;
4719   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
4720   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
4721 }
4722
4723 //================================================================================
4724 /*!
4725  * \brief Dump ids of nodes
4726  */
4727 //================================================================================
4728
4729 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
4730 {
4731 #ifdef _DEBUG_
4732   for ( int i = 0; i < nbNodes && i < (int)myNodeColumn->size(); ++i )
4733     cout << (*myNodeColumn)[i]->GetID() << " ";
4734   if ( nbNodes < (int) myNodeColumn->size() )
4735     cout << myNodeColumn->back()->GetID();
4736 #endif
4737 }
4738
4739 //================================================================================
4740 /*!
4741  * \brief Return coordinates for the given normalized parameter
4742   * \param U - normalized parameter
4743   * \retval gp_Pnt - coordinates
4744  */
4745 //================================================================================
4746
4747 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
4748 {
4749   return mySide->TSideFace::Value( U, myV );
4750 }
4751
4752 //================================================================================
4753 /*!
4754  * \brief Dump ids of <nbNodes> first nodes and the last one
4755  */
4756 //================================================================================
4757
4758 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
4759 {
4760 #ifdef _DEBUG_
4761   // Not bedugged code. Last node is sometimes incorrect
4762   const TSideFace* side = mySide;
4763   double u = 0;
4764   if ( mySide->IsComplex() )
4765     side = mySide->GetComponent(0,u);
4766
4767   TParam2ColumnIt col, col2;
4768   TParam2ColumnMap* u2cols = side->GetColumns();
4769   side->GetColumns( u , col, col2 );
4770   
4771   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
4772
4773   const SMDS_MeshNode* n = 0;
4774   const SMDS_MeshNode* lastN
4775     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
4776   for ( j = 0; j < nbNodes && n != lastN; ++j )
4777   {
4778     n = col->second[ i ];
4779     cout << n->GetID() << " ";
4780     if ( side->IsForward() )
4781       ++col;
4782     else
4783       --col;
4784   }
4785
4786   // last node
4787   u = 1;
4788   if ( mySide->IsComplex() )
4789     side = mySide->GetComponent(1,u);
4790
4791   side->GetColumns( u , col, col2 );
4792   if ( n != col->second[ i ] )
4793     cout << col->second[ i ]->GetID();
4794 #endif
4795 }
4796
4797 //================================================================================
4798 /*!
4799  * \brief Costructor of TPCurveOnHorFaceAdaptor fills its map of
4800  * normalized parameter to node UV on a horizontal face
4801  *  \param [in] sideFace - lateral prism side
4802  *  \param [in] isTop - is \a horFace top or bottom of the prism
4803  *  \param [in] horFace - top or bottom face of the prism
4804  */
4805 //================================================================================
4806
4807 StdMeshers_PrismAsBlock::
4808 TPCurveOnHorFaceAdaptor::TPCurveOnHorFaceAdaptor( const TSideFace*   sideFace,
4809                                                   const bool         isTop,
4810                                                   const TopoDS_Face& horFace)
4811 {
4812   if ( sideFace && !horFace.IsNull() )
4813   {
4814     //cout << "\n\t FACE " << sideFace->FaceID() << endl;
4815     const int Z = isTop ? sideFace->ColumnHeight() - 1 : 0;
4816     map<double, const SMDS_MeshNode* > u2nodes;
4817     sideFace->GetNodesAtZ( Z, u2nodes );
4818     if ( u2nodes.empty() )
4819       return;
4820
4821     SMESH_MesherHelper helper( *sideFace->GetMesh() );
4822     helper.SetSubShape( horFace );
4823
4824     bool okUV;
4825     gp_XY uv;
4826     double f,l;
4827     Handle(Geom2d_Curve) C2d;
4828     int edgeID = -1;
4829     const double tol = 10 * helper.MaxTolerance( horFace );
4830     const SMDS_MeshNode* prevNode = u2nodes.rbegin()->second;
4831
4832     map<double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4833     for ( ; u2n != u2nodes.end(); ++u2n )
4834     {
4835       const SMDS_MeshNode* n = u2n->second;
4836       okUV = false;
4837       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
4838       {
4839         if ( n->getshapeId() != edgeID )
4840         {
4841           C2d.Nullify();
4842           edgeID = n->getshapeId();
4843           TopoDS_Shape S = helper.GetSubShapeByNode( n, helper.GetMeshDS() );
4844           if ( !S.IsNull() && S.ShapeType() == TopAbs_EDGE )
4845           {
4846             C2d = BRep_Tool::CurveOnSurface( TopoDS::Edge( S ), horFace, f,l );
4847           }
4848         }
4849         if ( !C2d.IsNull() )
4850         {
4851           double u = SMDS_EdgePositionPtr( n->GetPosition() )->GetUParameter();
4852           if ( f <= u && u <= l )
4853           {
4854             uv = C2d->Value( u ).XY();
4855             okUV = helper.CheckNodeUV( horFace, n, uv, tol );
4856           }
4857         }
4858       }
4859       if ( !okUV )
4860         uv = helper.GetNodeUV( horFace, n, prevNode, &okUV );
4861
4862       myUVmap.insert( myUVmap.end(), make_pair( u2n->first, uv ));
4863       // cout << n->getshapeId() << " N " << n->GetID()
4864       //      << " \t" << uv.X() << ", " << uv.Y() << " \t" << u2n->first << endl;
4865
4866       prevNode = n;
4867     }
4868   }
4869 }
4870
4871 //================================================================================
4872 /*!
4873  * \brief Return UV on pcurve for the given normalized parameter
4874   * \param U - normalized parameter
4875   * \retval gp_Pnt - coordinates
4876  */
4877 //================================================================================
4878
4879 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
4880 {
4881   map< double, gp_XY >::const_iterator i1 = myUVmap.upper_bound( U );
4882
4883   if ( i1 == myUVmap.end() )
4884     return myUVmap.empty() ? gp_XY(0,0) : myUVmap.rbegin()->second;
4885
4886   if ( i1 == myUVmap.begin() )
4887     return (*i1).second;
4888
4889   map< double, gp_XY >::const_iterator i2 = i1--;
4890
4891   double r = ( U - i1->first ) / ( i2->first - i1->first );
4892   return i1->second * ( 1 - r ) + i2->second * r;
4893 }
4894
4895 //================================================================================
4896 /*!
4897  * \brief Projects internal nodes using transformation found by boundary nodes
4898  */
4899 //================================================================================
4900
4901 bool StdMeshers_Sweeper::projectIntPoints(const vector< gp_XYZ >&    fromBndPoints,
4902                                           const vector< gp_XYZ >&    toBndPoints,
4903                                           const vector< gp_XYZ >&    fromIntPoints,
4904                                           vector< gp_XYZ >&          toIntPoints,
4905                                           const double               r,
4906                                           NSProjUtils::TrsfFinder3D& trsf,
4907                                           vector< gp_XYZ > *         bndError)
4908 {
4909   // find transformation
4910   if ( trsf.IsIdentity() && !trsf.Solve( fromBndPoints, toBndPoints ))
4911     return false;
4912
4913   // compute internal points using the found trsf
4914   for ( size_t iP = 0; iP < fromIntPoints.size(); ++iP )
4915   {
4916     toIntPoints[ iP ] = trsf.Transform( fromIntPoints[ iP ]);
4917   }
4918
4919   // compute boundary error
4920   if ( bndError )
4921   {
4922     bndError->resize( fromBndPoints.size() );
4923     gp_XYZ fromTrsf;
4924     for ( size_t iP = 0; iP < fromBndPoints.size(); ++iP )
4925     {
4926       fromTrsf = trsf.Transform( fromBndPoints[ iP ] );
4927       (*bndError)[ iP ]  = toBndPoints[ iP ] - fromTrsf;
4928     }
4929   }
4930
4931   // apply boundary error
4932   if ( bndError && toIntPoints.size() == myTopBotTriangles.size() )
4933   {
4934     for ( size_t iP = 0; iP < toIntPoints.size(); ++iP )
4935     {
4936       const TopBotTriangles& tbTrias = myTopBotTriangles[ iP ];
4937       for ( int i = 0; i < 3; ++i ) // boundary errors at 3 triangle nodes
4938       {
4939         toIntPoints[ iP ] +=
4940           ( (*bndError)[ tbTrias.myBotTriaNodes[i] ] * tbTrias.myBotBC[i] * ( 1 - r ) +
4941             (*bndError)[ tbTrias.myTopTriaNodes[i] ] * tbTrias.myTopBC[i] * ( r     ));
4942       }
4943     }
4944   }
4945
4946   return true;
4947 }
4948
4949 //================================================================================
4950 /*!
4951  * \brief Create internal nodes of the prism by computing an affine transformation
4952  *        from layer to layer
4953  */
4954 //================================================================================
4955
4956 bool StdMeshers_Sweeper::ComputeNodesByTrsf( const double tol,
4957                                              const bool   allowHighBndError)
4958 {
4959   const size_t zSize = myBndColumns[0]->size();
4960   const size_t zSrc = 0, zTgt = zSize-1;
4961   if ( zSize < 3 ) return true;
4962
4963   vector< vector< gp_XYZ > > intPntsOfLayer( zSize ); // node coordinates to compute
4964   // set coordinates of src and tgt nodes
4965   for ( size_t z = 0; z < intPntsOfLayer.size(); ++z )
4966     intPntsOfLayer[ z ].resize( myIntColumns.size() );
4967   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
4968   {
4969     intPntsOfLayer[ zSrc ][ iP ] = intPoint( iP, zSrc );
4970     intPntsOfLayer[ zTgt ][ iP ] = intPoint( iP, zTgt );
4971   }
4972
4973   // for each internal column find boundary nodes whose error to use for correction
4974   prepareTopBotDelaunay();
4975   bool isErrorCorrectable = findDelaunayTriangles();
4976
4977   // compute coordinates of internal nodes by projecting (transforming) src and tgt
4978   // nodes towards the central layer
4979
4980   vector< NSProjUtils::TrsfFinder3D > trsfOfLayer( zSize );
4981   vector< vector< gp_XYZ > >          bndError( zSize );
4982
4983   // boundary points used to compute an affine transformation from a layer to a next one
4984   vector< gp_XYZ > fromSrcBndPnts( myBndColumns.size() ), fromTgtBndPnts( myBndColumns.size() );
4985   vector< gp_XYZ > toSrcBndPnts  ( myBndColumns.size() ), toTgtBndPnts  ( myBndColumns.size() );
4986   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4987   {
4988     fromSrcBndPnts[ iP ] = bndPoint( iP, zSrc );
4989     fromTgtBndPnts[ iP ] = bndPoint( iP, zTgt );
4990   }
4991
4992   size_t zS = zSrc + 1;
4993   size_t zT = zTgt - 1;
4994   for ( ; zS < zT; ++zS, --zT ) // vertical loop on layers
4995   {
4996     for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
4997     {
4998       toSrcBndPnts[ iP ] = bndPoint( iP, zS );
4999       toTgtBndPnts[ iP ] = bndPoint( iP, zT );
5000     }
5001     if (! projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
5002                             intPntsOfLayer[ zS-1 ], intPntsOfLayer[ zS ],
5003                             zS / ( zSize - 1.),
5004                             trsfOfLayer   [ zS-1 ], & bndError[ zS-1 ]))
5005       return false;
5006     if (! projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
5007                             intPntsOfLayer[ zT+1 ], intPntsOfLayer[ zT ],
5008                             zT / ( zSize - 1.),
5009                             trsfOfLayer   [ zT+1 ], & bndError[ zT+1 ]))
5010       return false;
5011
5012     // if ( zT == zTgt - 1 )
5013     // {
5014     //   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5015     //   {
5016     //     gp_XYZ fromTrsf = trsfOfLayer   [ zT+1].Transform( fromTgtBndPnts[ iP ] );
5017     //     cout << "mesh.AddNode( "
5018     //          << fromTrsf.X() << ", "
5019     //          << fromTrsf.Y() << ", "
5020     //          << fromTrsf.Z() << ") " << endl;
5021     //   }
5022     //   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5023     //     cout << "mesh.AddNode( "
5024     //          << intPntsOfLayer[ zT ][ iP ].X() << ", "
5025     //          << intPntsOfLayer[ zT ][ iP ].Y() << ", "
5026     //          << intPntsOfLayer[ zT ][ iP ].Z() << ") " << endl;
5027     // }
5028
5029     fromTgtBndPnts.swap( toTgtBndPnts );
5030     fromSrcBndPnts.swap( toSrcBndPnts );
5031   }
5032
5033   // Evaluate an error of boundary points
5034
5035   if ( !isErrorCorrectable && !allowHighBndError )
5036   {
5037     for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5038     {
5039       double sumError = 0;
5040       for ( size_t z = 1; z < zS; ++z ) // loop on layers
5041         sumError += ( bndError[ z-1     ][ iP ].Modulus() +
5042                       bndError[ zSize-z ][ iP ].Modulus() );
5043
5044       if ( sumError > tol )
5045         return false;
5046     }
5047   }
5048
5049   // Compute two projections of internal points to the central layer
5050   // in order to evaluate an error of internal points
5051
5052   bool centerIntErrorIsSmall;
5053   vector< gp_XYZ > centerSrcIntPnts( myIntColumns.size() );
5054   vector< gp_XYZ > centerTgtIntPnts( myIntColumns.size() );
5055
5056   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5057   {
5058     toSrcBndPnts[ iP ] = bndPoint( iP, zS );
5059     toTgtBndPnts[ iP ] = bndPoint( iP, zT );
5060   }
5061   if (! projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
5062                           intPntsOfLayer[ zS-1 ], centerSrcIntPnts,
5063                           zS / ( zSize - 1.),
5064                           trsfOfLayer   [ zS-1 ], & bndError[ zS-1 ]))
5065     return false;
5066   if (! projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
5067                           intPntsOfLayer[ zT+1 ], centerTgtIntPnts,
5068                           zT / ( zSize - 1.),
5069                           trsfOfLayer   [ zT+1 ], & bndError[ zT+1 ]))
5070     return false;
5071
5072   // evaluate an error of internal points on the central layer
5073   centerIntErrorIsSmall = true;
5074   if ( zS == zT ) // odd zSize
5075   {
5076     for ( size_t iP = 0; ( iP < myIntColumns.size() && centerIntErrorIsSmall ); ++iP )
5077       centerIntErrorIsSmall =
5078         (centerSrcIntPnts[ iP ] - centerTgtIntPnts[ iP ]).SquareModulus() < tol*tol;
5079   }
5080   else // even zSize
5081   {
5082     for ( size_t iP = 0; ( iP < myIntColumns.size() && centerIntErrorIsSmall ); ++iP )
5083       centerIntErrorIsSmall =
5084         (intPntsOfLayer[ zS-1 ][ iP ] - centerTgtIntPnts[ iP ]).SquareModulus() < tol*tol;
5085   }
5086
5087   // compute final points on the central layer
5088   double r = zS / ( zSize - 1.);
5089   if ( zS == zT )
5090   {
5091     for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5092     {
5093       intPntsOfLayer[ zS ][ iP ] =
5094         ( 1 - r ) * centerSrcIntPnts[ iP ] + r * centerTgtIntPnts[ iP ];
5095     }
5096   }
5097   else
5098   {
5099     for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5100     {
5101       intPntsOfLayer[ zS ][ iP ] =
5102         r * intPntsOfLayer[ zS ][ iP ] + ( 1 - r ) * centerSrcIntPnts[ iP ];
5103       intPntsOfLayer[ zT ][ iP ] =
5104         r * intPntsOfLayer[ zT ][ iP ] + ( 1 - r ) * centerTgtIntPnts[ iP ];
5105     }
5106   }
5107
5108   if ( !centerIntErrorIsSmall )
5109   {
5110     // Compensate the central error; continue adding projection
5111     // by going from central layer to the source and target ones
5112
5113     vector< gp_XYZ >& fromSrcIntPnts = centerSrcIntPnts;
5114     vector< gp_XYZ >& fromTgtIntPnts = centerTgtIntPnts;
5115     vector< gp_XYZ >  toSrcIntPnts( myIntColumns.size() );
5116     vector< gp_XYZ >  toTgtIntPnts( myIntColumns.size() );
5117     vector< gp_XYZ >  srcBndError( myBndColumns.size() );
5118     vector< gp_XYZ >  tgtBndError( myBndColumns.size() );
5119
5120     fromTgtBndPnts.swap( toTgtBndPnts );
5121     fromSrcBndPnts.swap( toSrcBndPnts );
5122
5123     for ( ++zS, --zT; zS < zTgt; ++zS, --zT ) // vertical loop on layers
5124     {
5125       // invert transformation
5126       if ( !trsfOfLayer[ zS+1 ].Invert() )
5127         trsfOfLayer[ zS+1 ] = NSProjUtils::TrsfFinder3D(); // to recompute
5128       if ( !trsfOfLayer[ zT-1 ].Invert() )
5129         trsfOfLayer[ zT-1 ] = NSProjUtils::TrsfFinder3D();
5130
5131       // project internal nodes and compute bnd error
5132       for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5133       {
5134         toSrcBndPnts[ iP ] = bndPoint( iP, zS );
5135         toTgtBndPnts[ iP ] = bndPoint( iP, zT );
5136       }
5137       projectIntPoints( fromSrcBndPnts, toSrcBndPnts,
5138                         fromSrcIntPnts, toSrcIntPnts,
5139                         zS / ( zSize - 1.),
5140                         trsfOfLayer[ zS+1 ], & srcBndError );
5141       projectIntPoints( fromTgtBndPnts, toTgtBndPnts,
5142                         fromTgtIntPnts, toTgtIntPnts,
5143                         zT / ( zSize - 1.),
5144                         trsfOfLayer[ zT-1 ], & tgtBndError );
5145
5146       // if ( zS == zTgt - 1 )
5147       // {
5148       //   cout << "mesh2 = smesh.Mesh()" << endl;
5149       //   for ( size_t iP = 0; iP < myBndColumns.size(); ++iP )
5150       //   {
5151       //     gp_XYZ fromTrsf = trsfOfLayer   [ zS+1].Transform( fromSrcBndPnts[ iP ] );
5152       //     cout << "mesh2.AddNode( "
5153       //          << fromTrsf.X() << ", "
5154       //          << fromTrsf.Y() << ", "
5155       //          << fromTrsf.Z() << ") " << endl;
5156       //   }
5157       //   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5158       //     cout << "mesh2.AddNode( "
5159       //          << toSrcIntPnts[ iP ].X() << ", "
5160       //          << toSrcIntPnts[ iP ].Y() << ", "
5161       //          << toSrcIntPnts[ iP ].Z() << ") " << endl;
5162       // }
5163
5164       // sum up 2 projections
5165       r = zS / ( zSize - 1.);
5166       vector< gp_XYZ >& zSIntPnts = intPntsOfLayer[ zS ];
5167       vector< gp_XYZ >& zTIntPnts = intPntsOfLayer[ zT ];
5168       for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5169       {
5170         zSIntPnts[ iP ] = r * zSIntPnts[ iP ]  +  ( 1 - r ) * toSrcIntPnts[ iP ];
5171         zTIntPnts[ iP ] = r * zTIntPnts[ iP ]  +  ( 1 - r ) * toTgtIntPnts[ iP ];
5172       }
5173
5174       fromSrcBndPnts.swap( toSrcBndPnts );
5175       fromSrcIntPnts.swap( toSrcIntPnts );
5176       fromTgtBndPnts.swap( toTgtBndPnts );
5177       fromTgtIntPnts.swap( toTgtIntPnts );
5178     }
5179   }  // if ( !centerIntErrorIsSmall )
5180
5181
5182   //cout << "centerIntErrorIsSmall = " << centerIntErrorIsSmall<< endl;
5183
5184   // Create nodes
5185   for ( size_t iP = 0; iP < myIntColumns.size(); ++iP )
5186   {
5187     vector< const SMDS_MeshNode* > & nodeCol = *myIntColumns[ iP ];
5188     for ( size_t z = zSrc + 1; z < zTgt; ++z ) // vertical loop on layers
5189     {
5190       const gp_XYZ & xyz = intPntsOfLayer[ z ][ iP ];
5191       if ( !( nodeCol[ z ] = myHelper->AddNode( xyz.X(), xyz.Y(), xyz.Z() )))
5192         return false;
5193     }
5194   }
5195
5196   return true;
5197 }
5198
5199 //================================================================================
5200 /*!
5201  * \brief Check if all nodes of each layers have same logical Z
5202  */
5203 //================================================================================
5204
5205 bool StdMeshers_Sweeper::CheckSameZ()
5206 {
5207   myZColumns.resize( myBndColumns.size() );
5208   fillZColumn( myZColumns[0], *myBndColumns[0] );
5209
5210   bool sameZ = true;
5211   const double tol = 0.1 * 1./ myBndColumns[0]->size();
5212
5213   // check columns based on VERTEXes
5214
5215   vector< int > vertexIndex;
5216   vertexIndex.push_back( 0 );
5217   for ( size_t iC = 1; iC < myBndColumns.size() &&  sameZ; ++iC )
5218   {
5219     if ( myBndColumns[iC]->front()->GetPosition()->GetDim() > 0 )
5220       continue; // not on VERTEX
5221
5222     vertexIndex.push_back( iC );
5223     fillZColumn( myZColumns[iC], *myBndColumns[iC] );
5224
5225     for ( size_t iZ = 0; iZ < myZColumns[0].size() &&  sameZ; ++iZ )
5226       sameZ = ( Abs( myZColumns[0][iZ] - myZColumns[iC][iZ]) < tol );
5227   }
5228
5229   // check columns based on EDGEs, one per EDGE
5230
5231   for ( size_t i = 1; i < vertexIndex.size() &&  sameZ; ++i )
5232   {
5233     if ( vertexIndex[i] - vertexIndex[i-1] < 2 )
5234       continue;
5235
5236     int iC = ( vertexIndex[i] + vertexIndex[i-1] ) / 2;
5237     fillZColumn( myZColumns[iC], *myBndColumns[iC] );
5238
5239     for ( size_t iZ = 0; iZ < myZColumns[0].size() &&  sameZ; ++iZ )
5240       sameZ = ( Abs( myZColumns[0][iZ] - myZColumns[iC][iZ]) < tol );
5241   }
5242
5243   if ( sameZ )
5244   {
5245     myZColumns.resize(1);
5246   }
5247   else
5248   {
5249     for ( size_t iC = 1; iC < myBndColumns.size(); ++iC )
5250       fillZColumn( myZColumns[iC], *myBndColumns[iC] );
5251   }
5252
5253   return sameZ;
5254 }
5255
5256 //================================================================================
5257 /*!
5258  * \brief Create internal nodes of the prism all located on straight lines with
5259  *        the same distribution along the lines.
5260  */
5261 //================================================================================
5262
5263 bool StdMeshers_Sweeper::ComputeNodesOnStraightSameZ()
5264 {
5265   TZColumn& z = myZColumns[0];
5266
5267   for ( size_t i = 0; i < myIntColumns.size(); ++i )
5268   {
5269     TNodeColumn& nodes = *myIntColumns[i];
5270     SMESH_NodeXYZ n0( nodes[0] ), n1( nodes.back() );
5271
5272     for ( size_t iZ = 0; iZ < z.size(); ++iZ )
5273     {
5274       gp_XYZ p = n0 * ( 1 - z[iZ] ) + n1 * z[iZ];
5275       nodes[ iZ+1 ] = myHelper->AddNode( p.X(), p.Y(), p.Z() );
5276     }
5277   }
5278
5279   return true;
5280 }
5281
5282 //================================================================================
5283 /*!
5284  * \brief Create internal nodes of the prism all located on straight lines with
5285  *        different distributions along the lines.
5286  */
5287 //================================================================================
5288
5289 bool StdMeshers_Sweeper::ComputeNodesOnStraight()
5290 {
5291   prepareTopBotDelaunay();
5292
5293   const SMDS_MeshNode     *botNode, *topNode;
5294   const BRepMesh_Triangle *topTria;
5295   double botBC[3], topBC[3]; // barycentric coordinates
5296   int    botTriaNodes[3], topTriaNodes[3];
5297   bool   checkUV = true;
5298
5299   int nbInternalNodes = myIntColumns.size();
5300   myBotDelaunay->InitTraversal( nbInternalNodes );
5301
5302   while (( botNode = myBotDelaunay->NextNode( botBC, botTriaNodes )))
5303   {
5304     TNodeColumn* column = myIntColumns[ myNodeID2ColID( botNode->GetID() )];
5305
5306     // find a Delaunay triangle containing the topNode
5307     topNode = column->back();
5308     gp_XY topUV = myHelper->GetNodeUV( myTopFace, topNode, NULL, &checkUV );
5309     // get a starting triangle basing on that top and bot boundary nodes have same index
5310     topTria = myTopDelaunay->GetTriangleNear( botTriaNodes[0] );
5311     topTria = myTopDelaunay->FindTriangle( topUV, topTria, topBC, topTriaNodes );
5312     if ( !topTria )
5313       return false;
5314
5315     // create nodes along a line
5316     SMESH_NodeXYZ botP( botNode ), topP( topNode );
5317     for ( size_t iZ = 0; iZ < myZColumns[0].size(); ++iZ )
5318     {
5319       // use barycentric coordinates as weight of Z of boundary columns
5320       double botZ = 0, topZ = 0;
5321       for ( int i = 0; i < 3; ++i )
5322       {
5323         botZ += botBC[i] * myZColumns[ botTriaNodes[i] ][ iZ ];
5324         topZ += topBC[i] * myZColumns[ topTriaNodes[i] ][ iZ ];
5325       }
5326       double rZ = double( iZ + 1 ) / ( myZColumns[0].size() + 1 );
5327       double z = botZ * ( 1 - rZ ) + topZ * rZ;
5328       gp_XYZ p = botP * ( 1 - z  ) + topP * z;
5329       (*column)[ iZ+1 ] = myHelper->AddNode( p.X(), p.Y(), p.Z() );
5330     }
5331   }
5332
5333   return myBotDelaunay->NbVisitedNodes() == nbInternalNodes;
5334 }
5335
5336 //================================================================================
5337 /*!
5338  * \brief Compute Z of nodes of a straight column
5339  */
5340 //================================================================================
5341
5342 void StdMeshers_Sweeper::fillZColumn( TZColumn&    zColumn,
5343                                       TNodeColumn& nodes )
5344 {
5345   if ( zColumn.size() == nodes.size() - 2 )
5346     return;
5347
5348   gp_Pnt p0 = SMESH_NodeXYZ( nodes[0] );
5349   gp_Vec line( p0, SMESH_NodeXYZ( nodes.back() ));
5350   double len2 = line.SquareMagnitude();
5351
5352   zColumn.resize( nodes.size() - 2 );
5353   for ( size_t i = 0; i < zColumn.size(); ++i )
5354   {
5355     gp_Vec vec( p0, SMESH_NodeXYZ( nodes[ i+1] ));
5356     zColumn[i] = ( line * vec ) / len2; // param [0,1] on the line
5357   }
5358 }
5359
5360 //================================================================================
5361 /*!
5362  * \brief Initialize *Delaunay members
5363  */
5364 //================================================================================
5365
5366 void StdMeshers_Sweeper::prepareTopBotDelaunay()
5367 {
5368   UVPtStructVec botUV( myBndColumns.size() );
5369   UVPtStructVec topUV( myBndColumns.size() );
5370   for ( size_t i = 0; i < myBndColumns.size(); ++i )
5371   {
5372     TNodeColumn& nodes = *myBndColumns[i];
5373     botUV[i].node = nodes[0];
5374     botUV[i].SetUV( myHelper->GetNodeUV( myBotFace, nodes[0] ));
5375     topUV[i].node = nodes.back();
5376     topUV[i].SetUV( myHelper->GetNodeUV( myTopFace, nodes.back() ));
5377     botUV[i].node->setIsMarked( true );
5378   }
5379   TopoDS_Edge dummyE;
5380   SMESH_Mesh* mesh = myHelper->GetMesh();
5381   TSideVector botWires( 1, StdMeshers_FaceSide::New( botUV, myBotFace, dummyE, mesh ));
5382   TSideVector topWires( 1, StdMeshers_FaceSide::New( topUV, myTopFace, dummyE, mesh ));
5383
5384   // Delaunay mesh on the FACEs.
5385   bool checkUV = false;
5386   myBotDelaunay.reset( new NSProjUtils::Delaunay( botWires, checkUV ));
5387   myTopDelaunay.reset( new NSProjUtils::Delaunay( topWires, checkUV ));
5388
5389   if ( myHelper->GetIsQuadratic() )
5390   {
5391     // mark all medium nodes of faces on botFace to avoid their treating
5392     SMESHDS_SubMesh* smDS = myHelper->GetMeshDS()->MeshElements( myBotFace );
5393     SMDS_ElemIteratorPtr eIt = smDS->GetElements();
5394     while ( eIt->more() )
5395     {
5396       const SMDS_MeshElement* e = eIt->next();
5397       for ( int i = e->NbCornerNodes(), nb = e->NbNodes(); i < nb; ++i )
5398         e->GetNode( i )->setIsMarked( true );
5399     }
5400   }
5401
5402   // map to get a node column by a bottom node
5403   myNodeID2ColID.Clear(/*doReleaseMemory=*/false);
5404   myNodeID2ColID.ReSize( myIntColumns.size() );
5405
5406   // un-mark nodes to treat (internal bottom nodes) to be returned by myBotDelaunay
5407   for ( size_t i = 0; i < myIntColumns.size(); ++i )
5408   {
5409     const SMDS_MeshNode* botNode = myIntColumns[i]->front();
5410     botNode->setIsMarked( false );
5411     myNodeID2ColID.Bind( botNode->GetID(), i );
5412   }
5413 }
5414
5415 //================================================================================
5416 /*!
5417  * \brief For each internal node column, find Delaunay triangles including it
5418  *        and Barycentric Coordinates within the triangles. Fill in myTopBotTriangles
5419  */
5420 //================================================================================
5421
5422 bool StdMeshers_Sweeper::findDelaunayTriangles()
5423 {
5424   const SMDS_MeshNode     *botNode, *topNode;
5425   const BRepMesh_Triangle *topTria;
5426   TopBotTriangles          tbTrias;
5427   bool  checkUV = true;
5428
5429   int nbInternalNodes = myIntColumns.size();
5430   myTopBotTriangles.resize( nbInternalNodes );
5431
5432   myBotDelaunay->InitTraversal( nbInternalNodes );
5433
5434   while (( botNode = myBotDelaunay->NextNode( tbTrias.myBotBC, tbTrias.myBotTriaNodes )))
5435   {
5436     int colID = myNodeID2ColID( botNode->GetID() );
5437     TNodeColumn* column = myIntColumns[ colID ];
5438
5439     // find a Delaunay triangle containing the topNode
5440     topNode = column->back();
5441     gp_XY topUV = myHelper->GetNodeUV( myTopFace, topNode, NULL, &checkUV );
5442     // get a starting triangle basing on that top and bot boundary nodes have same index
5443     topTria = myTopDelaunay->GetTriangleNear( tbTrias.myBotTriaNodes[0] );
5444     topTria = myTopDelaunay->FindTriangle( topUV, topTria,
5445                                            tbTrias.myTopBC, tbTrias.myTopTriaNodes );
5446     if ( !topTria )
5447       tbTrias.SetTopByBottom();
5448
5449     myTopBotTriangles[ colID ] = tbTrias;
5450   }
5451
5452   if ( myBotDelaunay->NbVisitedNodes() < nbInternalNodes )
5453   {
5454     myTopBotTriangles.clear();
5455     return false;
5456   }
5457
5458   myBotDelaunay.reset();
5459   myTopDelaunay.reset();
5460   myNodeID2ColID.Clear();
5461
5462   return true;
5463 }
5464
5465 //================================================================================
5466 /*!
5467  * \brief Initialize fields
5468  */
5469 //================================================================================
5470
5471 StdMeshers_Sweeper::TopBotTriangles::TopBotTriangles()
5472 {
5473   myBotBC[0] = myBotBC[1] = myBotBC[2] = myTopBC[0] = myTopBC[1] = myTopBC[2] = 0.;
5474   myBotTriaNodes[0] = myBotTriaNodes[1] = myBotTriaNodes[2] = 0;
5475   myTopTriaNodes[0] = myTopTriaNodes[1] = myTopTriaNodes[2] = 0;
5476 }
5477
5478 //================================================================================
5479 /*!
5480  * \brief Set top data equal to bottom data
5481  */
5482 //================================================================================
5483
5484 void StdMeshers_Sweeper::TopBotTriangles::SetTopByBottom()
5485 {
5486   for ( int i = 0; i < 3; ++i )
5487   {
5488     myTopBC[i]        = myBotBC[i];
5489     myTopTriaNodes[i] = myBotTriaNodes[0];
5490   }
5491 }