]> SALOME platform Git repositories - modules/smesh.git/blob - src/StdMeshers/StdMeshers_Prism_3D.cxx
Salome HOME
0021893: EDF 2133 SMESH : Improvement of 3D extrusion algorithm
[modules/smesh.git] / src / StdMeshers / StdMeshers_Prism_3D.cxx
1 // Copyright (C) 2007-2012  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.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File      : StdMeshers_Prism_3D.cxx
24 // Module    : SMESH
25 // Created   : Fri Oct 20 11:37:07 2006
26 // Author    : Edward AGAPOV (eap)
27 //
28 #include "StdMeshers_Prism_3D.hxx"
29
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeOfNodes.hxx"
32 #include "SMDS_VolumeTool.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_ProjectionSource1D.hxx"
39 #include "StdMeshers_ProjectionSource2D.hxx"
40 #include "StdMeshers_ProjectionUtils.hxx"
41 #include "StdMeshers_Projection_1D.hxx"
42 #include "StdMeshers_Projection_1D2D.hxx"
43 #include "StdMeshers_Quadrangle_2D.hxx"
44
45 #include "utilities.h"
46
47 #include <BRepAdaptor_CompCurve.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B3d.hxx>
50 #include <Geom2dAdaptor_Curve.hxx>
51 #include <Geom2d_Line.hxx>
52 #include <Geom_Curve.hxx>
53 #include <TopExp.hxx>
54 #include <TopExp_Explorer.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopTools_ListOfShape.hxx>
57 #include <TopTools_MapOfShape.hxx>
58 #include <TopTools_SequenceOfShape.hxx>
59 #include <TopoDS.hxx>
60 #include <gp_Ax2.hxx>
61 #include <gp_Ax3.hxx>
62
63 using namespace std;
64
65 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
66 #define gpXYZ(n) gp_XYZ(n->X(),n->Y(),n->Z())
67 #define SHOWYXZ(msg, xyz) // {\
68 // gp_Pnt p (xyz); \
69 // cout << msg << " ("<< p.X() << "; " <<p.Y() << "; " <<p.Z() << ") " <<endl;\
70 // }
71
72 typedef StdMeshers_ProjectionUtils TAssocTool;
73 typedef SMESH_Comment              TCom;
74
75 enum { ID_BOT_FACE = SMESH_Block::ID_Fxy0,
76        ID_TOP_FACE = SMESH_Block::ID_Fxy1,
77        BOTTOM_EDGE = 0, TOP_EDGE, V0_EDGE, V1_EDGE, // edge IDs in face
78        NB_WALL_FACES = 4 }; //
79
80 namespace {
81
82   //=======================================================================
83   /*!
84    * \brief Quadrangle algorithm
85    */
86   struct TQuadrangleAlgo : public StdMeshers_Quadrangle_2D
87   {
88     TQuadrangleAlgo(int studyId, SMESH_Gen* gen)
89       : StdMeshers_Quadrangle_2D( gen->GetANewId(), studyId, gen)
90     {
91     }
92     static StdMeshers_Quadrangle_2D* instance( SMESH_Algo* fatherAlgo,
93                                                SMESH_Mesh* mesh=0)
94     {
95       static TQuadrangleAlgo* algo = new TQuadrangleAlgo( fatherAlgo->GetStudyId(),
96                                                           fatherAlgo->GetGen() );
97       if ( mesh &&
98            algo->myProxyMesh &&
99            algo->myProxyMesh->GetMesh() != mesh )
100         algo->myProxyMesh.reset( new SMESH_ProxyMesh( *mesh ));
101
102       return algo;
103     }
104   };
105   //=======================================================================
106   /*!
107    * \brief Algorithm projecting 1D mesh
108    */
109   struct TProjction1dAlgo : public StdMeshers_Projection_1D
110   {
111     StdMeshers_ProjectionSource1D myHyp;
112
113     TProjction1dAlgo(int studyId, SMESH_Gen* gen)
114       : StdMeshers_Projection_1D( gen->GetANewId(), studyId, gen),
115         myHyp( gen->GetANewId(), studyId, gen)
116     {
117       StdMeshers_Projection_1D::_sourceHypo = & myHyp;
118     }
119     static TProjction1dAlgo* instance( SMESH_Algo* fatherAlgo )
120     {
121       static TProjction1dAlgo* algo = new TProjction1dAlgo( fatherAlgo->GetStudyId(),
122                                                             fatherAlgo->GetGen() );
123       return algo;
124     }
125   };
126   //=======================================================================
127   /*!
128    * \brief Algorithm projecting 2D mesh
129    */
130   struct TProjction2dAlgo : public StdMeshers_Projection_1D2D
131   {
132     StdMeshers_ProjectionSource2D myHyp;
133
134     TProjction2dAlgo(int studyId, SMESH_Gen* gen)
135       : StdMeshers_Projection_1D2D( gen->GetANewId(), studyId, gen),
136         myHyp( gen->GetANewId(), studyId, gen)
137     {
138       StdMeshers_Projection_2D::_sourceHypo = & myHyp;
139     }
140     static TProjction2dAlgo* instance( SMESH_Algo* fatherAlgo )
141     {
142       static TProjction2dAlgo* algo = new TProjction2dAlgo( fatherAlgo->GetStudyId(),
143                                                             fatherAlgo->GetGen() );
144       return algo;
145     }
146   };
147
148   //================================================================================
149   /*!
150    * \brief Make \a botE be the BOTTOM_SIDE of \a quad.
151    *        Return false if the BOTTOM_SIDE is composite
152    */
153   //================================================================================
154
155   bool setBottomEdge( const TopoDS_Edge&   botE,
156                       faceQuadStruct::Ptr& quad,
157                       const TopoDS_Shape&  face)
158   {
159     quad->side[ QUAD_TOP_SIDE  ]->Reverse();
160     quad->side[ QUAD_LEFT_SIDE ]->Reverse();
161     int edgeIndex = 0;
162     for ( size_t i = 0; i < quad->side.size(); ++i )
163     {
164       StdMeshers_FaceSide* quadSide = quad->side[i];
165       for ( int iE = 0; iE < quadSide->NbEdges(); ++iE )
166         if ( botE.IsSame( quadSide->Edge( iE )))
167         {
168           if ( quadSide->NbEdges() > 1 )
169             return false;
170           edgeIndex = i;
171           i = quad->side.size(); // to quit from the outer loop
172           break;
173         }
174     }
175     if ( edgeIndex != QUAD_BOTTOM_SIDE )
176       quad->shift( quad->side.size() - edgeIndex, /*keepUnitOri=*/false );
177
178     quad->face = TopoDS::Face( face );
179
180     return true;
181   }
182
183   //================================================================================
184   /*!
185    * \brief Return iterator pointing to node column for the given parameter
186    * \param columnsMap - node column map
187    * \param parameter - parameter
188    * \retval TParam2ColumnMap::iterator - result
189    *
190    * it returns closest left column
191    */
192   //================================================================================
193
194   TParam2ColumnIt getColumn( const TParam2ColumnMap* columnsMap,
195                              const double            parameter )
196   {
197     TParam2ColumnIt u_col = columnsMap->upper_bound( parameter );
198     if ( u_col != columnsMap->begin() )
199       --u_col;
200     return u_col; // return left column
201   }
202
203   //================================================================================
204   /*!
205    * \brief Return nodes around given parameter and a ratio
206    * \param column - node column
207    * \param param - parameter
208    * \param node1 - lower node
209    * \param node2 - upper node
210    * \retval double - ratio
211    */
212   //================================================================================
213
214   double getRAndNodes( const TNodeColumn*     column,
215                        const double           param,
216                        const SMDS_MeshNode* & node1,
217                        const SMDS_MeshNode* & node2)
218   {
219     if ( param >= 1.0 || column->size() == 1) {
220       node1 = node2 = column->back();
221       return 0;
222     }
223
224     int i = int( param * ( column->size() - 1 ));
225     double u0 = double( i )/ double( column->size() - 1 );
226     double r = ( param - u0 ) * ( column->size() - 1 );
227
228     node1 = (*column)[ i ];
229     node2 = (*column)[ i + 1];
230     return r;
231   }
232
233   //================================================================================
234   /*!
235    * \brief Compute boundary parameters of face parts
236     * \param nbParts - nb of parts to split columns into
237     * \param columnsMap - node columns of the face to split
238     * \param params - computed parameters
239    */
240   //================================================================================
241
242   void splitParams( const int               nbParts,
243                     const TParam2ColumnMap* columnsMap,
244                     vector< double > &      params)
245   {
246     params.clear();
247     params.reserve( nbParts + 1 );
248     TParam2ColumnIt last_par_col = --columnsMap->end();
249     double par = columnsMap->begin()->first; // 0.
250     double parLast = last_par_col->first;
251     params.push_back( par );
252     for ( int i = 0; i < nbParts - 1; ++ i )
253     {
254       double partSize = ( parLast - par ) / double ( nbParts - i );
255       TParam2ColumnIt par_col = getColumn( columnsMap, par + partSize );
256       if ( par_col->first == par ) {
257         ++par_col;
258         if ( par_col == last_par_col ) {
259           while ( i < nbParts - 1 )
260             params.push_back( par + partSize * i++ );
261           break;
262         }
263       }
264       par = par_col->first;
265       params.push_back( par );
266     }
267     params.push_back( parLast ); // 1.
268   }
269
270   //================================================================================
271   /*!
272    * \brief Return coordinate system for z-th layer of nodes
273    */
274   //================================================================================
275
276   gp_Ax2 getLayerCoordSys(const int                           z,
277                           const vector< const TNodeColumn* >& columns,
278                           int&                                xColumn)
279   {
280     // gravity center of a layer
281     gp_XYZ O(0,0,0);
282     int vertexCol = -1;
283     for ( int i = 0; i < columns.size(); ++i )
284     {
285       O += gpXYZ( (*columns[ i ])[ z ]);
286       if ( vertexCol < 0 &&
287            columns[ i ]->front()->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
288         vertexCol = i;
289     }
290     O /= columns.size();
291
292     // Z axis
293     gp_Vec Z(0,0,0);
294     int iPrev = columns.size()-1;
295     for ( int i = 0; i < columns.size(); ++i )
296     {
297       gp_Vec v1( O, gpXYZ( (*columns[ iPrev ])[ z ]));
298       gp_Vec v2( O, gpXYZ( (*columns[ i ]    )[ z ]));
299       Z += v1 ^ v2;
300       iPrev = i;
301     }
302
303     if ( vertexCol >= 0 )
304     {
305       O = gpXYZ( (*columns[ vertexCol ])[ z ]);
306     }
307     if ( xColumn < 0 || xColumn >= columns.size() )
308     {
309       // select a column for X dir
310       double maxDist = 0;
311       for ( int i = 0; i < columns.size(); ++i )
312       {
313         double dist = ( O - gpXYZ((*columns[ i ])[ z ])).SquareModulus();
314         if ( dist > maxDist )
315         {
316           xColumn = i;
317           maxDist = dist;
318         }
319       }
320     }
321
322     // X axis
323     gp_Vec X( O, gpXYZ( (*columns[ xColumn ])[ z ]));
324
325     return gp_Ax2( O, Z, X);
326   }
327
328   //================================================================================
329   /*!
330    * \brief Removes submeshes that are or can be meshed with regular grid from given list
331    *  \retval int - nb of removed submeshes
332    */
333   //================================================================================
334
335   int removeQuasiQuads(list< SMESH_subMesh* >&   notQuadSubMesh,
336                        SMESH_MesherHelper*       helper,
337                        StdMeshers_Quadrangle_2D* quadAlgo)
338   {
339     int nbRemoved = 0;
340     //SMESHDS_Mesh* mesh = notQuadSubMesh.front()->GetFather()->GetMeshDS();
341     list< SMESH_subMesh* >::iterator smIt = notQuadSubMesh.begin();
342     while ( smIt != notQuadSubMesh.end() )
343     {
344       SMESH_subMesh* faceSm = *smIt;
345       SMESHDS_SubMesh* faceSmDS = faceSm->GetSubMeshDS();
346       int nbQuads = faceSmDS ? faceSmDS->NbElements() : 0;
347       bool toRemove;
348       if ( nbQuads > 0 )
349         toRemove = helper->IsStructured( faceSm );
350       else
351         toRemove = quadAlgo->CheckNbEdges( *helper->GetMesh(),
352                                            faceSm->GetSubShape() );
353       nbRemoved += toRemove;
354       if ( toRemove )
355         smIt = notQuadSubMesh.erase( smIt );
356       else
357         ++smIt;
358     }
359
360     return nbRemoved;
361   }
362
363 } // namespace
364
365 //=======================================================================
366 //function : StdMeshers_Prism_3D
367 //purpose  : 
368 //=======================================================================
369
370 StdMeshers_Prism_3D::StdMeshers_Prism_3D(int hypId, int studyId, SMESH_Gen* gen)
371   :SMESH_3D_Algo(hypId, studyId, gen)
372 {
373   _name                    = "Prism_3D";
374   _shapeType               = (1 << TopAbs_SOLID); // 1 bit per shape type
375   _onlyUnaryInput          = false; // accept all SOLIDs at once
376   _requireDiscreteBoundary = false; // mesh FACEs and EDGEs by myself
377   _supportSubmeshes        = true;  // "source" FACE must be meshed by other algo
378   _neededLowerHyps[ 1 ]    = true;  // suppress warning on hiding a global 1D algo
379   _neededLowerHyps[ 2 ]    = true;  // suppress warning on hiding a global 2D algo
380
381   //myProjectTriangles       = false;
382   mySetErrorToSM           = true;  // to pass an error to a sub-mesh of a current solid or not
383 }
384
385 //================================================================================
386 /*!
387  * \brief Destructor
388  */
389 //================================================================================
390
391 StdMeshers_Prism_3D::~StdMeshers_Prism_3D()
392 {}
393
394 //=======================================================================
395 //function : CheckHypothesis
396 //purpose  : 
397 //=======================================================================
398
399 bool StdMeshers_Prism_3D::CheckHypothesis(SMESH_Mesh&                          aMesh,
400                                           const TopoDS_Shape&                  aShape,
401                                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
402 {
403   // Check shape geometry
404 /*  PAL16229
405   aStatus = SMESH_Hypothesis::HYP_BAD_GEOMETRY;
406
407   // find not quadrangle faces
408   list< TopoDS_Shape > notQuadFaces;
409   int nbEdge, nbWire, nbFace = 0;
410   TopExp_Explorer exp( aShape, TopAbs_FACE );
411   for ( ; exp.More(); exp.Next() ) {
412     ++nbFace;
413     const TopoDS_Shape& face = exp.Current();
414     nbEdge = TAssocTool::Count( face, TopAbs_EDGE, 0 );
415     nbWire = TAssocTool::Count( face, TopAbs_WIRE, 0 );
416     if (  nbEdge!= 4 || nbWire!= 1 ) {
417       if ( !notQuadFaces.empty() ) {
418         if ( TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 ) != nbEdge ||
419              TAssocTool::Count( notQuadFaces.back(), TopAbs_WIRE, 0 ) != nbWire )
420           RETURN_BAD_RESULT("Different not quad faces");
421       }
422       notQuadFaces.push_back( face );
423     }
424   }
425   if ( !notQuadFaces.empty() )
426   {
427     if ( notQuadFaces.size() != 2 )
428       RETURN_BAD_RESULT("Bad nb not quad faces: " << notQuadFaces.size());
429
430     // check total nb faces
431     nbEdge = TAssocTool::Count( notQuadFaces.back(), TopAbs_EDGE, 0 );
432     if ( nbFace != nbEdge + 2 )
433       RETURN_BAD_RESULT("Bad nb of faces: " << nbFace << " but must be " << nbEdge + 2);
434   }
435 */
436   // no hypothesis
437   aStatus = SMESH_Hypothesis::HYP_OK;
438   return true;
439 }
440
441 //=======================================================================
442 //function : Compute
443 //purpose  : Compute mesh on a COMPOUND of SOLIDs
444 //=======================================================================
445
446 bool StdMeshers_Prism_3D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
447 {
448   SMESH_MesherHelper helper( theMesh );
449   myHelper = &helper;
450
451   int nbSolids = helper.Count( theShape, TopAbs_SOLID, /*skipSame=*/false );
452   if ( nbSolids < 1 )
453     return true;
454
455   Prism_3D::TPrismTopo prism;
456
457   if ( nbSolids == 1 )
458   {
459     return ( initPrism( prism, TopExp_Explorer( theShape, TopAbs_SOLID ).Current() ) &&
460              compute( prism ));
461   }
462
463   TopTools_IndexedDataMapOfShapeListOfShape faceToSolids;
464   TopExp::MapShapesAndAncestors( theShape, TopAbs_FACE, TopAbs_SOLID, faceToSolids );
465
466   // look for meshed FACEs ("source" FACEs) that must be prism bottoms
467   list< TopoDS_Face > meshedFaces;//, notQuadMeshedFaces, notQuadFaces;
468   const bool meshHasQuads = ( theMesh.NbQuadrangles() > 0 );
469   for ( int iF = 1; iF < faceToSolids.Extent(); ++iF )
470   {
471     const TopoDS_Face& face = TopoDS::Face( faceToSolids.FindKey( iF ));
472     SMESH_subMesh*   faceSM = theMesh.GetSubMesh( face );
473     if ( !faceSM->IsEmpty() )
474     {
475       if ( !meshHasQuads ||
476            !helper.IsSameElemGeometry( faceSM->GetSubMeshDS(), SMDSGeom_QUADRANGLE ) ||
477            !helper.IsStructured( faceSM ))
478         // notQuadMeshedFaces are of higher priority
479         meshedFaces.push_front( face );
480       else
481         meshedFaces.push_back( face );
482     }
483   }
484   //meshedFaces.splice( meshedFaces.begin(), notQuadMeshedFaces );
485
486   if ( meshedFaces.empty() )
487     return error( COMPERR_BAD_INPUT_MESH, "No meshed source faces found" );
488
489   TopTools_MapOfShape meshedSolids;
490   list< Prism_3D::TPrismTopo > meshedPrism;
491   TopTools_ListIteratorOfListOfShape solidIt;
492
493   while ( meshedSolids.Extent() < nbSolids )
494   {
495     if ( _computeCanceled )
496       return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
497
498     // compute prisms having avident computed source FACE
499     while ( !meshedFaces.empty() )
500     {
501       TopoDS_Face face = meshedFaces.front();
502       meshedFaces.pop_front();
503       solidIt.Initialize( faceToSolids.FindFromKey( face ));
504       for ( ; solidIt.More(); solidIt.Next() )
505       {
506         const TopoDS_Shape& solid = solidIt.Value();
507         if ( !meshedSolids.Add( solid ))
508           continue; // already computed prism
509
510         prism.Clear();
511         prism.myBottom = face;
512         if ( !initPrism( prism, solid ) ||
513              !compute( prism ))
514           return false;
515
516         meshedFaces.push_front( prism.myTop );
517         meshedPrism.push_back( prism );
518       }
519     }
520     if ( meshedSolids.Extent() == nbSolids )
521       break;
522
523     // project mesh from source FACEs of computed prisms to
524     // prisms sharing wall FACEs
525     list< Prism_3D::TPrismTopo >::iterator prismIt = meshedPrism.begin();
526     for ( ; prismIt != meshedPrism.end(); ++prismIt )
527     {
528       for ( size_t iW = 0; iW < prismIt->myWallQuads.size(); ++iW )
529       {
530         Prism_3D::TQuadList::iterator wQuad = prismIt->myWallQuads[iW].begin();
531         for ( ; wQuad != prismIt->myWallQuads[iW].end(); ++ wQuad )
532         {
533           const TopoDS_Face& wFace = (*wQuad)->face;
534           solidIt.Initialize( faceToSolids.FindFromKey( wFace ));
535           for ( ; solidIt.More(); solidIt.Next() )
536           {
537             const TopoDS_Shape& solid = solidIt.Value();
538             if ( meshedSolids.Contains( solid ))
539               continue; // already computed prism
540
541             // find a source FACE of the SOLID: it's a FACE sharing a bottom EDGE with wFace
542             const TopoDS_Edge& wEdge = (*wQuad)->side[ QUAD_TOP_SIDE ]->Edge(0);
543             PShapeIteratorPtr faceIt = myHelper->GetAncestors( wEdge, *myHelper->GetMesh(),
544                                                                TopAbs_FACE);
545             while ( const TopoDS_Shape* f = faceIt->next() )
546             {
547               const TopoDS_Face& candidateF = TopoDS::Face( *f );
548               prism.Clear();
549               prism.myBottom  = candidateF;
550               mySetErrorToSM = false;
551               if ( !myHelper->IsSubShape( candidateF, prismIt->myShape3D ) &&
552                    !myHelper->GetMesh()->GetSubMesh( candidateF )->IsMeshComputed() &&
553                    initPrism( prism, solid ) &&
554                    project2dMesh( prismIt->myBottom, candidateF))
555               {
556                 mySetErrorToSM = true;
557                 if ( !compute( prism ))
558                   return false;
559                 meshedFaces.push_front( prism.myTop );
560                 meshedFaces.push_front( prism.myBottom );
561                 meshedPrism.push_back( prism );
562                 meshedSolids.Add( solid );
563               }
564               InitComputeError();
565             }
566             mySetErrorToSM = true;
567             InitComputeError();
568           }
569         }
570       }
571       if ( !meshedFaces.empty() )
572         break; // to compute prisms with avident sources
573     }
574
575     // TODO. there are other ways to find out the source FACE:
576     // propagation, topological similarity, ect.
577
578
579     if ( meshedFaces.empty() ) // set same error to 10 not-computed solids
580     {
581       SMESH_ComputeErrorPtr err = SMESH_ComputeError::New
582         ( COMPERR_BAD_INPUT_MESH, "No meshed source face found", this );
583
584       const int maxNbErrors = 10; // limit nb errors not to overload the Compute dialog
585       TopExp_Explorer solid( theShape, TopAbs_SOLID );
586       for ( int i = 0; ( i < maxNbErrors && solid.More() ); ++i, solid.Next() )
587         if ( !meshedSolids.Contains( solid.Current() ))
588         {
589           SMESH_subMesh* sm = theMesh.GetSubMesh( solid.Current() );
590           sm->GetComputeError() = err;
591         }
592       return false;
593     }
594   }
595   return true;
596 }
597
598 //================================================================================
599 /*!
600  * \brief Find wall faces by bottom edges
601  */
602 //================================================================================
603
604 bool StdMeshers_Prism_3D::getWallFaces( Prism_3D::TPrismTopo & thePrism,
605                                         const int              totalNbFaces)
606 {
607   thePrism.myWallQuads.clear();
608
609   SMESH_Mesh* mesh = myHelper->GetMesh();
610
611   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, mesh );
612
613   TopTools_MapOfShape faceMap;
614   TopTools_IndexedDataMapOfShapeListOfShape edgeToFaces;   
615   TopExp::MapShapesAndAncestors( thePrism.myShape3D,
616                                  TopAbs_EDGE, TopAbs_FACE, edgeToFaces );
617
618   // ------------------------------
619   // Get the 1st row of wall FACEs
620   // ------------------------------
621
622   list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
623   std::list< int >::iterator     nbE = thePrism.myNbEdgesInWires.begin();
624   int iE = 0;
625   while ( edge != thePrism.myBottomEdges.end() )
626   {
627     ++iE;
628     if ( BRep_Tool::Degenerated( *edge ))
629     {
630       edge = thePrism.myBottomEdges.erase( edge );
631       --iE;
632       --(*nbE);
633     }
634     else
635     {
636       TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( *edge ));
637       for ( ; faceIt.More(); faceIt.Next() )
638       {
639         const TopoDS_Face& face = TopoDS::Face( faceIt.Value() );
640         if ( !thePrism.myBottom.IsSame( face ))
641         {
642           Prism_3D::TQuadList quadList( 1, quadAlgo->CheckNbEdges( *mesh, face ));
643           if ( !quadList.back() )
644             return toSM( error(TCom("Side face #") << shapeID( face )
645                                << " not meshable with quadrangles"));
646           if ( ! setBottomEdge( *edge, quadList.back(), face ))
647             return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
648           thePrism.myWallQuads.push_back( quadList );
649           faceMap.Add( face );
650           break;
651         }
652       }
653       ++edge;
654     }
655     if ( iE == *nbE )
656     {
657       iE = 0;
658       ++nbE;
659     }
660   }
661
662   // -------------------------
663   // Find the rest wall FACEs
664   // -------------------------
665
666   // Compose a vector of indixes of right neighbour FACE for each wall FACE
667   // that is not so evident in case of several WIREs
668   thePrism.myRightQuadIndex.clear();
669   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
670     thePrism.myRightQuadIndex.push_back( i+1 );
671   list< int >::iterator nbEinW = thePrism.myNbEdgesInWires.begin();
672   for ( int iLeft = 0; nbEinW != thePrism.myNbEdgesInWires.end(); ++nbEinW )
673   {
674     thePrism.myRightQuadIndex[ iLeft + *nbEinW - 1 ] = iLeft; // 1st EDGE index of a current WIRE
675     iLeft += *nbEinW;
676   }
677
678   while ( totalNbFaces - faceMap.Extent() > 2 )
679   {
680     // find wall FACEs adjacent to each of wallQuads by the right side EDGE
681     int nbKnownFaces;
682     do {
683       nbKnownFaces = faceMap.Extent();
684       StdMeshers_FaceSide *rightSide, *topSide; // sides of the quad
685       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
686       {
687         rightSide = thePrism.myWallQuads[i].back()->side[ QUAD_RIGHT_SIDE ];
688         for ( int iE = 0; iE < rightSide->NbEdges(); ++iE ) // rightSide can be composite
689         {
690           const TopoDS_Edge & rightE = rightSide->Edge( iE );
691           TopTools_ListIteratorOfListOfShape face( edgeToFaces.FindFromKey( rightE ));
692           for ( ; face.More(); face.Next() )
693             if ( faceMap.Add( face.Value() ))
694             {
695               // a new wall FACE encountered, store it in thePrism.myWallQuads
696               const int iRight = thePrism.myRightQuadIndex[i];
697               topSide = thePrism.myWallQuads[ iRight ].back()->side[ QUAD_TOP_SIDE ];
698               const TopoDS_Edge&   newBotE = topSide->Edge(0);
699               const TopoDS_Shape& newWallF = face.Value();
700               thePrism.myWallQuads[ iRight ].push_back( quadAlgo->CheckNbEdges( *mesh, newWallF ));
701               if ( !thePrism.myWallQuads[ iRight ].back() )
702                 return toSM( error(TCom("Side face #") << shapeID( newWallF ) <<
703                                    " not meshable with quadrangles"));
704               if ( ! setBottomEdge( newBotE, thePrism.myWallQuads[ iRight ].back(), newWallF ))
705                 return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
706             }
707         }
708       }
709     } while ( nbKnownFaces != faceMap.Extent() );
710
711     // find wall FACEs adjacent to each of thePrism.myWallQuads by the top side EDGE
712     if ( totalNbFaces - faceMap.Extent() > 2 )
713     {
714       for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
715       {
716         StdMeshers_FaceSide* topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
717         const TopoDS_Edge &     topE = topSide->Edge( 0 );
718         if ( topSide->NbEdges() > 1 )
719           return toSM( error(COMPERR_BAD_SHAPE, TCom("Side face #") <<
720                              shapeID( thePrism.myWallQuads[i].back()->face )
721                              << " has a composite top edge"));
722         TopTools_ListIteratorOfListOfShape faceIt( edgeToFaces.FindFromKey( topE ));
723         for ( ; faceIt.More(); faceIt.Next() )
724           if ( faceMap.Add( faceIt.Value() ))
725           {
726             // a new wall FACE encountered, store it in wallQuads
727             thePrism.myWallQuads[ i ].push_back( quadAlgo->CheckNbEdges( *mesh, faceIt.Value() ));
728             if ( !thePrism.myWallQuads[ i ].back() )
729               return toSM( error(TCom("Side face #") << shapeID( faceIt.Value() ) <<
730                                  " not meshable with quadrangles"));
731             if ( ! setBottomEdge( topE, thePrism.myWallQuads[ i ].back(), faceIt.Value() ))
732               return toSM( error(TCom("Composite 'horizontal' edges are not supported")));
733             if ( totalNbFaces - faceMap.Extent() == 2 )
734             {
735               i = thePrism.myWallQuads.size(); // to quit from the outer loop
736               break;
737             }
738           }
739       }
740     }
741   } // while ( totalNbFaces - faceMap.Extent() > 2 )
742
743   // ------------------
744   // Find the top FACE
745   // ------------------
746
747   if ( thePrism.myTop.IsNull() )
748   {
749     // now only top and bottom FACEs are not in the faceMap
750     faceMap.Add( thePrism.myBottom );
751     for ( TopExp_Explorer f( thePrism.myShape3D, TopAbs_FACE );f.More(); f.Next() )
752       if ( !faceMap.Contains( f.Current() )) {
753         thePrism.myTop = TopoDS::Face( f.Current() );
754         break;
755       }
756     if ( thePrism.myTop.IsNull() )
757       return toSM( error("Top face not found"));
758   }
759
760   // Check that the top FACE shares all the top EDGEs
761   for ( size_t i = 0; i < thePrism.myWallQuads.size(); ++i )
762   {
763     StdMeshers_FaceSide* topSide = thePrism.myWallQuads[i].back()->side[ QUAD_TOP_SIDE ];
764     const TopoDS_Edge &     topE = topSide->Edge( 0 );
765     if ( !myHelper->IsSubShape( topE, thePrism.myTop ))
766       return toSM( error( TCom("Wrong source face (#") << shapeID( thePrism.myBottom )));
767   }
768
769   return true;
770 }
771
772 //=======================================================================
773 //function : compute
774 //purpose  : Compute mesh on a SOLID
775 //=======================================================================
776
777 bool StdMeshers_Prism_3D::compute(const Prism_3D::TPrismTopo& thePrism)
778 {
779   myHelper->IsQuadraticSubMesh( thePrism.myShape3D );
780   if ( _computeCanceled )
781     return toSM( error( SMESH_ComputeError::New(COMPERR_CANCELED)));
782
783   // Make all side FACEs of thePrism meshed with quads
784   if ( !computeWalls( thePrism ))
785     return false;
786
787   // Analyse mesh and geometry to find block sub-shapes and submeshes
788   if ( !myBlock.Init( myHelper, thePrism ))
789     return toSM( error( myBlock.GetError()));
790
791   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
792
793   int volumeID = meshDS->ShapeToIndex( thePrism.myShape3D );
794
795
796   // To compute coordinates of a node inside a block, it is necessary to know
797   // 1. normalized parameters of the node by which
798   // 2. coordinates of node projections on all block sub-shapes are computed
799
800   // So we fill projections on vertices at once as they are same for all nodes
801   myShapeXYZ.resize( myBlock.NbSubShapes() );
802   for ( int iV = SMESH_Block::ID_FirstV; iV < SMESH_Block::ID_FirstE; ++iV ) {
803     myBlock.VertexPoint( iV, myShapeXYZ[ iV ]);
804     SHOWYXZ("V point " <<iV << " ", myShapeXYZ[ iV ]);
805   }
806
807   // Projections on the top and bottom faces are taken from nodes existing
808   // on these faces; find correspondence between bottom and top nodes
809   myBotToColumnMap.clear();
810   if ( !assocOrProjBottom2Top() ) // it also fills myBotToColumnMap
811     return false;
812
813
814   // Create nodes inside the block
815
816   // try to use transformation (issue 0020680)
817   vector<gp_Trsf> trsf;
818   if ( myBlock.GetLayersTransformation(trsf))
819   {
820     // loop on nodes inside the bottom face
821     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
822     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
823     {
824       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
825       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
826         continue; // node is not inside face 
827
828       // column nodes; middle part of the column are zero pointers
829       TNodeColumn& column = bot_column->second;
830       TNodeColumn::iterator columnNodes = column.begin();
831       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
832       {
833         const SMDS_MeshNode* & node = *columnNodes;
834         if ( node ) continue; // skip bottom or top node
835
836         gp_XYZ coords = tBotNode.GetCoords();
837         trsf[z-1].Transforms( coords );
838         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
839         meshDS->SetNodeInVolume( node, volumeID );
840       }
841     } // loop on bottom nodes
842   }
843   else // use block approach
844   {
845     // loop on nodes inside the bottom face
846     Prism_3D::TNode prevBNode;
847     TNode2ColumnMap::iterator bot_column = myBotToColumnMap.begin();
848     for ( ; bot_column != myBotToColumnMap.end(); ++bot_column )
849     {
850       const Prism_3D::TNode& tBotNode = bot_column->first; // bottom TNode
851       if ( tBotNode.GetPositionType() != SMDS_TOP_FACE )
852         continue; // node is not inside face 
853
854       // column nodes; middle part of the column are zero pointers
855       TNodeColumn& column = bot_column->second;
856
857       // compute bottom node parameters
858       gp_XYZ paramHint(-1,-1,-1);
859       if ( prevBNode.IsNeighbor( tBotNode ))
860         paramHint = prevBNode.GetParams();
861       if ( !myBlock.ComputeParameters( tBotNode.GetCoords(), tBotNode.ChangeParams(),
862                                        ID_BOT_FACE, paramHint ))
863         return toSM( error(TCom("Can't compute normalized parameters for node ")
864                            << tBotNode.myNode->GetID() << " on the face #"
865                            << myBlock.SubMesh( ID_BOT_FACE )->GetId() ));
866       prevBNode = tBotNode;
867
868       myShapeXYZ[ ID_BOT_FACE ] = tBotNode.GetCoords();
869       gp_XYZ botParams          = tBotNode.GetParams();
870
871       // compute top node parameters
872       myShapeXYZ[ ID_TOP_FACE ] = gpXYZ( column.back() );
873       gp_XYZ topParams = botParams;
874       topParams.SetZ( 1 );
875       if ( column.size() > 2 ) {
876         gp_Pnt topCoords = myShapeXYZ[ ID_TOP_FACE ];
877         if ( !myBlock.ComputeParameters( topCoords, topParams, ID_TOP_FACE, topParams ))
878           return toSM( error(TCom("Can't compute normalized parameters ")
879                              << "for node " << column.back()->GetID()
880                              << " on the face #"<< column.back()->getshapeId() ));
881       }
882
883       // vertical loop
884       TNodeColumn::iterator columnNodes = column.begin();
885       for ( int z = 0; columnNodes != column.end(); ++columnNodes, ++z)
886       {
887         const SMDS_MeshNode* & node = *columnNodes;
888         if ( node ) continue; // skip bottom or top node
889
890         // params of a node to create
891         double rz = (double) z / (double) ( column.size() - 1 );
892         gp_XYZ params = botParams * ( 1 - rz ) + topParams * rz;
893
894         // set coords on all faces and nodes
895         const int nbSideFaces = 4;
896         int sideFaceIDs[nbSideFaces] = { SMESH_Block::ID_Fx0z,
897                                          SMESH_Block::ID_Fx1z,
898                                          SMESH_Block::ID_F0yz,
899                                          SMESH_Block::ID_F1yz };
900         for ( int iF = 0; iF < nbSideFaces; ++iF )
901           if ( !setFaceAndEdgesXYZ( sideFaceIDs[ iF ], params, z ))
902             return false;
903
904         // compute coords for a new node
905         gp_XYZ coords;
906         if ( !SMESH_Block::ShellPoint( params, myShapeXYZ, coords ))
907           return toSM( error("Can't compute coordinates by normalized parameters"));
908
909         SHOWYXZ("TOPFacePoint ",myShapeXYZ[ ID_TOP_FACE]);
910         SHOWYXZ("BOT Node "<< tBotNode.myNode->GetID(),gpXYZ(tBotNode.myNode));
911         SHOWYXZ("ShellPoint ",coords);
912
913         // create a node
914         node = meshDS->AddNode( coords.X(), coords.Y(), coords.Z() );
915         meshDS->SetNodeInVolume( node, volumeID );
916       }
917     } // loop on bottom nodes
918   }
919
920   // Create volumes
921
922   SMESHDS_SubMesh* smDS = myBlock.SubMeshDS( ID_BOT_FACE );
923   if ( !smDS ) return toSM( error(COMPERR_BAD_INPUT_MESH, "Null submesh"));
924
925   // loop on bottom mesh faces
926   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
927   while ( faceIt->more() )
928   {
929     const SMDS_MeshElement* face = faceIt->next();
930     if ( !face || face->GetType() != SMDSAbs_Face )
931       continue;
932
933     // find node columns for each node
934     int nbNodes = face->NbCornerNodes();
935     vector< const TNodeColumn* > columns( nbNodes );
936     for ( int i = 0; i < nbNodes; ++i )
937     {
938       const SMDS_MeshNode* n = face->GetNode( i );
939       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
940         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
941         if ( bot_column == myBotToColumnMap.end() )
942           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
943         columns[ i ] = & bot_column->second;
944       }
945       else {
946         columns[ i ] = myBlock.GetNodeColumn( n );
947         if ( !columns[ i ] )
948           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
949       }
950     }
951     // create prisms
952     AddPrisms( columns, myHelper );
953
954   } // loop on bottom mesh faces
955
956   // clear data
957   myBotToColumnMap.clear();
958   myBlock.Clear();
959         
960   return true;
961 }
962
963 //=======================================================================
964 //function : computeWalls
965 //purpose  : Compute 2D mesh on walls FACEs of a prism
966 //=======================================================================
967
968 bool StdMeshers_Prism_3D::computeWalls(const Prism_3D::TPrismTopo& thePrism)
969 {
970   SMESH_Mesh*     mesh = myHelper->GetMesh();
971   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
972
973   TProjction1dAlgo* projector1D = TProjction1dAlgo::instance( this );
974   StdMeshers_Quadrangle_2D* quadAlgo = TQuadrangleAlgo::instance( this, mesh );
975
976   SMESH_HypoFilter hyp1dFilter( SMESH_HypoFilter::IsAlgo(),/*not=*/true);
977   hyp1dFilter.And( SMESH_HypoFilter::HasDim( 1 ));
978   hyp1dFilter.And( SMESH_HypoFilter::IsMoreLocalThan( thePrism.myShape3D, *mesh ));
979
980   // Discretize equally 'vertical' EDGEs
981   // -----------------------------------
982   // find source FACE sides for projection: either already computed ones or
983   // the 'most composite' ones
984   multimap< int, int > wgt2quad;
985   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
986   {
987     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
988     int wgt = 0; // "weight"
989     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
990     {
991       StdMeshers_FaceSide* lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];
992       for ( int i = 0; i < lftSide->NbEdges(); ++i )
993       {
994         ++wgt;
995         const TopoDS_Edge& E = lftSide->Edge(i);
996         if ( mesh->GetSubMesh( E )->IsMeshComputed() )
997           wgt += 10;
998         else if ( mesh->GetHypothesis( E, hyp1dFilter, true )) // local hypothesis!
999           wgt += 100;
1000       }
1001     }
1002     wgt2quad.insert( make_pair( wgt, iW ));
1003   }
1004
1005   // Project 'vertical' EDGEs, from left to right
1006   multimap< int, int >::reverse_iterator w2q = wgt2quad.rbegin();
1007   for ( ; w2q != wgt2quad.rend(); ++w2q )
1008   {
1009     const int iW = w2q->second;
1010     const Prism_3D::TQuadList&         quads = thePrism.myWallQuads[ iW ];
1011     Prism_3D::TQuadList::const_iterator quad = quads.begin();
1012     for ( ; quad != quads.end(); ++quad )
1013     {
1014       StdMeshers_FaceSide* rgtSide = (*quad)->side[ QUAD_RIGHT_SIDE ]; // tgt
1015       StdMeshers_FaceSide* lftSide = (*quad)->side[ QUAD_LEFT_SIDE ];  // src
1016       bool swapLeftRight = ( lftSide->NbSegments( /*update=*/true ) == 0 &&
1017                              rgtSide->NbSegments( /*update=*/true )  > 0 );
1018       if ( swapLeftRight )
1019         std::swap( lftSide, rgtSide );
1020
1021       // assure that all the source (left) EDGEs are meshed
1022       int nbSrcSegments = 0;
1023       for ( int i = 0; i < lftSide->NbEdges(); ++i )
1024       {
1025         const TopoDS_Edge& srcE = lftSide->Edge(i);
1026         SMESH_subMesh*    srcSM = mesh->GetSubMesh( srcE );
1027         if ( !srcSM->IsMeshComputed() ) {
1028           srcSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1029           srcSM->ComputeStateEngine       ( SMESH_subMesh::COMPUTE );
1030           if ( !srcSM->IsMeshComputed() )
1031             return false;
1032         }
1033         nbSrcSegments += srcSM->GetSubMeshDS()->NbElements();
1034       }
1035       // check target EDGEs
1036       int nbTgtMeshed = 0, nbTgtSegments = 0;
1037       vector< bool > isTgtEdgeComputed( rgtSide->NbEdges() );
1038       for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1039       {
1040         const TopoDS_Edge& tgtE = rgtSide->Edge(i);
1041         SMESH_subMesh*    tgtSM = mesh->GetSubMesh( tgtE );
1042         if (( isTgtEdgeComputed[ i ] = tgtSM->IsMeshComputed() )) {
1043           ++nbTgtMeshed;
1044           nbTgtSegments += tgtSM->GetSubMeshDS()->NbElements();
1045         }
1046       }
1047       if ( rgtSide->NbEdges() == nbTgtMeshed ) // all tgt EDGEs meshed
1048       {
1049         if ( nbTgtSegments != nbSrcSegments )
1050         {
1051           for ( int i = 0; i < lftSide->NbEdges(); ++i )
1052             addBadInputElements( meshDS->MeshElements( lftSide->Edge( i )));
1053           for ( int i = 0; i < rgtSide->NbEdges(); ++i )
1054             addBadInputElements( meshDS->MeshElements( rgtSide->Edge( i )));
1055           return toSM( error( TCom("Different nb of segment on logically vertical edges #")
1056                               << shapeID( lftSide->Edge(0) ) << " and #"
1057                               << shapeID( rgtSide->Edge(0) ) << ": "
1058                               << nbSrcSegments << " != " << nbTgtSegments ));
1059         }
1060         continue;
1061       }
1062       // Compute
1063       if ( nbTgtMeshed == 0 )
1064       {
1065         // compute nodes on target VERTEXes
1066         const UVPtStructVec&  srcNodeStr = lftSide->GetUVPtStruct();
1067         if ( srcNodeStr.size() == 0 )
1068           return toSM( error( TCom("Invalid node positions on edge #") <<
1069                               shapeID( lftSide->Edge(0) )));
1070         vector< SMDS_MeshNode* > newNodes( srcNodeStr.size() );
1071         for ( int is2ndV = 0; is2ndV < 2; ++is2ndV )
1072         {
1073           const TopoDS_Edge& E = rgtSide->Edge( is2ndV ? rgtSide->NbEdges()-1 : 0 );
1074           TopoDS_Vertex      v = myHelper->IthVertex( is2ndV, E );
1075           mesh->GetSubMesh( v )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1076           const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, meshDS );
1077           newNodes[ is2ndV ? 0 : newNodes.size()-1 ] = (SMDS_MeshNode*) n;
1078         }
1079
1080         // compute nodes on target EDGEs
1081         rgtSide->Reverse(); // direct it same as the lftSide
1082         myHelper->SetElementsOnShape( false );
1083         TopoDS_Edge tgtEdge;
1084         for ( size_t iN = 1; iN < srcNodeStr.size()-1; ++iN ) // add nodes
1085         {
1086           gp_Pnt       p = rgtSide->Value3d  ( srcNodeStr[ iN ].normParam );
1087           double       u = rgtSide->Parameter( srcNodeStr[ iN ].normParam, tgtEdge );
1088           newNodes[ iN ] = meshDS->AddNode( p.X(), p.Y(), p.Z() );
1089           meshDS->SetNodeOnEdge( newNodes[ iN ], tgtEdge, u );
1090         }
1091         for ( size_t iN = 1; iN < srcNodeStr.size(); ++iN ) // add segments
1092         {
1093           SMDS_MeshElement* newEdge = myHelper->AddEdge( newNodes[ iN-1 ], newNodes[ iN ] );
1094           std::pair<int, TopAbs_ShapeEnum> id2type = 
1095             myHelper->GetMediumPos( newNodes[ iN-1 ], newNodes[ iN ] );
1096           if ( id2type.second == TopAbs_EDGE )
1097           {
1098             meshDS->SetMeshElementOnShape( newEdge, id2type.first );
1099           }
1100           else // new nodes are on different EDGEs; put one of them on VERTEX
1101           {
1102             const int      edgeIndex = rgtSide->EdgeIndex( srcNodeStr[ iN-1 ].normParam );
1103             const double vertexParam = rgtSide->LastParameter( edgeIndex );
1104             const gp_Pnt           p = BRep_Tool::Pnt( rgtSide->LastVertex( edgeIndex ));
1105             const int         isPrev = ( Abs( srcNodeStr[ iN-1 ].normParam - vertexParam ) <
1106                                          Abs( srcNodeStr[ iN   ].normParam - vertexParam ));
1107             meshDS->SetMeshElementOnShape( newEdge, newNodes[ iN-(1-isPrev) ]->getshapeId() );
1108             meshDS->UnSetNodeOnShape( newNodes[ iN-isPrev ] );
1109             meshDS->SetNodeOnVertex ( newNodes[ iN-isPrev ], rgtSide->LastVertex( edgeIndex ));
1110             meshDS->MoveNode( newNodes[ iN-isPrev ], p.X(), p.Y(), p.Z() );
1111           }
1112         }
1113         myHelper->SetElementsOnShape( true );
1114         for ( int i = 0; i < rgtSide->NbEdges(); ++i ) // update state of sub-meshes
1115         {
1116           const TopoDS_Edge& E = rgtSide->Edge( i );
1117           SMESH_subMesh* tgtSM = mesh->GetSubMesh( E );
1118           tgtSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1119         }
1120
1121         // to continue projection from the just computed side as a source
1122         if ( !swapLeftRight && rgtSide->NbEdges() > 1 && w2q->second == iW )
1123         {
1124           std::pair<int,int> wgt2quadKeyVal( w2q->first + 1, thePrism.myRightQuadIndex[ iW ]);
1125           wgt2quad.insert( wgt2quadKeyVal ); // it will be skipped by ++w2q
1126           wgt2quad.insert( wgt2quadKeyVal );
1127           w2q = wgt2quad.rbegin();
1128         }
1129       }
1130       else
1131       {
1132         // HOPE assigned hypotheses are OK, so that equal nb of segments will be generated
1133         //return toSM( error("Partial projection not implemented"));
1134       }
1135     } // loop on quads of a composite wall side
1136   } // loop on the ordered wall sides
1137
1138
1139
1140   for ( size_t iW = 0; iW != thePrism.myWallQuads.size(); ++iW )
1141   {
1142     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[iW].begin();
1143     for ( ; quad != thePrism.myWallQuads[iW].end(); ++quad )
1144     {
1145       // Top EDGEs must be projections from the bottom ones
1146       // to compute stuctured quad mesh on wall FACEs
1147       // ---------------------------------------------------
1148       const TopoDS_Edge& botE = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge(0);
1149       const TopoDS_Edge& topE = (*quad)->side[ QUAD_TOP_SIDE    ]->Edge(0);
1150
1151       projector1D->myHyp.SetSourceEdge( botE );
1152
1153       SMESH_subMesh* tgtEdgeSm = mesh->GetSubMesh( topE );
1154       if ( !tgtEdgeSm->IsMeshComputed() )
1155       {
1156         // compute nodes on VERTEXes
1157         tgtEdgeSm->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1158         // project segments
1159         projector1D->InitComputeError();
1160         bool ok = projector1D->Compute( *mesh, topE );
1161         if ( !ok )
1162         {
1163           SMESH_ComputeErrorPtr err = projector1D->GetComputeError();
1164           if ( err->IsOK() ) err->myName = COMPERR_ALGO_FAILED;
1165           tgtEdgeSm->GetComputeError() = err;
1166           return false;
1167         }
1168       }
1169       tgtEdgeSm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1170
1171       // Compute quad mesh on wall FACEs
1172       // -------------------------------
1173       const TopoDS_Face& face = (*quad)->face;
1174       SMESH_subMesh* fSM = mesh->GetSubMesh( face );
1175       if ( fSM->IsMeshComputed() ) continue;
1176
1177       // make all EDGES meshed
1178       fSM->ComputeSubMeshStateEngine( SMESH_subMesh::COMPUTE );
1179       if ( !fSM->SubMeshesComputed() )
1180         return toSM( error( COMPERR_BAD_INPUT_MESH,
1181                             "Not all edges have valid algorithm and hypothesis"));
1182       // mesh the <face>
1183       quadAlgo->InitComputeError();
1184       bool ok = quadAlgo->Compute( *mesh, face );
1185       fSM->GetComputeError() = quadAlgo->GetComputeError();
1186       if ( !ok )
1187         return false;
1188       fSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1189     }
1190   }
1191
1192   return true;
1193 }
1194
1195 //=======================================================================
1196 //function : Evaluate
1197 //purpose  : 
1198 //=======================================================================
1199
1200 bool StdMeshers_Prism_3D::Evaluate(SMESH_Mesh&         theMesh,
1201                                    const TopoDS_Shape& theShape,
1202                                    MapShapeNbElems&    aResMap)
1203 {
1204   if ( theShape.ShapeType() == TopAbs_COMPOUND )
1205   {
1206     bool ok = true;
1207     for ( TopoDS_Iterator it( theShape ); it.More(); it.Next() )
1208       ok &= Evaluate( theMesh, it.Value(), aResMap );
1209     return ok;
1210   }
1211   SMESH_MesherHelper helper( theMesh );
1212   myHelper = &helper;
1213   myHelper->SetSubShape( theShape );
1214
1215   // find face contains only triangles
1216   vector < SMESH_subMesh * >meshFaces;
1217   TopTools_SequenceOfShape aFaces;
1218   int NumBase = 0, i = 0, NbQFs = 0;
1219   for (TopExp_Explorer exp(theShape, TopAbs_FACE); exp.More(); exp.Next()) {
1220     i++;
1221     aFaces.Append(exp.Current());
1222     SMESH_subMesh *aSubMesh = theMesh.GetSubMesh(exp.Current());
1223     meshFaces.push_back(aSubMesh);
1224     MapShapeNbElemsItr anIt = aResMap.find(meshFaces[i-1]);
1225     if( anIt==aResMap.end() )
1226       return toSM( error( "Submesh can not be evaluated"));
1227
1228     std::vector<int> aVec = (*anIt).second;
1229     int nbtri = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1230     int nbqua = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1231     if( nbtri==0 && nbqua>0 ) {
1232       NbQFs++;
1233     }
1234     if( nbtri>0 ) {
1235       NumBase = i;
1236     }
1237   }
1238
1239   if(NbQFs<4) {
1240     std::vector<int> aResVec(SMDSEntity_Last);
1241     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1242     SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1243     aResMap.insert(std::make_pair(sm,aResVec));
1244     return toSM( error( "Submesh can not be evaluated" ));
1245   }
1246
1247   if(NumBase==0) NumBase = 1; // only quads => set 1 faces as base
1248
1249   // find number of 1d elems for base face
1250   int nb1d = 0;
1251   TopTools_MapOfShape Edges1;
1252   for (TopExp_Explorer exp(aFaces.Value(NumBase), TopAbs_EDGE); exp.More(); exp.Next()) {
1253     Edges1.Add(exp.Current());
1254     SMESH_subMesh *sm = theMesh.GetSubMesh(exp.Current());
1255     if( sm ) {
1256       MapShapeNbElemsItr anIt = aResMap.find(sm);
1257       if( anIt == aResMap.end() ) continue;
1258       std::vector<int> aVec = (*anIt).second;
1259       nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
1260     }
1261   }
1262   // find face opposite to base face
1263   int OppNum = 0;
1264   for(i=1; i<=6; i++) {
1265     if(i==NumBase) continue;
1266     bool IsOpposite = true;
1267     for(TopExp_Explorer exp(aFaces.Value(i), TopAbs_EDGE); exp.More(); exp.Next()) {
1268       if( Edges1.Contains(exp.Current()) ) {
1269         IsOpposite = false;
1270         break;
1271       }
1272     }
1273     if(IsOpposite) {
1274       OppNum = i;
1275       break;
1276     }
1277   }
1278   // find number of 2d elems on side faces
1279   int nb2d = 0;
1280   for(i=1; i<=6; i++) {
1281     if( i==OppNum || i==NumBase ) continue;
1282     MapShapeNbElemsItr anIt = aResMap.find( meshFaces[i-1] );
1283     if( anIt == aResMap.end() ) continue;
1284     std::vector<int> aVec = (*anIt).second;
1285     nb2d += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1286   }
1287   
1288   MapShapeNbElemsItr anIt = aResMap.find( meshFaces[NumBase-1] );
1289   std::vector<int> aVec = (*anIt).second;
1290   bool IsQuadratic = (aVec[SMDSEntity_Quad_Triangle]>aVec[SMDSEntity_Triangle]) ||
1291                      (aVec[SMDSEntity_Quad_Quadrangle]>aVec[SMDSEntity_Quadrangle]);
1292   int nb2d_face0_3 = Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
1293   int nb2d_face0_4 = Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
1294   int nb0d_face0 = aVec[SMDSEntity_Node];
1295   int nb1d_face0_int = ( nb2d_face0_3*3 + nb2d_face0_4*4 - nb1d ) / 2;
1296
1297   std::vector<int> aResVec(SMDSEntity_Last);
1298   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1299   if(IsQuadratic) {
1300     aResVec[SMDSEntity_Quad_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1301     aResVec[SMDSEntity_Quad_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1302     aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
1303   }
1304   else {
1305     aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
1306     aResVec[SMDSEntity_Penta] = nb2d_face0_3 * ( nb2d/nb1d );
1307     aResVec[SMDSEntity_Hexa] = nb2d_face0_4 * ( nb2d/nb1d );
1308   }
1309   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1310   aResMap.insert(std::make_pair(sm,aResVec));
1311
1312   return true;
1313 }
1314
1315 //================================================================================
1316 /*!
1317  * \brief Create prisms
1318  * \param columns - columns of nodes generated from nodes of a mesh face
1319  * \param helper - helper initialized by mesh and shape to add prisms to
1320  */
1321 //================================================================================
1322
1323 void StdMeshers_Prism_3D::AddPrisms( vector<const TNodeColumn*> & columns,
1324                                      SMESH_MesherHelper*          helper)
1325 {
1326   int nbNodes = columns.size();
1327   int nbZ     = columns[0]->size();
1328   if ( nbZ < 2 ) return;
1329
1330   // find out orientation
1331   bool isForward = true;
1332   SMDS_VolumeTool vTool;
1333   int z = 1;
1334   switch ( nbNodes ) {
1335   case 3: {
1336     SMDS_VolumeOfNodes tmpPenta ( (*columns[0])[z-1], // bottom
1337                                   (*columns[1])[z-1],
1338                                   (*columns[2])[z-1],
1339                                   (*columns[0])[z],   // top
1340                                   (*columns[1])[z],
1341                                   (*columns[2])[z] );
1342     vTool.Set( &tmpPenta );
1343     isForward  = vTool.IsForward();
1344     break;
1345   }
1346   case 4: {
1347     SMDS_VolumeOfNodes tmpHex( (*columns[0])[z-1], (*columns[1])[z-1], // bottom
1348                                (*columns[2])[z-1], (*columns[3])[z-1],
1349                                (*columns[0])[z],   (*columns[1])[z],   // top
1350                                (*columns[2])[z],   (*columns[3])[z] );
1351     vTool.Set( &tmpHex );
1352     isForward  = vTool.IsForward();
1353     break;
1354   }
1355   default:
1356     const int di = (nbNodes+1) / 3;
1357     SMDS_VolumeOfNodes tmpVol ( (*columns[0]   )[z-1],
1358                                 (*columns[di]  )[z-1],
1359                                 (*columns[2*di])[z-1],
1360                                 (*columns[0]   )[z],
1361                                 (*columns[di]  )[z],
1362                                 (*columns[2*di])[z] );
1363     vTool.Set( &tmpVol );
1364     isForward  = vTool.IsForward();
1365   }
1366
1367   // vertical loop on columns
1368
1369   helper->SetElementsOnShape( true );
1370
1371   switch ( nbNodes ) {
1372
1373   case 3: { // ---------- pentahedra
1374     const int i1 = isForward ? 1 : 2;
1375     const int i2 = isForward ? 2 : 1;
1376     for ( z = 1; z < nbZ; ++z )
1377       helper->AddVolume( (*columns[0 ])[z-1], // bottom
1378                          (*columns[i1])[z-1],
1379                          (*columns[i2])[z-1],
1380                          (*columns[0 ])[z],   // top
1381                          (*columns[i1])[z],
1382                          (*columns[i2])[z] );
1383     break;
1384   }
1385   case 4: { // ---------- hexahedra
1386     const int i1 = isForward ? 1 : 3;
1387     const int i3 = isForward ? 3 : 1;
1388     for ( z = 1; z < nbZ; ++z )
1389       helper->AddVolume( (*columns[0])[z-1], (*columns[i1])[z-1], // bottom
1390                          (*columns[2])[z-1], (*columns[i3])[z-1],
1391                          (*columns[0])[z],   (*columns[i1])[z],     // top
1392                          (*columns[2])[z],   (*columns[i3])[z] );
1393     break;
1394   }
1395   case 6: { // ---------- octahedra
1396     const int iBase1 = isForward ? -1 : 0;
1397     const int iBase2 = isForward ?  0 :-1;
1398     for ( z = 1; z < nbZ; ++z )
1399       helper->AddVolume( (*columns[0])[z+iBase1], (*columns[1])[z+iBase1], // bottom or top
1400                          (*columns[2])[z+iBase1], (*columns[3])[z+iBase1],
1401                          (*columns[4])[z+iBase1], (*columns[5])[z+iBase1],
1402                          (*columns[0])[z+iBase2], (*columns[1])[z+iBase2], // top or bottom
1403                          (*columns[2])[z+iBase2], (*columns[3])[z+iBase2],
1404                          (*columns[4])[z+iBase2], (*columns[5])[z+iBase2] );
1405     break;
1406   }
1407   default: // ---------- polyhedra
1408     vector<int> quantities( 2 + nbNodes, 4 );
1409     quantities[0] = quantities[1] = nbNodes;
1410     columns.resize( nbNodes + 1 );
1411     columns[ nbNodes ] = columns[ 0 ];
1412     const int i1 = isForward ? 1 : 3;
1413     const int i3 = isForward ? 3 : 1;
1414     const int iBase1 = isForward ? -1 : 0;
1415     const int iBase2 = isForward ?  0 :-1;
1416     vector<const SMDS_MeshNode*> nodes( 2*nbNodes + 4*nbNodes);
1417     for ( z = 1; z < nbZ; ++z )
1418     {
1419       for ( int i = 0; i < nbNodes; ++i ) {
1420         nodes[ i             ] = (*columns[ i ])[z+iBase1]; // bottom or top
1421         nodes[ 2*nbNodes-i-1 ] = (*columns[ i ])[z+iBase2]; // top or bottom
1422         // side
1423         int di = 2*nbNodes + 4*i;
1424         nodes[ di+0 ] = (*columns[i  ])[z  ];
1425         nodes[ di+i1] = (*columns[i+1])[z  ];
1426         nodes[ di+2 ] = (*columns[i+1])[z-1];
1427         nodes[ di+i3] = (*columns[i  ])[z-1];
1428       }
1429       helper->AddPolyhedralVolume( nodes, quantities );
1430     }
1431
1432   } // switch ( nbNodes )
1433 }
1434
1435 //================================================================================
1436 /*!
1437  * \brief Find correspondence between bottom and top nodes
1438  *  If elements on the bottom and top faces are topologically different,
1439  *  and projection is possible and allowed, perform the projection
1440  *  \retval bool - is a success or not
1441  */
1442 //================================================================================
1443
1444 bool StdMeshers_Prism_3D::assocOrProjBottom2Top()
1445 {
1446   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1447   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1448
1449   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1450   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1451
1452   if ( !botSMDS || botSMDS->NbElements() == 0 )
1453     return toSM( error(TCom("No elememts on face #") << botSM->GetId() ));
1454
1455   bool needProject = !topSM->IsMeshComputed();
1456   if ( !needProject && 
1457        (botSMDS->NbElements() != topSMDS->NbElements() ||
1458         botSMDS->NbNodes()    != topSMDS->NbNodes()))
1459   {
1460     MESSAGE("nb elem bot " << botSMDS->NbElements() <<
1461             " top " << ( topSMDS ? topSMDS->NbElements() : 0 ));
1462     MESSAGE("nb node bot " << botSMDS->NbNodes() <<
1463             " top " << ( topSMDS ? topSMDS->NbNodes() : 0 ));
1464     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1465                        <<" and #"<< topSM->GetId() << " seems different" ));
1466   }
1467
1468   if ( 0/*needProject && !myProjectTriangles*/ )
1469     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1470                        <<" and #"<< topSM->GetId() << " seems different" ));
1471   ///RETURN_BAD_RESULT("Need to project but not allowed");
1472
1473   if ( needProject )
1474   {
1475     return projectBottomToTop();
1476   }
1477
1478   TopoDS_Face botFace = TopoDS::Face( myBlock.Shape( ID_BOT_FACE ));
1479   TopoDS_Face topFace = TopoDS::Face( myBlock.Shape( ID_TOP_FACE ));
1480   // associate top and bottom faces
1481   TAssocTool::TShapeShapeMap shape2ShapeMap;
1482   if ( !TAssocTool::FindSubShapeAssociation( botFace, myBlock.Mesh(),
1483                                              topFace, myBlock.Mesh(),
1484                                              shape2ShapeMap) )
1485     return toSM( error(TCom("Topology of faces #") << botSM->GetId()
1486                        <<" and #"<< topSM->GetId() << " seems different" ));
1487
1488   // Find matching nodes of top and bottom faces
1489   TNodeNodeMap n2nMap;
1490   if ( ! TAssocTool::FindMatchingNodesOnFaces( botFace, myBlock.Mesh(),
1491                                                topFace, myBlock.Mesh(),
1492                                                shape2ShapeMap, n2nMap ))
1493     return toSM( error(TCom("Mesh on faces #") << botSM->GetId()
1494                        <<" and #"<< topSM->GetId() << " seems different" ));
1495
1496   // Fill myBotToColumnMap
1497
1498   int zSize = myBlock.VerticalSize();
1499   //TNode prevTNode;
1500   TNodeNodeMap::iterator bN_tN = n2nMap.begin();
1501   for ( ; bN_tN != n2nMap.end(); ++bN_tN )
1502   {
1503     const SMDS_MeshNode* botNode = bN_tN->first;
1504     const SMDS_MeshNode* topNode = bN_tN->second;
1505     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1506       continue; // wall columns are contained in myBlock
1507     // create node column
1508     Prism_3D::TNode bN( botNode );
1509     TNode2ColumnMap::iterator bN_col = 
1510       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1511     TNodeColumn & column = bN_col->second;
1512     column.resize( zSize );
1513     column.front() = botNode;
1514     column.back()  = topNode;
1515   }
1516   return true;
1517 }
1518
1519 //================================================================================
1520 /*!
1521  * \brief Remove quadrangles from the top face and
1522  * create triangles there by projection from the bottom
1523  * \retval bool - a success or not
1524  */
1525 //================================================================================
1526
1527 bool StdMeshers_Prism_3D::projectBottomToTop()
1528 {
1529   SMESHDS_Mesh*  meshDS = myBlock.MeshDS();
1530   SMESH_subMesh * botSM = myBlock.SubMesh( ID_BOT_FACE );
1531   SMESH_subMesh * topSM = myBlock.SubMesh( ID_TOP_FACE );
1532
1533   SMESHDS_SubMesh * botSMDS = botSM->GetSubMeshDS();
1534   SMESHDS_SubMesh * topSMDS = topSM->GetSubMeshDS();
1535
1536   if ( topSMDS && topSMDS->NbElements() > 0 )
1537     topSM->ComputeStateEngine( SMESH_subMesh::CLEAN );
1538
1539   const TopoDS_Shape& botFace = myBlock.Shape( ID_BOT_FACE ); // oriented within the 3D SHAPE
1540   const TopoDS_Shape& topFace = myBlock.Shape( ID_TOP_FACE);
1541   int topFaceID = meshDS->ShapeToIndex( topFace );
1542
1543   // Fill myBotToColumnMap
1544
1545   int zSize = myBlock.VerticalSize();
1546   Prism_3D::TNode prevTNode;
1547   SMDS_NodeIteratorPtr nIt = botSMDS->GetNodes();
1548   while ( nIt->more() )
1549   {
1550     const SMDS_MeshNode* botNode = nIt->next();
1551     if ( botNode->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE )
1552       continue; // strange
1553     // compute bottom node params
1554     Prism_3D::TNode bN( botNode );
1555     gp_XYZ paramHint(-1,-1,-1);
1556     if ( prevTNode.IsNeighbor( bN ))
1557       paramHint = prevTNode.GetParams();
1558     if ( !myBlock.ComputeParameters( bN.GetCoords(), bN.ChangeParams(),
1559                                      ID_BOT_FACE, paramHint ))
1560       return toSM( error(TCom("Can't compute normalized parameters for node ")
1561                          << botNode->GetID() << " on the face #"<< botSM->GetId() ));
1562     prevTNode = bN;
1563     // compute top node coords
1564     gp_XYZ topXYZ; gp_XY topUV;
1565     if ( !myBlock.FacePoint( ID_TOP_FACE, bN.GetParams(), topXYZ ) ||
1566          !myBlock.FaceUV   ( ID_TOP_FACE, bN.GetParams(), topUV ))
1567       return toSM( error(TCom("Can't compute coordinates "
1568                               "by normalized parameters on the face #")<< topSM->GetId() ));
1569     SMDS_MeshNode * topNode = meshDS->AddNode( topXYZ.X(),topXYZ.Y(),topXYZ.Z() );
1570     meshDS->SetNodeOnFace( topNode, topFaceID, topUV.X(), topUV.Y() );
1571     // create node column
1572     TNode2ColumnMap::iterator bN_col = 
1573       myBotToColumnMap.insert( make_pair ( bN, TNodeColumn() )).first;
1574     TNodeColumn & column = bN_col->second;
1575     column.resize( zSize );
1576     column.front() = botNode;
1577     column.back()  = topNode;
1578   }
1579
1580   // Create top faces
1581
1582   const bool oldSetElemsOnShape = myHelper->SetElementsOnShape( false );
1583
1584   // care of orientation;
1585   // if the bottom faces is orienetd OK then top faces must be reversed
1586   bool reverseTop = true;
1587   if ( myHelper->NbAncestors( botFace, *myBlock.Mesh(), TopAbs_SOLID ) > 1 )
1588     reverseTop = ! SMESH_Algo::IsReversedSubMesh( TopoDS::Face( botFace ), meshDS );
1589   int iFrw, iRev, *iPtr = &( reverseTop ? iRev : iFrw );
1590
1591   // loop on bottom mesh faces
1592   SMDS_ElemIteratorPtr faceIt = botSMDS->GetElements();
1593   vector< const SMDS_MeshNode* > nodes;
1594   while ( faceIt->more() )
1595   {
1596     const SMDS_MeshElement* face = faceIt->next();
1597     if ( !face || face->GetType() != SMDSAbs_Face )
1598       continue;
1599
1600     // find top node in columns for each bottom node
1601     int nbNodes = face->NbCornerNodes();
1602     nodes.resize( nbNodes );
1603     for ( iFrw = 0, iRev = nbNodes-1; iFrw < nbNodes; ++iFrw, --iRev )
1604     {
1605       const SMDS_MeshNode* n = face->GetNode( *iPtr );
1606       if ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
1607         TNode2ColumnMap::iterator bot_column = myBotToColumnMap.find( n );
1608         if ( bot_column == myBotToColumnMap.end() )
1609           return toSM( error(TCom("No nodes found above node ") << n->GetID() ));
1610         nodes[ iFrw ] = bot_column->second.back();
1611       }
1612       else {
1613         const TNodeColumn* column = myBlock.GetNodeColumn( n );
1614         if ( !column )
1615           return toSM( error(TCom("No side nodes found above node ") << n->GetID() ));
1616         nodes[ iFrw ] = column->back();
1617       }
1618     }
1619     SMDS_MeshElement* newFace = 0;
1620     switch ( nbNodes ) {
1621
1622     case 3: {
1623       newFace = myHelper->AddFace(nodes[0], nodes[1], nodes[2]);
1624       break;
1625       }
1626     case 4: {
1627       newFace = myHelper->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] );
1628       break;
1629       }
1630     default:
1631       newFace = meshDS->AddPolygonalFace( nodes );
1632     }
1633     if ( newFace )
1634       meshDS->SetMeshElementOnShape( newFace, topFaceID );
1635   }
1636
1637   myHelper->SetElementsOnShape( oldSetElemsOnShape );  
1638
1639   return true;
1640 }
1641
1642 //=======================================================================
1643 //function : project2dMesh
1644 //purpose  : Project mesh faces from a source FACE of one prism (theSrcFace)
1645 //           to a source FACE of another prism (theTgtFace)
1646 //=======================================================================
1647
1648 bool StdMeshers_Prism_3D::project2dMesh(const TopoDS_Face& theSrcFace,
1649                                         const TopoDS_Face& theTgtFace)
1650 {
1651   TProjction2dAlgo* projector2D = TProjction2dAlgo::instance( this );
1652   projector2D->myHyp.SetSourceFace( theSrcFace );
1653   bool ok = projector2D->Compute( *myHelper->GetMesh(), theTgtFace );
1654
1655   SMESH_subMesh* tgtSM = myHelper->GetMesh()->GetSubMesh( theTgtFace );
1656   tgtSM->ComputeStateEngine       ( SMESH_subMesh::CHECK_COMPUTE_STATE );
1657   tgtSM->ComputeSubMeshStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
1658
1659   return ok;
1660 }
1661
1662 //================================================================================
1663 /*!
1664  * \brief Set projection coordinates of a node to a face and it's sub-shapes
1665  * \param faceID - the face given by in-block ID
1666  * \param params - node normalized parameters
1667  * \retval bool - is a success
1668  */
1669 //================================================================================
1670
1671 bool StdMeshers_Prism_3D::setFaceAndEdgesXYZ( const int faceID, const gp_XYZ& params, int z )
1672 {
1673   // find base and top edges of the face
1674   enum { BASE = 0, TOP, LEFT, RIGHT };
1675   vector< int > edgeVec; // 0-base, 1-top
1676   SMESH_Block::GetFaceEdgesIDs( faceID, edgeVec );
1677
1678   myBlock.EdgePoint( edgeVec[ BASE ], params, myShapeXYZ[ edgeVec[ BASE ]]);
1679   myBlock.EdgePoint( edgeVec[ TOP  ], params, myShapeXYZ[ edgeVec[ TOP ]]);
1680
1681   SHOWYXZ("\nparams ", params);
1682   SHOWYXZ("TOP is " <<edgeVec[ TOP ], myShapeXYZ[ edgeVec[ TOP]]);
1683   SHOWYXZ("BASE is "<<edgeVec[ BASE], myShapeXYZ[ edgeVec[ BASE]]);
1684
1685   if ( faceID == SMESH_Block::ID_Fx0z || faceID == SMESH_Block::ID_Fx1z )
1686   {
1687     myBlock.EdgePoint( edgeVec[ LEFT ], params, myShapeXYZ[ edgeVec[ LEFT ]]);
1688     myBlock.EdgePoint( edgeVec[ RIGHT ], params, myShapeXYZ[ edgeVec[ RIGHT ]]);
1689
1690     SHOWYXZ("VER "<<edgeVec[ LEFT], myShapeXYZ[ edgeVec[ LEFT]]);
1691     SHOWYXZ("VER "<<edgeVec[ RIGHT], myShapeXYZ[ edgeVec[ RIGHT]]);
1692   }
1693   myBlock.FacePoint( faceID, params, myShapeXYZ[ faceID ]);
1694   SHOWYXZ("FacePoint "<<faceID, myShapeXYZ[ faceID]);
1695
1696   return true;
1697 }
1698
1699 //=======================================================================
1700 //function : toSM
1701 //purpose  : If (!isOK), sets the error to a sub-mesh of a current SOLID
1702 //=======================================================================
1703
1704 bool StdMeshers_Prism_3D::toSM( bool isOK )
1705 {
1706   if ( mySetErrorToSM &&
1707        !isOK &&
1708        myHelper &&
1709        !myHelper->GetSubShape().IsNull() &&
1710        myHelper->GetSubShape().ShapeType() == TopAbs_SOLID)
1711   {
1712     SMESH_subMesh* sm = myHelper->GetMesh()->GetSubMesh( myHelper->GetSubShape() );
1713     sm->GetComputeError() = this->GetComputeError();
1714     // clear error in order not to return it twice
1715     _error = COMPERR_OK;
1716     _comment.clear();
1717   }
1718   return isOK;
1719 }
1720
1721 //=======================================================================
1722 //function : shapeID
1723 //purpose  : Return index of a shape
1724 //=======================================================================
1725
1726 int StdMeshers_Prism_3D::shapeID( const TopoDS_Shape& S )
1727 {
1728   if ( S.IsNull() ) return 0;
1729   if ( !myHelper  ) return -3;
1730   return myHelper->GetMeshDS()->ShapeToIndex( S );
1731 }
1732
1733 namespace Prism_3D
1734 {
1735   //================================================================================
1736   /*!
1737    * \brief Return true if this node and other one belong to one face
1738    */
1739   //================================================================================
1740
1741   bool Prism_3D::TNode::IsNeighbor( const Prism_3D::TNode& other ) const
1742   {
1743     if ( !other.myNode || !myNode ) return false;
1744
1745     SMDS_ElemIteratorPtr fIt = other.myNode->GetInverseElementIterator(SMDSAbs_Face);
1746     while ( fIt->more() )
1747       if ( fIt->next()->GetNodeIndex( myNode ) >= 0 )
1748         return true;
1749     return false;
1750   }
1751
1752   //================================================================================
1753   /*!
1754    * \brief Prism initialization
1755    */
1756   //================================================================================
1757
1758   void TPrismTopo::Clear()
1759   {
1760     myShape3D.Nullify();
1761     myTop.Nullify();
1762     myBottom.Nullify();
1763     myWallQuads.clear();
1764     myBottomEdges.clear();
1765     myNbEdgesInWires.clear();
1766     myWallQuads.clear();
1767   }
1768
1769 } // namespace Prism_3D
1770
1771 //================================================================================
1772 /*!
1773  * \brief Constructor. Initialization is needed
1774  */
1775 //================================================================================
1776
1777 StdMeshers_PrismAsBlock::StdMeshers_PrismAsBlock()
1778 {
1779   mySide = 0;
1780 }
1781
1782 StdMeshers_PrismAsBlock::~StdMeshers_PrismAsBlock()
1783 {
1784   Clear();
1785 }
1786 void StdMeshers_PrismAsBlock::Clear()
1787 {
1788   myHelper = 0;
1789   myShapeIDMap.Clear();
1790   myError.reset();
1791
1792   if ( mySide ) {
1793     delete mySide; mySide = 0;
1794   }
1795   myParam2ColumnMaps.clear();
1796   myShapeIndex2ColumnMap.clear();
1797 }
1798
1799 //=======================================================================
1800 //function : initPrism
1801 //purpose  : Analyse shape geometry and mesh.
1802 //           If there are triangles on one of faces, it becomes 'bottom'.
1803 //           thePrism.myBottom can be already set up.
1804 //=======================================================================
1805
1806 bool StdMeshers_Prism_3D::initPrism(Prism_3D::TPrismTopo& thePrism,
1807                                     const TopoDS_Shape&   shape3D)
1808 {
1809   myHelper->SetSubShape( shape3D );
1810
1811   SMESH_subMesh* mainSubMesh = myHelper->GetMesh()->GetSubMeshContaining( shape3D );
1812   if ( !mainSubMesh ) return toSM( error(COMPERR_BAD_INPUT_MESH,"Null submesh of shape3D"));
1813
1814   // detect not-quad FACE sub-meshes of the 3D SHAPE
1815   list< SMESH_subMesh* > notQuadGeomSubMesh;
1816   list< SMESH_subMesh* > notQuadElemSubMesh;
1817   int nbFaces = 0;
1818   //
1819   SMESH_subMesh* anyFaceSM = 0;
1820   SMESH_subMeshIteratorPtr smIt = mainSubMesh->getDependsOnIterator(false,true);
1821   while ( smIt->more() )
1822   {
1823     SMESH_subMesh* sm = smIt->next();
1824     const TopoDS_Shape& face = sm->GetSubShape();
1825     if      ( face.ShapeType() > TopAbs_FACE ) break;
1826     else if ( face.ShapeType() < TopAbs_FACE ) continue;
1827     nbFaces++;
1828     anyFaceSM = sm;
1829
1830     // is quadrangle FACE?
1831     list< TopoDS_Edge > orderedEdges;
1832     list< int >         nbEdgesInWires;
1833     int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( face ), orderedEdges,
1834                                                 nbEdgesInWires );
1835     if ( nbWires != 1 || nbEdgesInWires.front() != 4 )
1836       notQuadGeomSubMesh.push_back( sm );
1837
1838     // look for not quadrangle mesh elements
1839     if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
1840       if ( !myHelper->IsSameElemGeometry( smDS, SMDSGeom_QUADRANGLE ))
1841         notQuadElemSubMesh.push_back( sm );
1842   }
1843
1844   int nbNotQuadMeshed = notQuadElemSubMesh.size();
1845   int       nbNotQuad = notQuadGeomSubMesh.size();
1846   bool     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1847
1848   // detect bad cases
1849   if ( nbNotQuadMeshed > 2 )
1850   {
1851     return toSM( error(COMPERR_BAD_INPUT_MESH,
1852                        TCom("More than 2 faces with not quadrangle elements: ")
1853                        <<nbNotQuadMeshed));
1854   }
1855   if ( nbNotQuad > 2 || !thePrism.myBottom.IsNull() )
1856   {
1857     // Issue 0020843 - one of side FACEs is quasi-quadrilateral (not 4 EDGEs).
1858     // Remove from notQuadGeomSubMesh faces meshed with regular grid
1859     int nbQuasiQuads = removeQuasiQuads( notQuadGeomSubMesh, myHelper,
1860                                          TQuadrangleAlgo::instance(this,myHelper->GetMesh()) );
1861     nbNotQuad -= nbQuasiQuads;
1862     if ( nbNotQuad > 2 )
1863       return toSM( error(COMPERR_BAD_SHAPE,
1864                          TCom("More than 2 not quadrilateral faces: ") <<nbNotQuad));
1865     hasNotQuad = ( nbNotQuad || nbNotQuadMeshed );
1866   }
1867
1868   // Analyse mesh and topology of FACEs: choose the bottom sub-mesh.
1869   // If there are not quadrangle FACEs, they are top and bottom ones.
1870   // Not quadrangle FACEs must be only on top and bottom.
1871
1872   SMESH_subMesh * botSM = 0;
1873   SMESH_subMesh * topSM = 0;
1874
1875   if ( hasNotQuad ) // can chose a bottom FACE
1876   {
1877     if ( nbNotQuadMeshed > 0 ) botSM = notQuadElemSubMesh.front();
1878     else                       botSM = notQuadGeomSubMesh.front();
1879     if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.back();
1880     else if ( nbNotQuad  > 1 ) topSM = notQuadGeomSubMesh.back();
1881
1882     if ( topSM == botSM ) {
1883       if ( nbNotQuadMeshed > 1 ) topSM = notQuadElemSubMesh.front();
1884       else                       topSM = notQuadGeomSubMesh.front();
1885     }
1886
1887     // detect mesh triangles on wall FACEs
1888     if ( nbNotQuad == 2 && nbNotQuadMeshed > 0 ) {
1889       bool ok = false;
1890       if ( nbNotQuadMeshed == 1 )
1891         ok = ( find( notQuadGeomSubMesh.begin(),
1892                      notQuadGeomSubMesh.end(), botSM ) != notQuadGeomSubMesh.end() );
1893       else
1894         ok = ( notQuadGeomSubMesh == notQuadElemSubMesh );
1895       if ( !ok )
1896         return toSM( error(COMPERR_BAD_INPUT_MESH,
1897                            "Side face meshed with not quadrangle elements"));
1898     }
1899   }
1900
1901   thePrism.myNotQuadOnTop = ( nbNotQuadMeshed > 1 );
1902
1903   // use thePrism.myBottom
1904   if ( !thePrism.myBottom.IsNull() )
1905   {
1906     if ( botSM ) {
1907       if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom )) {
1908         std::swap( botSM, topSM );
1909         if ( ! botSM->GetSubShape().IsSame( thePrism.myBottom ))
1910           return toSM( error( COMPERR_BAD_INPUT_MESH,
1911                               "Incompatible non-structured sub-meshes"));
1912       }
1913     }
1914     else {
1915       botSM = myHelper->GetMesh()->GetSubMesh( thePrism.myBottom );
1916     }
1917   }
1918   else if ( !botSM ) // find a proper bottom
1919   {
1920     // composite walls or not prism shape
1921     for ( TopExp_Explorer f( shape3D, TopAbs_FACE ); f.More(); f.Next() )
1922     {
1923       int minNbFaces = 2 + myHelper->Count( f.Current(), TopAbs_EDGE, false);
1924       if ( nbFaces >= minNbFaces)
1925       {
1926         thePrism.Clear();
1927         thePrism.myBottom = TopoDS::Face( f.Current() );
1928         if ( initPrism( thePrism, shape3D ))
1929           return true;
1930       }
1931       return toSM( error( COMPERR_BAD_SHAPE ));
1932     }
1933   }
1934
1935   // find vertex 000 - the one with smallest coordinates (for easy DEBUG :-)
1936   TopoDS_Vertex V000;
1937   double minVal = DBL_MAX, minX, val;
1938   for ( TopExp_Explorer exp( botSM->GetSubShape(), TopAbs_VERTEX );
1939         exp.More(); exp.Next() )
1940   {
1941     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
1942     gp_Pnt P = BRep_Tool::Pnt( v );
1943     val = P.X() + P.Y() + P.Z();
1944     if ( val < minVal || ( val == minVal && P.X() < minX )) {
1945       V000 = v;
1946       minVal = val;
1947       minX = P.X();
1948     }
1949   }
1950
1951   thePrism.myShape3D = shape3D;
1952   if ( thePrism.myBottom.IsNull() )
1953     thePrism.myBottom  = TopoDS::Face( botSM->GetSubShape() );
1954   thePrism.myBottom.Orientation( myHelper->GetSubShapeOri( shape3D,
1955                                                            thePrism.myBottom ));
1956   // Get ordered bottom edges
1957   TopoDS_Face reverseBottom = // to have order of top EDGEs as in the top FACE
1958     TopoDS::Face( thePrism.myBottom.Reversed() );
1959   SMESH_Block::GetOrderedEdges( reverseBottom,
1960                                 thePrism.myBottomEdges,
1961                                 thePrism.myNbEdgesInWires, V000 );
1962
1963   // Get Wall faces corresponding to the ordered bottom edges and the top FACE
1964   if ( !getWallFaces( thePrism, nbFaces ))
1965     return false; //toSM( error(COMPERR_BAD_SHAPE, "Can't find side faces"));
1966
1967   if ( topSM )
1968   {
1969     if ( !thePrism.myTop.IsSame( topSM->GetSubShape() ))
1970       return toSM( error
1971                    (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
1972                     "Non-quadrilateral faces are not opposite"));
1973
1974     // check that the found top and bottom FACEs are opposite
1975     list< TopoDS_Edge >::iterator edge = thePrism.myBottomEdges.begin();
1976     for ( ; edge != thePrism.myBottomEdges.end(); ++edge )
1977       if ( myHelper->IsSubShape( *edge, thePrism.myTop ))
1978         return toSM( error
1979                      (notQuadGeomSubMesh.empty() ? COMPERR_BAD_INPUT_MESH : COMPERR_BAD_SHAPE,
1980                       "Non-quadrilateral faces are not opposite"));
1981   }
1982
1983   return true;
1984 }
1985
1986 //================================================================================
1987 /*!
1988  * \brief Initialization.
1989  * \param helper - helper loaded with mesh and 3D shape
1990  * \param thePrism - a prosm data
1991  * \retval bool - false if a mesh or a shape are KO
1992  */
1993 //================================================================================
1994
1995 bool StdMeshers_PrismAsBlock::Init(SMESH_MesherHelper*         helper,
1996                                    const Prism_3D::TPrismTopo& thePrism)
1997 {
1998   if ( mySide ) {
1999     delete mySide; mySide = 0;
2000   }
2001   vector< TSideFace* >         sideFaces( NB_WALL_FACES, 0 );
2002   vector< pair< double, double> > params( NB_WALL_FACES );
2003   mySide = new TSideFace( sideFaces, params );
2004
2005   myHelper = helper;
2006   SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2007
2008   SMESH_Block::init();
2009   myShapeIDMap.Clear();
2010   myShapeIndex2ColumnMap.clear();
2011   
2012   int wallFaceIds[ NB_WALL_FACES ] = { // to walk around a block
2013     SMESH_Block::ID_Fx0z, SMESH_Block::ID_F1yz,
2014     SMESH_Block::ID_Fx1z, SMESH_Block::ID_F0yz
2015   };
2016
2017   myError = SMESH_ComputeError::New();
2018
2019   myNotQuadOnTop = thePrism.myNotQuadOnTop;
2020
2021   // Find columns of wall nodes and calculate edges' lengths
2022   // --------------------------------------------------------
2023
2024   myParam2ColumnMaps.clear();
2025   myParam2ColumnMaps.resize( thePrism.myBottomEdges.size() ); // total nb edges
2026
2027   size_t iE, nbEdges = thePrism.myNbEdgesInWires.front(); // nb outer edges
2028   vector< double >    edgeLength( nbEdges );
2029   multimap< double, int > len2edgeMap;
2030
2031   list< TopoDS_Edge >::const_iterator edgeIt = thePrism.myBottomEdges.begin();
2032   for ( iE = 0; iE < nbEdges; ++iE, ++edgeIt )
2033   {
2034     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2035
2036     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2037     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2038     {
2039       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge( 0 );
2040       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2041         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2042                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2043     }
2044     SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2045     SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2046     SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2047
2048     edgeLength[ iE ] = SMESH_Algo::EdgeLength( *edgeIt );
2049
2050     if ( nbEdges < NB_WALL_FACES ) // fill map used to split faces
2051     {
2052       SMESHDS_SubMesh* smDS = meshDS->MeshElements( *edgeIt);
2053       if ( !smDS )
2054         return error(COMPERR_BAD_INPUT_MESH, TCom("Null submesh on the edge #")
2055                      << MeshDS()->ShapeToIndex( *edgeIt ));
2056       len2edgeMap.insert( make_pair( edgeLength[ iE ], iE ));
2057     }
2058   }
2059   // Load columns of internal edges (forming holes)
2060   // and fill map ShapeIndex to TParam2ColumnMap for them
2061   for ( ; edgeIt != thePrism.myBottomEdges.end() ; ++edgeIt, ++iE )
2062   {
2063     TParam2ColumnMap & faceColumns = myParam2ColumnMaps[ iE ];
2064
2065     Prism_3D::TQuadList::const_iterator quad = thePrism.myWallQuads[ iE ].begin();
2066     for ( ; quad != thePrism.myWallQuads[ iE ].end(); ++quad )
2067     {
2068       const TopoDS_Edge& quadBot = (*quad)->side[ QUAD_BOTTOM_SIDE ]->Edge( 0 );
2069       if ( !myHelper->LoadNodeColumns( faceColumns, (*quad)->face, quadBot, meshDS ))
2070         return error(COMPERR_BAD_INPUT_MESH, TCom("Can't find regular quadrangle mesh ")
2071                      << "on a side face #" << MeshDS()->ShapeToIndex( (*quad)->face ));
2072     }
2073     // edge columns
2074     int id = MeshDS()->ShapeToIndex( *edgeIt );
2075     bool isForward = true; // meaningless for intenal wires
2076     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2077     // columns for vertices
2078     // 1
2079     const SMDS_MeshNode* n0 = faceColumns.begin()->second.front();
2080     id = n0->getshapeId();
2081     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2082     // 2
2083     const SMDS_MeshNode* n1 = faceColumns.rbegin()->second.front();
2084     id = n1->getshapeId();
2085     myShapeIndex2ColumnMap[ id ] = make_pair( & faceColumns, isForward );
2086
2087     // SHOWYXZ("\np1 F " <<iE, gpXYZ(faceColumns.begin()->second.front() ));
2088     // SHOWYXZ("p2 F "   <<iE, gpXYZ(faceColumns.rbegin()->second.front() ));
2089     // SHOWYXZ("V First "<<iE, BRep_Tool::Pnt( TopExp::FirstVertex(*edgeIt,true )));
2090   }
2091
2092   // Create 4 wall faces of a block
2093   // -------------------------------
2094
2095   if ( nbEdges <= NB_WALL_FACES ) // ************* Split faces if necessary
2096   {
2097     map< int, int > iE2nbSplit;
2098     if ( nbEdges != NB_WALL_FACES ) // define how to split
2099     {
2100       if ( len2edgeMap.size() != nbEdges )
2101         RETURN_BAD_RESULT("Uniqueness of edge lengths not assured");
2102       map< double, int >::reverse_iterator maxLen_i = len2edgeMap.rbegin();
2103       map< double, int >::reverse_iterator midLen_i = ++len2edgeMap.rbegin();
2104       double maxLen = maxLen_i->first;
2105       double midLen = ( len2edgeMap.size() == 1 ) ? 0 : midLen_i->first;
2106       switch ( nbEdges ) {
2107       case 1: // 0-th edge is split into 4 parts
2108         iE2nbSplit.insert( make_pair( 0, 4 )); break;
2109       case 2: // either the longest edge is split into 3 parts, or both edges into halves
2110         if ( maxLen / 3 > midLen / 2 ) {
2111           iE2nbSplit.insert( make_pair( maxLen_i->second, 3 ));
2112         }
2113         else {
2114           iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
2115           iE2nbSplit.insert( make_pair( midLen_i->second, 2 ));
2116         }
2117         break;
2118       case 3:
2119         // split longest into halves
2120         iE2nbSplit.insert( make_pair( maxLen_i->second, 2 ));
2121       }
2122     }
2123     // Create TSideFace's
2124     int iSide = 0;
2125     list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2126     for ( iE = 0; iE < nbEdges; ++iE, ++botE )
2127     {
2128       TFaceQuadStructPtr quad = thePrism.myWallQuads[ iE ].front();
2129       // split?
2130       map< int, int >::iterator i_nb = iE2nbSplit.find( iE );
2131       if ( i_nb != iE2nbSplit.end() ) {
2132         // split!
2133         int nbSplit = i_nb->second;
2134         vector< double > params;
2135         splitParams( nbSplit, &myParam2ColumnMaps[ iE ], params );
2136         const bool isForward =
2137           StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
2138                                                   myParam2ColumnMaps[iE],
2139                                                   *botE, SMESH_Block::ID_Fx0z );
2140         for ( int i = 0; i < nbSplit; ++i ) {
2141           double f = ( isForward ? params[ i ]   : params[ nbSplit - i-1 ]);
2142           double l = ( isForward ? params[ i+1 ] : params[ nbSplit - i ]);
2143           TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
2144                                            thePrism.myWallQuads[ iE ], *botE,
2145                                            &myParam2ColumnMaps[ iE ], f, l );
2146           mySide->SetComponent( iSide++, comp );
2147         }
2148       }
2149       else {
2150         TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
2151                                          thePrism.myWallQuads[ iE ], *botE,
2152                                          &myParam2ColumnMaps[ iE ]);
2153         mySide->SetComponent( iSide++, comp );
2154       }
2155     }
2156   }
2157   else { // **************************** Unite faces
2158
2159     // unite first faces
2160     int nbExraFaces = nbEdges - 3;
2161     int iSide = 0, iE;
2162     double u0 = 0, sumLen = 0;
2163     for ( iE = 0; iE < nbExraFaces; ++iE )
2164       sumLen += edgeLength[ iE ];
2165
2166     vector< TSideFace* >        components( nbExraFaces );
2167     vector< pair< double, double> > params( nbExraFaces );
2168     list< TopoDS_Edge >::const_iterator botE = thePrism.myBottomEdges.begin();
2169     for ( iE = 0; iE < nbExraFaces; ++iE, ++botE )
2170     {
2171       components[ iE ] = new TSideFace( myHelper, wallFaceIds[ iSide ],
2172                                         thePrism.myWallQuads[ iE ], *botE,
2173                                         &myParam2ColumnMaps[ iE ]);
2174       double u1 = u0 + edgeLength[ iE ] / sumLen;
2175       params[ iE ] = make_pair( u0 , u1 );
2176       u0 = u1;
2177     }
2178     mySide->SetComponent( iSide++, new TSideFace( components, params ));
2179
2180     // fill the rest faces
2181     for ( ; iE < nbEdges; ++iE, ++botE )
2182     {
2183       TSideFace* comp = new TSideFace( myHelper, wallFaceIds[ iSide ],
2184                                        thePrism.myWallQuads[ iE ], *botE,
2185                                        &myParam2ColumnMaps[ iE ]);
2186       mySide->SetComponent( iSide++, comp );
2187     }
2188   }
2189
2190
2191   // Fill geometry fields of SMESH_Block
2192   // ------------------------------------
2193
2194   vector< int > botEdgeIdVec;
2195   SMESH_Block::GetFaceEdgesIDs( ID_BOT_FACE, botEdgeIdVec );
2196
2197   bool isForward[NB_WALL_FACES] = { true, true, true, true };
2198   Adaptor2d_Curve2d* botPcurves[NB_WALL_FACES];
2199   Adaptor2d_Curve2d* topPcurves[NB_WALL_FACES];
2200
2201   for ( int iF = 0; iF < NB_WALL_FACES; ++iF )
2202   {
2203     TSideFace * sideFace = mySide->GetComponent( iF );
2204     if ( !sideFace )
2205       RETURN_BAD_RESULT("NULL TSideFace");
2206     int fID = sideFace->FaceID(); // in-block ID
2207
2208     // fill myShapeIDMap
2209     if ( sideFace->InsertSubShapes( myShapeIDMap ) != 8 &&
2210          !sideFace->IsComplex())
2211       MESSAGE( ": Warning : InsertSubShapes() < 8 on side " << iF );
2212
2213     // side faces geometry
2214     Adaptor2d_Curve2d* pcurves[NB_WALL_FACES];
2215     if ( !sideFace->GetPCurves( pcurves ))
2216       RETURN_BAD_RESULT("TSideFace::GetPCurves() failed");
2217
2218     SMESH_Block::TFace& tFace = myFace[ fID - ID_FirstF ];
2219     tFace.Set( fID, sideFace->Surface(), pcurves, isForward );
2220
2221     SHOWYXZ( endl<<"F "<< iF << " id " << fID << " FRW " << sideFace->IsForward(), sideFace->Value(0,0));
2222     // edges 3D geometry
2223     vector< int > edgeIdVec;
2224     SMESH_Block::GetFaceEdgesIDs( fID, edgeIdVec );
2225     for ( int isMax = 0; isMax < 2; ++isMax ) {
2226       {
2227         int eID = edgeIdVec[ isMax ];
2228         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE ];
2229         tEdge.Set( eID, sideFace->HorizCurve(isMax), true);
2230         SHOWYXZ(eID<<" HOR"<<isMax<<"(0)", sideFace->HorizCurve(isMax)->Value(0));
2231         SHOWYXZ(eID<<" HOR"<<isMax<<"(1)", sideFace->HorizCurve(isMax)->Value(1));
2232       }
2233       {
2234         int eID = edgeIdVec[ isMax+2 ];
2235         SMESH_Block::TEdge& tEdge = myEdge[ eID - ID_FirstE  ];
2236         tEdge.Set( eID, sideFace->VertiCurve(isMax), true);
2237         SHOWYXZ(eID<<" VER"<<isMax<<"(0)", sideFace->VertiCurve(isMax)->Value(0));
2238         SHOWYXZ(eID<<" VER"<<isMax<<"(1)", sideFace->VertiCurve(isMax)->Value(1));
2239
2240         // corner points
2241         vector< int > vertexIdVec;
2242         SMESH_Block::GetEdgeVertexIDs( eID, vertexIdVec );
2243         myPnt[ vertexIdVec[0] - ID_FirstV ] = tEdge.GetCurve()->Value(0).XYZ();
2244         myPnt[ vertexIdVec[1] - ID_FirstV ] = tEdge.GetCurve()->Value(1).XYZ();
2245       }
2246     }
2247     // pcurves on horizontal faces
2248     for ( iE = 0; iE < NB_WALL_FACES; ++iE ) {
2249       if ( edgeIdVec[ BOTTOM_EDGE ] == botEdgeIdVec[ iE ] ) {
2250         botPcurves[ iE ] = sideFace->HorizPCurve( false, thePrism.myBottom );
2251         topPcurves[ iE ] = sideFace->HorizPCurve( true,  thePrism.myTop );
2252         break;
2253       }
2254     }
2255     //sideFace->dumpNodes( 4 ); // debug
2256   }
2257   // horizontal faces geometry
2258   {
2259     SMESH_Block::TFace& tFace = myFace[ ID_BOT_FACE - ID_FirstF ];
2260     tFace.Set( ID_BOT_FACE, new BRepAdaptor_Surface( thePrism.myBottom ), botPcurves, isForward );
2261     SMESH_Block::Insert( thePrism.myBottom, ID_BOT_FACE, myShapeIDMap );
2262   }
2263   {
2264     SMESH_Block::TFace& tFace = myFace[ ID_TOP_FACE - ID_FirstF ];
2265     tFace.Set( ID_TOP_FACE, new BRepAdaptor_Surface( thePrism.myTop ), topPcurves, isForward );
2266     SMESH_Block::Insert( thePrism.myTop, ID_TOP_FACE, myShapeIDMap );
2267   }
2268
2269   // Fill map ShapeIndex to TParam2ColumnMap
2270   // ----------------------------------------
2271
2272   list< TSideFace* > fList;
2273   list< TSideFace* >::iterator fListIt;
2274   fList.push_back( mySide );
2275   for ( fListIt = fList.begin(); fListIt != fList.end(); ++fListIt)
2276   {
2277     int nb = (*fListIt)->NbComponents();
2278     for ( int i = 0; i < nb; ++i ) {
2279       if ( TSideFace* comp = (*fListIt)->GetComponent( i ))
2280         fList.push_back( comp );
2281     }
2282     if ( TParam2ColumnMap* cols = (*fListIt)->GetColumns()) {
2283       // columns for a base edge
2284       int id = MeshDS()->ShapeToIndex( (*fListIt)->BaseEdge() );
2285       bool isForward = (*fListIt)->IsForward();
2286       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
2287
2288       // columns for vertices
2289       const SMDS_MeshNode* n0 = cols->begin()->second.front();
2290       id = n0->getshapeId();
2291       myShapeIndex2ColumnMap[ id ] = make_pair( cols, isForward );
2292
2293       const SMDS_MeshNode* n1 = cols->rbegin()->second.front();
2294       id = n1->getshapeId();
2295       myShapeIndex2ColumnMap[ id ] = make_pair( cols, !isForward );
2296     }
2297   }
2298
2299 //   gp_XYZ testPar(0.25, 0.25, 0), testCoord;
2300 //   if ( !FacePoint( ID_BOT_FACE, testPar, testCoord ))
2301 //     RETURN_BAD_RESULT("TEST FacePoint() FAILED");
2302 //   SHOWYXZ("IN TEST PARAM" , testPar);
2303 //   SHOWYXZ("OUT TEST CORD" , testCoord);
2304 //   if ( !ComputeParameters( testCoord, testPar , ID_BOT_FACE))
2305 //     RETURN_BAD_RESULT("TEST ComputeParameters() FAILED");
2306 //   SHOWYXZ("OUT TEST PARAM" , testPar);
2307
2308   return true;
2309 }
2310
2311 //================================================================================
2312 /*!
2313  * \brief Return pointer to column of nodes
2314  * \param node - bottom node from which the returned column goes up
2315  * \retval const TNodeColumn* - the found column
2316  */
2317 //================================================================================
2318
2319 const TNodeColumn* StdMeshers_PrismAsBlock::GetNodeColumn(const SMDS_MeshNode* node) const
2320 {
2321   int sID = node->getshapeId();
2322
2323   map<int, pair< TParam2ColumnMap*, bool > >::const_iterator col_frw =
2324     myShapeIndex2ColumnMap.find( sID );
2325   if ( col_frw != myShapeIndex2ColumnMap.end() ) {
2326     const TParam2ColumnMap* cols = col_frw->second.first;
2327     TParam2ColumnIt u_col = cols->begin();
2328     for ( ; u_col != cols->end(); ++u_col )
2329       if ( u_col->second[ 0 ] == node )
2330         return & u_col->second;
2331   }
2332   return 0;
2333 }
2334
2335 //=======================================================================
2336 //function : GetLayersTransformation
2337 //purpose  : Return transformations to get coordinates of nodes of each layer
2338 //           by nodes of the bottom. Layer is a set of nodes at a certain step
2339 //           from bottom to top.
2340 //=======================================================================
2341
2342 bool StdMeshers_PrismAsBlock::GetLayersTransformation(vector<gp_Trsf> & trsf) const
2343 {
2344   const int zSize = VerticalSize();
2345   if ( zSize < 3 ) return true;
2346   trsf.resize( zSize - 2 );
2347
2348   // Select some node columns by which we will define coordinate system of layers
2349
2350   vector< const TNodeColumn* > columns;
2351   {
2352     const TopoDS_Shape& baseFace = Shape(ID_BOT_FACE);
2353     list< TopoDS_Edge > orderedEdges;
2354     list< int >         nbEdgesInWires;
2355     GetOrderedEdges( TopoDS::Face( baseFace ), orderedEdges, nbEdgesInWires );
2356     bool isReverse;
2357     list< TopoDS_Edge >::iterator edgeIt = orderedEdges.begin();
2358     for ( int iE = 0; iE < nbEdgesInWires.front(); ++iE, ++edgeIt )
2359     {
2360       if ( BRep_Tool::Degenerated( *edgeIt )) continue;
2361       const TParam2ColumnMap* u2colMap =
2362         GetParam2ColumnMap( MeshDS()->ShapeToIndex( *edgeIt ), isReverse );
2363       if ( !u2colMap ) return false;
2364       double f = u2colMap->begin()->first, l = u2colMap->rbegin()->first;
2365       //isReverse = ( edgeIt->Orientation() == TopAbs_REVERSED );
2366       //if ( isReverse ) swap ( f, l ); -- u2colMap takes orientation into account
2367       const int nbCol = 5;
2368       for ( int i = 0; i < nbCol; ++i )
2369       {
2370         double u = f + i/double(nbCol) * ( l - f );
2371         const TNodeColumn* col = & getColumn( u2colMap, u )->second;
2372         if ( columns.empty() || col != columns.back() )
2373           columns.push_back( col );
2374       }
2375     }
2376   }
2377
2378   // Find tolerance to check transformations
2379
2380   double tol2;
2381   {
2382     Bnd_B3d bndBox;
2383     for ( int i = 0; i < columns.size(); ++i )
2384       bndBox.Add( gpXYZ( columns[i]->front() ));
2385     tol2 = bndBox.SquareExtent() * 1e-5;
2386   }
2387
2388   // Compute transformations
2389
2390   int xCol = -1;
2391   gp_Trsf fromCsZ, toCs0;
2392   gp_Ax3 cs0 = getLayerCoordSys(0, columns, xCol );
2393   //double dist0 = cs0.Location().Distance( gpXYZ( (*columns[0])[0]));
2394   toCs0.SetTransformation( cs0 );
2395   for ( int z = 1; z < zSize-1; ++z )
2396   {
2397     gp_Ax3 csZ = getLayerCoordSys(z, columns, xCol );
2398     //double distZ = csZ.Location().Distance( gpXYZ( (*columns[0])[z]));
2399     fromCsZ.SetTransformation( csZ );
2400     fromCsZ.Invert();
2401     gp_Trsf& t = trsf[ z-1 ];
2402     t = fromCsZ * toCs0;
2403     //t.SetScaleFactor( distZ/dist0 ); - it does not work properly, wrong base point
2404
2405     // check a transformation
2406     for ( int i = 0; i < columns.size(); ++i )
2407     {
2408       gp_Pnt p0 = gpXYZ( (*columns[i])[0] );
2409       gp_Pnt pz = gpXYZ( (*columns[i])[z] );
2410       t.Transforms( p0.ChangeCoord() );
2411       if ( p0.SquareDistance( pz ) > tol2 )
2412         return false;
2413     }
2414   }
2415   return true;
2416 }
2417
2418 //================================================================================
2419 /*!
2420  * \brief Check curve orientation of a bootom edge
2421   * \param meshDS - mesh DS
2422   * \param columnsMap - node columns map of side face
2423   * \param bottomEdge - the bootom edge
2424   * \param sideFaceID - side face in-block ID
2425   * \retval bool - true if orientation coinside with in-block forward orientation
2426  */
2427 //================================================================================
2428
2429 bool StdMeshers_PrismAsBlock::IsForwardEdge(SMESHDS_Mesh*           meshDS,
2430                                             const TParam2ColumnMap& columnsMap,
2431                                             const TopoDS_Edge &     bottomEdge,
2432                                             const int               sideFaceID)
2433 {
2434   bool isForward = false;
2435   if ( SMESH_MesherHelper::IsClosedEdge( bottomEdge ))
2436   {
2437     isForward = ( bottomEdge.Orientation() == TopAbs_FORWARD );
2438   }
2439   else
2440   {
2441     const TNodeColumn&     firstCol = columnsMap.begin()->second;
2442     const SMDS_MeshNode* bottomNode = firstCol[0];
2443     TopoDS_Shape firstVertex = SMESH_MesherHelper::GetSubShapeByNode( bottomNode, meshDS );
2444     isForward = ( firstVertex.IsSame( TopExp::FirstVertex( bottomEdge, true )));
2445   }
2446   // on 2 of 4 sides first vertex is end
2447   if ( sideFaceID == ID_Fx1z || sideFaceID == ID_F0yz )
2448     isForward = !isForward;
2449   return isForward;
2450 }
2451
2452 //================================================================================
2453 /*!
2454  * \brief Constructor
2455   * \param faceID - in-block ID
2456   * \param face - geom FACE
2457   * \param baseEdge - EDGE proreply oriented in the bottom EDGE !!!
2458   * \param columnsMap - map of node columns
2459   * \param first - first normalized param
2460   * \param last - last normalized param
2461  */
2462 //================================================================================
2463
2464 StdMeshers_PrismAsBlock::TSideFace::TSideFace(SMESH_MesherHelper*        helper,
2465                                               const int                  faceID,
2466                                               const Prism_3D::TQuadList& quadList,
2467                                               const TopoDS_Edge&         baseEdge,
2468                                               TParam2ColumnMap*          columnsMap,
2469                                               const double               first,
2470                                               const double               last):
2471   myID( faceID ),
2472   myParamToColumnMap( columnsMap ),
2473   myHelper( helper )
2474 {
2475   myParams.resize( 1 );
2476   myParams[ 0 ] = make_pair( first, last );
2477   mySurface     = PSurface( new BRepAdaptor_Surface( quadList.front()->face ));
2478   myBaseEdge    = baseEdge;
2479   myIsForward   = StdMeshers_PrismAsBlock::IsForwardEdge( myHelper->GetMeshDS(),
2480                                                           *myParamToColumnMap,
2481                                                           myBaseEdge, myID );
2482   if ( quadList.size() > 1 ) // side is vertically composite
2483   {
2484     // fill myShapeID2Surf map to enable finding a right surface by any sub-shape ID
2485
2486     SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2487
2488     TopTools_IndexedDataMapOfShapeListOfShape subToFaces;
2489     Prism_3D::TQuadList::const_iterator quad = quadList.begin();
2490     for ( ; quad != quadList.end(); ++quad )
2491     {
2492       const TopoDS_Face& face = (*quad)->face;
2493       TopExp::MapShapesAndAncestors( face, TopAbs_VERTEX, TopAbs_FACE, subToFaces );
2494       TopExp::MapShapesAndAncestors( face, TopAbs_EDGE,   TopAbs_FACE, subToFaces );
2495       myShapeID2Surf.insert( make_pair( meshDS->ShapeToIndex( face ),
2496                                         PSurface( new BRepAdaptor_Surface( face ))));
2497     }
2498     for ( int i = 1; i <= subToFaces.Extent(); ++i )
2499     {
2500       const TopoDS_Shape&     sub = subToFaces.FindKey( i );
2501       TopTools_ListOfShape& faces = subToFaces( i );
2502       int subID  = meshDS->ShapeToIndex( sub );
2503       int faceID = meshDS->ShapeToIndex( faces.First() );
2504       myShapeID2Surf.insert ( make_pair( subID, myShapeID2Surf[ faceID ]));
2505     }
2506   }
2507 }
2508
2509 //================================================================================
2510 /*!
2511  * \brief Constructor of complex side face
2512  */
2513 //================================================================================
2514
2515 StdMeshers_PrismAsBlock::TSideFace::
2516 TSideFace(const vector< TSideFace* >&             components,
2517           const vector< pair< double, double> > & params)
2518   :myID( components[0] ? components[0]->myID : 0 ),
2519    myParamToColumnMap( 0 ),
2520    myParams( params ),
2521    myIsForward( true ),
2522    myComponents( components ),
2523    myHelper( components[0] ? components[0]->myHelper : 0 )
2524 {}
2525 //================================================================================
2526 /*!
2527  * \brief Copy constructor
2528   * \param other - other side
2529  */
2530 //================================================================================
2531
2532 StdMeshers_PrismAsBlock::TSideFace::TSideFace( const TSideFace& other )
2533 {
2534   myID               = other.myID;
2535   mySurface          = other.mySurface;
2536   myBaseEdge         = other.myBaseEdge;
2537   myParams           = other.myParams;
2538   myIsForward        = other.myIsForward;
2539   myHelper           = other.myHelper;
2540   myParamToColumnMap = other.myParamToColumnMap;
2541
2542   myComponents.resize( other.myComponents.size());
2543   for (int i = 0 ; i < myComponents.size(); ++i )
2544     myComponents[ i ] = new TSideFace( *other.myComponents[ i ]);
2545 }
2546
2547 //================================================================================
2548 /*!
2549  * \brief Deletes myComponents
2550  */
2551 //================================================================================
2552
2553 StdMeshers_PrismAsBlock::TSideFace::~TSideFace()
2554 {
2555   for (int i = 0 ; i < myComponents.size(); ++i )
2556     if ( myComponents[ i ] )
2557       delete myComponents[ i ];
2558 }
2559
2560 //================================================================================
2561 /*!
2562  * \brief Return geometry of the vertical curve
2563   * \param isMax - true means curve located closer to (1,1,1) block point
2564   * \retval Adaptor3d_Curve* - curve adaptor
2565  */
2566 //================================================================================
2567
2568 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::VertiCurve(const bool isMax) const
2569 {
2570   if ( !myComponents.empty() ) {
2571     if ( isMax )
2572       return myComponents.back()->VertiCurve(isMax);
2573     else
2574       return myComponents.front()->VertiCurve(isMax);
2575   }
2576   double f = myParams[0].first, l = myParams[0].second;
2577   if ( !myIsForward ) std::swap( f, l );
2578   return new TVerticalEdgeAdaptor( myParamToColumnMap, isMax ? l : f );
2579 }
2580
2581 //================================================================================
2582 /*!
2583  * \brief Return geometry of the top or bottom curve
2584   * \param isTop - 
2585   * \retval Adaptor3d_Curve* - 
2586  */
2587 //================================================================================
2588
2589 Adaptor3d_Curve* StdMeshers_PrismAsBlock::TSideFace::HorizCurve(const bool isTop) const
2590 {
2591   return new THorizontalEdgeAdaptor( this, isTop );
2592 }
2593
2594 //================================================================================
2595 /*!
2596  * \brief Return pcurves
2597   * \param pcurv - array of 4 pcurves
2598   * \retval bool - is a success
2599  */
2600 //================================================================================
2601
2602 bool StdMeshers_PrismAsBlock::TSideFace::GetPCurves(Adaptor2d_Curve2d* pcurv[4]) const
2603 {
2604   int iEdge[ 4 ] = { BOTTOM_EDGE, TOP_EDGE, V0_EDGE, V1_EDGE };
2605
2606   for ( int i = 0 ; i < 4 ; ++i ) {
2607     Handle(Geom2d_Line) line;
2608     switch ( iEdge[ i ] ) {
2609     case TOP_EDGE:
2610       line = new Geom2d_Line( gp_Pnt2d( 0, 1 ), gp::DX2d() ); break;
2611     case BOTTOM_EDGE:
2612       line = new Geom2d_Line( gp::Origin2d(), gp::DX2d() ); break;
2613     case V0_EDGE:
2614       line = new Geom2d_Line( gp::Origin2d(), gp::DY2d() ); break;
2615     case V1_EDGE:
2616       line = new Geom2d_Line( gp_Pnt2d( 1, 0 ), gp::DY2d() ); break;
2617     }
2618     pcurv[ i ] = new Geom2dAdaptor_Curve( line, 0, 1 );
2619   }
2620   return true;
2621 }
2622
2623 //================================================================================
2624 /*!
2625  * \brief Returns geometry of pcurve on a horizontal face
2626   * \param isTop - is top or bottom face
2627   * \param horFace - a horizontal face
2628   * \retval Adaptor2d_Curve2d* - curve adaptor
2629  */
2630 //================================================================================
2631
2632 Adaptor2d_Curve2d*
2633 StdMeshers_PrismAsBlock::TSideFace::HorizPCurve(const bool         isTop,
2634                                                 const TopoDS_Face& horFace) const
2635 {
2636   return new TPCurveOnHorFaceAdaptor( this, isTop, horFace );
2637 }
2638
2639 //================================================================================
2640 /*!
2641  * \brief Return a component corresponding to parameter
2642   * \param U - parameter along a horizontal size
2643   * \param localU - parameter along a horizontal size of a component
2644   * \retval TSideFace* - found component
2645  */
2646 //================================================================================
2647
2648 StdMeshers_PrismAsBlock::TSideFace*
2649 StdMeshers_PrismAsBlock::TSideFace::GetComponent(const double U,double & localU) const
2650 {
2651   localU = U;
2652   if ( myComponents.empty() )
2653     return const_cast<TSideFace*>( this );
2654
2655   int i;
2656   for ( i = 0; i < myComponents.size(); ++i )
2657     if ( U < myParams[ i ].second )
2658       break;
2659   if ( i >= myComponents.size() )
2660     i = myComponents.size() - 1;
2661
2662   double f = myParams[ i ].first, l = myParams[ i ].second;
2663   localU = ( U - f ) / ( l - f );
2664   return myComponents[ i ];
2665 }
2666
2667 //================================================================================
2668 /*!
2669  * \brief Find node columns for a parameter
2670   * \param U - parameter along a horizontal edge
2671   * \param col1 - the 1st found column
2672   * \param col2 - the 2nd found column
2673   * \retval r - normalized position of U between the found columns
2674  */
2675 //================================================================================
2676
2677 double StdMeshers_PrismAsBlock::TSideFace::GetColumns(const double      U,
2678                                                       TParam2ColumnIt & col1,
2679                                                       TParam2ColumnIt & col2) const
2680 {
2681   double u = U, r = 0;
2682   if ( !myComponents.empty() ) {
2683     TSideFace * comp = GetComponent(U,u);
2684     return comp->GetColumns( u, col1, col2 );
2685   }
2686
2687   if ( !myIsForward )
2688     u = 1 - u;
2689   double f = myParams[0].first, l = myParams[0].second;
2690   u = f + u * ( l - f );
2691
2692   col1 = col2 = getColumn( myParamToColumnMap, u );
2693   if ( ++col2 == myParamToColumnMap->end() ) {
2694     --col2;
2695     r = 0.5;
2696   }
2697   else {
2698     double uf = col1->first;
2699     double ul = col2->first;
2700     r = ( u - uf ) / ( ul - uf );
2701   }
2702   return r;
2703 }
2704
2705 //================================================================================
2706 /*!
2707  * \brief Return coordinates by normalized params
2708   * \param U - horizontal param
2709   * \param V - vertical param
2710   * \retval gp_Pnt - result point
2711  */
2712 //================================================================================
2713
2714 gp_Pnt StdMeshers_PrismAsBlock::TSideFace::Value(const Standard_Real U,
2715                                                  const Standard_Real V) const
2716 {
2717   if ( !myComponents.empty() ) {
2718     double u;
2719     TSideFace * comp = GetComponent(U,u);
2720     return comp->Value( u, V );
2721   }
2722
2723   TParam2ColumnIt u_col1, u_col2;
2724   double vR, hR = GetColumns( U, u_col1, u_col2 );
2725
2726   const SMDS_MeshNode* nn[4];
2727
2728   // BEGIN issue 0020680: Bad cell created by Radial prism in center of torus
2729   // Workaround for a wrongly located point returned by mySurface.Value() for
2730   // UV located near boundary of BSpline surface.
2731   // To bypass the problem, we take point from 3D curve of EDGE.
2732   // It solves pb of the bloc_fiss_new.py
2733   const double tol = 1e-3;
2734   if ( V < tol || V+tol >= 1. )
2735   {
2736     nn[0] = V < tol ? u_col1->second.front() : u_col1->second.back();
2737     nn[2] = V < tol ? u_col2->second.front() : u_col2->second.back();
2738     TopoDS_Edge edge;
2739     if ( V < tol )
2740     {
2741       edge = myBaseEdge;
2742     }
2743     else
2744     {
2745       TopoDS_Shape s = myHelper->GetSubShapeByNode( nn[0], myHelper->GetMeshDS() );
2746       if ( s.ShapeType() != TopAbs_EDGE )
2747         s = myHelper->GetSubShapeByNode( nn[2], myHelper->GetMeshDS() );
2748       if ( s.ShapeType() == TopAbs_EDGE )
2749         edge = TopoDS::Edge( s );
2750     }
2751     if ( !edge.IsNull() )
2752     {
2753       double u1 = myHelper->GetNodeU( edge, nn[0] );
2754       double u3 = myHelper->GetNodeU( edge, nn[2] );
2755       double u = u1 * ( 1 - hR ) + u3 * hR;
2756       TopLoc_Location loc; double f,l;
2757       Handle(Geom_Curve) curve = BRep_Tool::Curve( edge,loc,f,l );
2758       return curve->Value( u ).Transformed( loc );
2759     }
2760   }
2761   // END issue 0020680: Bad cell created by Radial prism in center of torus
2762
2763   vR = getRAndNodes( & u_col1->second, V, nn[0], nn[1] );
2764   vR = getRAndNodes( & u_col2->second, V, nn[2], nn[3] );
2765
2766   if ( !myShapeID2Surf.empty() ) // side is vertically composite
2767   {
2768     // find a FACE on which the 4 nodes lie
2769     TSideFace* me = (TSideFace*) this;
2770     int notFaceID1 = 0, notFaceID2 = 0;
2771     for ( int i = 0; i < 4; ++i )
2772       if ( nn[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) // node on FACE
2773       {
2774         me->mySurface = me->myShapeID2Surf[ nn[i]->getshapeId() ];
2775         notFaceID2 = 0;
2776         break;
2777       }
2778       else if ( notFaceID1 == 0 ) // node on EDGE or VERTEX
2779       {
2780         me->mySurface  = me->myShapeID2Surf[ nn[i]->getshapeId() ];
2781         notFaceID1 = nn[i]->getshapeId();
2782       }
2783       else if ( notFaceID1 != nn[i]->getshapeId() ) // node on other EDGE or VERTEX
2784       {
2785         if ( mySurface != me->myShapeID2Surf[ nn[i]->getshapeId() ])
2786           notFaceID2 = nn[i]->getshapeId();
2787       }
2788     if ( notFaceID2 ) // no nodes of FACE and nodes are on different FACEs
2789     {
2790       SMESHDS_Mesh* meshDS = myHelper->GetMeshDS();
2791       TopoDS_Shape face = myHelper->GetCommonAncestor( meshDS->IndexToShape( notFaceID1 ),
2792                                                        meshDS->IndexToShape( notFaceID2 ),
2793                                                        *myHelper->GetMesh(),
2794                                                        TopAbs_FACE );
2795       if ( face.IsNull() ) 
2796         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() face.IsNull()");
2797       int faceID = meshDS->ShapeToIndex( face );
2798       me->mySurface = me->myShapeID2Surf[ faceID ];
2799       if ( !mySurface )
2800         throw SALOME_Exception("StdMeshers_PrismAsBlock::TSideFace::Value() !mySurface");
2801     }
2802   }
2803   
2804   gp_XY uv1 = myHelper->GetNodeUV( mySurface->Face(), nn[0], nn[2]);
2805   gp_XY uv2 = myHelper->GetNodeUV( mySurface->Face(), nn[1], nn[3]);
2806   gp_XY uv12 = uv1 * ( 1 - vR ) + uv2 * vR;
2807
2808   gp_XY uv3 = myHelper->GetNodeUV( mySurface->Face(), nn[2], nn[0]);
2809   gp_XY uv4 = myHelper->GetNodeUV( mySurface->Face(), nn[3], nn[1]);
2810   gp_XY uv34 = uv3 * ( 1 - vR ) + uv4 * vR;
2811
2812   gp_XY uv = uv12 * ( 1 - hR ) + uv34 * hR;
2813
2814   gp_Pnt p = mySurface->Value( uv.X(), uv.Y() );
2815   return p;
2816 }
2817
2818
2819 //================================================================================
2820 /*!
2821  * \brief Return boundary edge
2822   * \param edge - edge index
2823   * \retval TopoDS_Edge - found edge
2824  */
2825 //================================================================================
2826
2827 TopoDS_Edge StdMeshers_PrismAsBlock::TSideFace::GetEdge(const int iEdge) const
2828 {
2829   if ( !myComponents.empty() ) {
2830     switch ( iEdge ) {
2831     case V0_EDGE : return myComponents.front()->GetEdge( iEdge );
2832     case V1_EDGE : return myComponents.back() ->GetEdge( iEdge );
2833     default: return TopoDS_Edge();
2834     }
2835   }
2836   TopoDS_Shape edge;
2837   const SMDS_MeshNode* node = 0;
2838   SMESHDS_Mesh * meshDS = myHelper->GetMesh()->GetMeshDS();
2839   TNodeColumn* column;
2840
2841   switch ( iEdge ) {
2842   case TOP_EDGE:
2843   case BOTTOM_EDGE:
2844     column = & (( ++myParamToColumnMap->begin())->second );
2845     node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2846     edge = myHelper->GetSubShapeByNode ( node, meshDS );
2847     if ( edge.ShapeType() == TopAbs_VERTEX ) {
2848       column = & ( myParamToColumnMap->begin()->second );
2849       node = ( iEdge == TOP_EDGE ) ? column->back() : column->front();
2850     }
2851     break;
2852   case V0_EDGE:
2853   case V1_EDGE: {
2854     bool back = ( iEdge == V1_EDGE );
2855     if ( !myIsForward ) back = !back;
2856     if ( back )
2857       column = & ( myParamToColumnMap->rbegin()->second );
2858     else
2859       column = & ( myParamToColumnMap->begin()->second );
2860     if ( column->size() > 0 )
2861       edge = myHelper->GetSubShapeByNode( (*column)[ 1 ], meshDS );
2862     if ( edge.IsNull() || edge.ShapeType() == TopAbs_VERTEX )
2863       node = column->front();
2864     break;
2865   }
2866   default:;
2867   }
2868   if ( !edge.IsNull() && edge.ShapeType() == TopAbs_EDGE )
2869     return TopoDS::Edge( edge );
2870
2871   // find edge by 2 vertices
2872   TopoDS_Shape V1 = edge;
2873   TopoDS_Shape V2 = myHelper->GetSubShapeByNode( node, meshDS );
2874   if ( !V2.IsNull() && V2.ShapeType() == TopAbs_VERTEX && !V2.IsSame( V1 ))
2875   {
2876     TopoDS_Shape ancestor = myHelper->GetCommonAncestor( V1, V2, *myHelper->GetMesh(), TopAbs_EDGE);
2877     if ( !ancestor.IsNull() )
2878       return TopoDS::Edge( ancestor );
2879   }
2880   return TopoDS_Edge();
2881 }
2882
2883 //================================================================================
2884 /*!
2885  * \brief Fill block sub-shapes
2886   * \param shapeMap - map to fill in
2887   * \retval int - nb inserted sub-shapes
2888  */
2889 //================================================================================
2890
2891 int StdMeshers_PrismAsBlock::TSideFace::InsertSubShapes(TBlockShapes& shapeMap) const
2892 {
2893   int nbInserted = 0;
2894
2895   // Insert edges
2896   vector< int > edgeIdVec;
2897   SMESH_Block::GetFaceEdgesIDs( myID, edgeIdVec );
2898
2899   for ( int i = BOTTOM_EDGE; i <=V1_EDGE ; ++i ) {
2900     TopoDS_Edge e = GetEdge( i );
2901     if ( !e.IsNull() ) {
2902       nbInserted += SMESH_Block::Insert( e, edgeIdVec[ i ], shapeMap);
2903     }
2904   }
2905
2906   // Insert corner vertices
2907
2908   TParam2ColumnIt col1, col2 ;
2909   vector< int > vertIdVec;
2910
2911   // from V0 column
2912   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V0_EDGE ], vertIdVec);
2913   GetColumns(0, col1, col2 );
2914   const SMDS_MeshNode* node0 = col1->second.front();
2915   const SMDS_MeshNode* node1 = col1->second.back();
2916   TopoDS_Shape v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
2917   TopoDS_Shape v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
2918   if ( v0.ShapeType() == TopAbs_VERTEX ) {
2919     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
2920   }
2921   if ( v1.ShapeType() == TopAbs_VERTEX ) {
2922     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
2923   }
2924   
2925   // from V1 column
2926   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ V1_EDGE ], vertIdVec);
2927   GetColumns(1, col1, col2 );
2928   node0 = col2->second.front();
2929   node1 = col2->second.back();
2930   v0 = myHelper->GetSubShapeByNode( node0, myHelper->GetMeshDS());
2931   v1 = myHelper->GetSubShapeByNode( node1, myHelper->GetMeshDS());
2932   if ( v0.ShapeType() == TopAbs_VERTEX ) {
2933     nbInserted += SMESH_Block::Insert( v0, vertIdVec[ 0 ], shapeMap);
2934   }
2935   if ( v1.ShapeType() == TopAbs_VERTEX ) {
2936     nbInserted += SMESH_Block::Insert( v1, vertIdVec[ 1 ], shapeMap);
2937   }
2938
2939 //   TopoDS_Vertex V0, V1, Vcom;
2940 //   TopExp::Vertices( myBaseEdge, V0, V1, true );
2941 //   if ( !myIsForward ) std::swap( V0, V1 );
2942
2943 //   // bottom vertex IDs
2944 //   SMESH_Block::GetEdgeVertexIDs( edgeIdVec[ _u0 ], vertIdVec);
2945 //   SMESH_Block::Insert( V0, vertIdVec[ 0 ], shapeMap);
2946 //   SMESH_Block::Insert( V1, vertIdVec[ 1 ], shapeMap);
2947
2948 //   TopoDS_Edge sideEdge = GetEdge( V0_EDGE );
2949 //   if ( sideEdge.IsNull() || !TopExp::CommonVertex( botEdge, sideEdge, Vcom ))
2950 //     return false;
2951
2952 //   // insert one side edge
2953 //   int edgeID;
2954 //   if ( Vcom.IsSame( V0 )) edgeID = edgeIdVec[ _v0 ];
2955 //   else                    edgeID = edgeIdVec[ _v1 ];
2956 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
2957
2958 //   // top vertex of the side edge
2959 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec);
2960 //   TopoDS_Vertex Vtop = TopExp::FirstVertex( sideEdge );
2961 //   if ( Vcom.IsSame( Vtop ))
2962 //     Vtop = TopExp::LastVertex( sideEdge );
2963 //   SMESH_Block::Insert( Vtop, vertIdVec[ 1 ], shapeMap);
2964
2965 //   // other side edge
2966 //   sideEdge = GetEdge( V1_EDGE );
2967 //   if ( sideEdge.IsNull() )
2968 //     return false;
2969 //   if ( edgeID = edgeIdVec[ _v1 ]) edgeID = edgeIdVec[ _v0 ];
2970 //   else                            edgeID = edgeIdVec[ _v1 ];
2971 //   SMESH_Block::Insert( sideEdge, edgeID, shapeMap);
2972   
2973 //   // top edge
2974 //   TopoDS_Edge topEdge = GetEdge( TOP_EDGE );
2975 //   SMESH_Block::Insert( topEdge, edgeIdVec[ _u1 ], shapeMap);
2976
2977 //   // top vertex of the other side edge
2978 //   if ( !TopExp::CommonVertex( topEdge, sideEdge, Vcom ))
2979 //     return false;
2980 //   SMESH_Block::GetEdgeVertexIDs( edgeID, vertIdVec );
2981 //   SMESH_Block::Insert( Vcom, vertIdVec[ 1 ], shapeMap);
2982
2983   return nbInserted;
2984 }
2985
2986 //================================================================================
2987 /*!
2988  * \brief Dump ids of nodes of sides
2989  */
2990 //================================================================================
2991
2992 void StdMeshers_PrismAsBlock::TSideFace::dumpNodes(int nbNodes) const
2993 {
2994 #ifdef _DEBUG_
2995   cout << endl << "NODES OF FACE "; SMESH_Block::DumpShapeID( myID, cout ) << endl;
2996   THorizontalEdgeAdaptor* hSize0 = (THorizontalEdgeAdaptor*) HorizCurve(0);
2997   cout << "Horiz side 0: "; hSize0->dumpNodes(nbNodes); cout << endl;
2998   THorizontalEdgeAdaptor* hSize1 = (THorizontalEdgeAdaptor*) HorizCurve(1);
2999   cout << "Horiz side 1: "; hSize1->dumpNodes(nbNodes); cout << endl;
3000   TVerticalEdgeAdaptor* vSide0 = (TVerticalEdgeAdaptor*) VertiCurve(0);
3001   cout << "Verti side 0: "; vSide0->dumpNodes(nbNodes); cout << endl;
3002   TVerticalEdgeAdaptor* vSide1 = (TVerticalEdgeAdaptor*) VertiCurve(1);
3003   cout << "Verti side 1: "; vSide1->dumpNodes(nbNodes); cout << endl;
3004   delete hSize0; delete hSize1; delete vSide0; delete vSide1;
3005 #endif
3006 }
3007
3008 //================================================================================
3009 /*!
3010  * \brief Creates TVerticalEdgeAdaptor 
3011   * \param columnsMap - node column map
3012   * \param parameter - normalized parameter
3013  */
3014 //================================================================================
3015
3016 StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::
3017 TVerticalEdgeAdaptor( const TParam2ColumnMap* columnsMap, const double parameter)
3018 {
3019   myNodeColumn = & getColumn( columnsMap, parameter )->second;
3020 }
3021
3022 //================================================================================
3023 /*!
3024  * \brief Return coordinates for the given normalized parameter
3025   * \param U - normalized parameter
3026   * \retval gp_Pnt - coordinates
3027  */
3028 //================================================================================
3029
3030 gp_Pnt StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::Value(const Standard_Real U) const
3031 {
3032   const SMDS_MeshNode* n1;
3033   const SMDS_MeshNode* n2;
3034   double r = getRAndNodes( myNodeColumn, U, n1, n2 );
3035   return gpXYZ(n1) * ( 1 - r ) + gpXYZ(n2) * r;
3036 }
3037
3038 //================================================================================
3039 /*!
3040  * \brief Dump ids of nodes
3041  */
3042 //================================================================================
3043
3044 void StdMeshers_PrismAsBlock::TVerticalEdgeAdaptor::dumpNodes(int nbNodes) const
3045 {
3046 #ifdef _DEBUG_
3047   for ( int i = 0; i < nbNodes && i < myNodeColumn->size(); ++i )
3048     cout << (*myNodeColumn)[i]->GetID() << " ";
3049   if ( nbNodes < myNodeColumn->size() )
3050     cout << myNodeColumn->back()->GetID();
3051 #endif
3052 }
3053
3054 //================================================================================
3055 /*!
3056  * \brief Return coordinates for the given normalized parameter
3057   * \param U - normalized parameter
3058   * \retval gp_Pnt - coordinates
3059  */
3060 //================================================================================
3061
3062 gp_Pnt StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::Value(const Standard_Real U) const
3063 {
3064   return mySide->TSideFace::Value( U, myV );
3065 }
3066
3067 //================================================================================
3068 /*!
3069  * \brief Dump ids of <nbNodes> first nodes and the last one
3070  */
3071 //================================================================================
3072
3073 void StdMeshers_PrismAsBlock::THorizontalEdgeAdaptor::dumpNodes(int nbNodes) const
3074 {
3075 #ifdef _DEBUG_
3076   // Not bedugged code. Last node is sometimes incorrect
3077   const TSideFace* side = mySide;
3078   double u = 0;
3079   if ( mySide->IsComplex() )
3080     side = mySide->GetComponent(0,u);
3081
3082   TParam2ColumnIt col, col2;
3083   TParam2ColumnMap* u2cols = side->GetColumns();
3084   side->GetColumns( u , col, col2 );
3085   
3086   int j, i = myV ? mySide->ColumnHeight()-1 : 0;
3087
3088   const SMDS_MeshNode* n = 0;
3089   const SMDS_MeshNode* lastN
3090     = side->IsForward() ? u2cols->rbegin()->second[ i ] : u2cols->begin()->second[ i ];
3091   for ( j = 0; j < nbNodes && n != lastN; ++j )
3092   {
3093     n = col->second[ i ];
3094     cout << n->GetID() << " ";
3095     if ( side->IsForward() )
3096       ++col;
3097     else
3098       --col;
3099   }
3100
3101   // last node
3102   u = 1;
3103   if ( mySide->IsComplex() )
3104     side = mySide->GetComponent(1,u);
3105
3106   side->GetColumns( u , col, col2 );
3107   if ( n != col->second[ i ] )
3108     cout << col->second[ i ]->GetID();
3109 #endif
3110 }
3111 //================================================================================
3112 /*!
3113  * \brief Return UV on pcurve for the given normalized parameter
3114   * \param U - normalized parameter
3115   * \retval gp_Pnt - coordinates
3116  */
3117 //================================================================================
3118
3119 gp_Pnt2d StdMeshers_PrismAsBlock::TPCurveOnHorFaceAdaptor::Value(const Standard_Real U) const
3120 {
3121   TParam2ColumnIt u_col1, u_col2;
3122   double r = mySide->GetColumns( U, u_col1, u_col2 );
3123   gp_XY uv1 = mySide->GetNodeUV( myFace, u_col1->second[ myZ ]);
3124   gp_XY uv2 = mySide->GetNodeUV( myFace, u_col2->second[ myZ ]);
3125   return uv1 * ( 1 - r ) + uv2 * r;
3126 }