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