Salome HOME
Merge from V6_main 13/12/2012
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.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 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 // File      : StdMeshers_Projection_2D.cxx
25 // Module    : SMESH
26 // Created   : Fri Oct 20 11:37:07 2006
27 // Author    : Edward AGAPOV (eap)
28 //
29 #include "StdMeshers_Projection_2D.hxx"
30
31 #include "StdMeshers_ProjectionSource2D.hxx"
32 #include "StdMeshers_ProjectionUtils.hxx"
33 #include "StdMeshers_FaceSide.hxx"
34
35 #include "SMDS_EdgePosition.hxx"
36 #include "SMDS_FacePosition.hxx"
37 #include "SMESHDS_Hypothesis.hxx"
38 #include "SMESHDS_SubMesh.hxx"
39 #include "SMESH_Block.hxx"
40 #include "SMESH_Comment.hxx"
41 #include "SMESH_Gen.hxx"
42 #include "SMESH_Mesh.hxx"
43 #include "SMESH_MesherHelper.hxx"
44 #include "SMESH_Pattern.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_subMeshEventListener.hxx"
47
48 #include "utilities.h"
49
50 #include <BRep_Tool.hxx>
51 #include <Bnd_B2d.hxx>
52 #include <TopExp.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_ListIteratorOfListOfShape.hxx>
55 #include <TopoDS.hxx>
56 #include <gp_Ax2.hxx>
57 #include <gp_Ax3.hxx>
58
59
60 using namespace std;
61
62 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
63
64 typedef StdMeshers_ProjectionUtils TAssocTool;
65
66 //=======================================================================
67 //function : StdMeshers_Projection_2D
68 //purpose  : 
69 //=======================================================================
70
71 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
72   :SMESH_2D_Algo(hypId, studyId, gen)
73 {
74   _name = "Projection_2D";
75   _compatibleHypothesis.push_back("ProjectionSource2D");
76   _sourceHypo = 0;
77 }
78
79 //================================================================================
80 /*!
81  * \brief Destructor
82  */
83 //================================================================================
84
85 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
86 {}
87
88 //=======================================================================
89 //function : CheckHypothesis
90 //purpose  : 
91 //=======================================================================
92
93 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
94                                                const TopoDS_Shape&                  theShape,
95                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
96 {
97   list <const SMESHDS_Hypothesis * >::const_iterator itl;
98
99   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
100   if ( hyps.size() == 0 )
101   {
102     theStatus = HYP_MISSING;
103     return false;  // can't work with no hypothesis
104   }
105
106   if ( hyps.size() > 1 )
107   {
108     theStatus = HYP_ALREADY_EXIST;
109     return false;
110   }
111
112   const SMESHDS_Hypothesis *theHyp = hyps.front();
113
114   string hypName = theHyp->GetName();
115
116   theStatus = HYP_OK;
117
118   if (hypName == "ProjectionSource2D")
119   {
120     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
121
122     // Check hypo parameters
123
124     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
125     SMESH_Mesh* tgtMesh = & theMesh;
126     if ( !srcMesh )
127       srcMesh = tgtMesh;
128
129     // check vertices
130     if ( _sourceHypo->HasVertexAssociation() )
131     {
132       // source vertices
133       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
134         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
135       if ( edge.IsNull() ||
136            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
137            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
138       {
139         theStatus = HYP_BAD_PARAMETER;
140         SCRUTE((edge.IsNull()));
141         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
142         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
143       }
144       else
145       {
146         // target vertices
147         edge = TAssocTool::GetEdgeByVertices
148           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
149         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
150         {
151           theStatus = HYP_BAD_PARAMETER;
152           SCRUTE((edge.IsNull()));
153           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
154         }
155         // PAL16203
156         else if ( !_sourceHypo->IsCompoundSource() &&
157                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
158         {
159           theStatus = HYP_BAD_PARAMETER;
160           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
161         }
162       }
163     }
164     // check a source face
165     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
166          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
167     {
168       theStatus = HYP_BAD_PARAMETER;
169       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
170       SCRUTE((srcMesh == tgtMesh));
171       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
172     }
173   }
174   else
175   {
176     theStatus = HYP_INCOMPATIBLE;
177   }
178   return ( theStatus == HYP_OK );
179 }
180
181 namespace {
182
183   //================================================================================
184   /*!
185    * \brief define if a node is new or old
186    * \param node - node to check
187    * \retval bool - true if the node existed before Compute() is called
188    */
189   //================================================================================
190
191   bool isOldNode( const SMDS_MeshNode* node/*, const bool is1DComputed*/ )
192   {
193     // old nodes are shared by edges and new ones are shared
194     // only by faces created by mapper
195     //if ( is1DComputed )
196     {
197       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
198       return isOld;
199     }
200     // else
201     // {
202     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
203     //   bool isNew = invFace->more();
204     //   return !isNew;
205     // }
206   }
207
208   //================================================================================
209   /*!
210    * \brief Class to remove mesh built by pattern mapper on edges
211    * and vertices in the case of failure of projection algo.
212    * It does it's job at destruction
213    */
214   //================================================================================
215
216   class MeshCleaner {
217     SMESH_subMesh* sm;
218   public:
219     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
220     ~MeshCleaner() { Clean(sm); }
221     void Release() { sm = 0; } // mesh will not be removed
222     static void Clean( SMESH_subMesh* sm, bool withSub=true )
223     {
224       if ( !sm || !sm->GetSubMeshDS() ) return;
225       // PAL16567, 18920. Remove face nodes as well
226 //       switch ( sm->GetSubShape().ShapeType() ) {
227 //       case TopAbs_VERTEX:
228 //       case TopAbs_EDGE: {
229         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
230         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
231         while ( nIt->more() ) {
232           const SMDS_MeshNode* node = nIt->next();
233           if ( !isOldNode( node ) )
234             mesh->RemoveNode( node );
235         }
236         // do not break but iterate over DependsOn()
237 //       }
238 //       default:
239         if ( !withSub ) return;
240         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
241         while ( smIt->more() )
242           Clean( smIt->next(), false );
243 //       }
244     }
245   };
246
247   //================================================================================
248   /*!
249    * \brief find new nodes belonging to one free border of mesh on face
250     * \param sm - submesh on edge or vertex containg nodes to choose from
251     * \param face - the face bound the submesh
252     * \param u2nodes - map to fill with nodes
253     * \param seamNodes - set of found nodes
254     * \retval bool - is a success
255    */
256   //================================================================================
257
258   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
259                           const TopoDS_Face&                    face,
260                           map< double, const SMDS_MeshNode* > & u2nodes,
261                           set< const SMDS_MeshNode* > &         seamNodes)
262   {
263     u2nodes.clear();
264     seamNodes.clear();
265     if ( !sm || !sm->GetSubMeshDS() )
266       RETURN_BAD_RESULT("Null submesh");
267
268     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
269     switch ( sm->GetSubShape().ShapeType() ) {
270
271     case TopAbs_VERTEX: {
272       while ( nIt->more() ) {
273         const SMDS_MeshNode* node = nIt->next();
274         if ( isOldNode( node ) ) continue;
275         u2nodes.insert( make_pair( 0., node ));
276         seamNodes.insert( node );
277         return true;
278       }
279       break;
280     }
281     case TopAbs_EDGE: {
282       
283       // Get submeshes of sub-vertices
284       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
285       if ( subSM.size() != 2 )
286         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
287                           " but we have " << subSM.size());
288       SMESH_subMesh* smV1 = subSM.begin()->second;
289       SMESH_subMesh* smV2 = subSM.rbegin()->second;
290       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
291         RETURN_BAD_RESULT("Empty vertex submeshes");
292
293       // Look for a new node on V1
294       nIt = smV1->GetSubMeshDS()->GetNodes();
295       const SMDS_MeshNode* nV1 = 0;
296       while ( nIt->more() && !nV1 ) {
297         const SMDS_MeshNode* node = nIt->next();
298         if ( !isOldNode( node ) ) nV1 = node;
299       }
300       if ( !nV1 )
301         RETURN_BAD_RESULT("No new node found on V1");
302
303       // Find a new node connected to nV1 and belonging to edge submesh;
304       const SMDS_MeshNode* nE = 0;
305       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
306       SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
307       while ( vElems->more() && !nE ) {
308         const SMDS_MeshElement* elem = vElems->next();
309         int nbNodes = elem->NbNodes();
310         if ( elem->IsQuadratic() )
311           nbNodes /= 2;
312         int iV1 = elem->GetNodeIndex( nV1 );
313         // try next after nV1
314         int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
315         if ( smDS->Contains( elem->GetNode( iE ) ))
316           nE = elem->GetNode( iE );
317         if ( !nE ) {
318           // try node before nV1
319           iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
320           if ( smDS->Contains( elem->GetNode( iE )))
321             nE = elem->GetNode( iE );
322         }
323         if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
324           if ( Abs( iV1 - iE ) == 1 )
325             nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
326           else
327             nE = elem->GetNode( elem->NbNodes() - 1 );
328         }
329       }
330       if ( !nE )
331         RETURN_BAD_RESULT("new node on edge not found");
332
333       // Get the whole free border of a face
334       list< const SMDS_MeshNode* > bordNodes;
335       list< const SMDS_MeshElement* > bordFaces;
336       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
337         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
338                           nV1->GetID() << " " << nE->GetID() );
339
340       // Insert nodes of the free border to the map until node on V2 encountered
341       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
342       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
343       bordIt++; // skip nV1
344       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
345         const SMDS_MeshNode* node = *bordIt;
346         if ( v2smDS->Contains( node ))
347           break;
348         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
349           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
350                             " pos type " << node->GetPosition()->GetTypeOfPosition());
351         const SMDS_EdgePosition* pos =
352           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
353         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
354         seamNodes.insert( node );
355       }
356       if ( u2nodes.size() != seamNodes.size() )
357         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
358                           ", " << u2nodes.size() << " != " << seamNodes.size() );
359       return true;
360     }
361     default:;
362     }
363     RETURN_BAD_RESULT ("Unexpected submesh type");
364
365   } // bool getBoundaryNodes()
366
367   //================================================================================
368   /*!
369    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
370    * if projection by transformation is possible
371    */
372   //================================================================================
373
374   bool projectPartner(const TopoDS_Face&                tgtFace,
375                       const TopoDS_Face&                srcFace,
376                       SMESH_Mesh *                      tgtMesh,
377                       SMESH_Mesh *                      srcMesh,
378                       const TAssocTool::TShapeShapeMap& shape2ShapeMap)
379   {
380     MESSAGE("projectPartner");
381     const double tol = 1.e-7*srcMesh->GetMeshDS()->getMaxDim();
382
383     gp_Trsf trsf; // transformation to get location of target nodes from source ones
384     if ( tgtFace.IsPartner( srcFace ))
385     {
386       gp_Trsf srcTrsf = srcFace.Location();
387       gp_Trsf tgtTrsf = tgtFace.Location();
388       trsf = srcTrsf.Inverted() * tgtTrsf;
389     }
390     else
391     {
392       // Try to find the transformation
393
394       // make any local coord systems of src and tgt faces
395       vector<gp_Pnt> srcPP, tgtPP; // 3 points on face boundaries to make axes of CS
396       SMESH_subMesh * srcSM = srcMesh->GetSubMesh( srcFace );
397       SMESH_subMeshIteratorPtr smIt = srcSM->getDependsOnIterator(/*includeSelf=*/false,false);
398       srcSM = smIt->next(); // sm of a vertex
399       while ( smIt->more() && srcPP.size() < 3 )
400       {
401         srcSM = smIt->next();
402         SMESHDS_SubMesh* srcSmds = srcSM->GetSubMeshDS();
403         if ( !srcSmds ) continue;
404         SMDS_NodeIteratorPtr nIt = srcSmds->GetNodes();
405         while ( nIt->more() )
406         {
407           SMESH_TNodeXYZ p ( nIt->next());
408           bool pOK = false;
409           switch ( srcPP.size() )
410           {
411           case 0: pOK = true; break;
412
413           case 1: pOK = ( srcPP[0].SquareDistance( p ) > 10*tol ); break;
414             
415           case 2:
416             {
417               gp_Vec p0p1( srcPP[0], srcPP[1] ), p0p( srcPP[0], p );
418               // pOK = !p0p1.IsParallel( p0p, tol );
419               pOK = !p0p1.IsParallel( p0p, 3.14/20 ); // angle min 18 degrees
420               break;
421             }
422           }
423           if ( !pOK )
424             continue;
425
426           // find corresponding point on target shape
427           pOK = false;
428           gp_Pnt tgtP;
429           const TopoDS_Shape& tgtShape = shape2ShapeMap( srcSM->GetSubShape(), /*isSrc=*/true );
430           if ( tgtShape.ShapeType() == TopAbs_VERTEX )
431           {
432             tgtP = BRep_Tool::Pnt( TopoDS::Vertex( tgtShape ));
433             pOK = true;
434             //cout << "V - nS " << p._node->GetID() << " - nT " << SMESH_Algo::VertexNode(TopoDS::Vertex( tgtShape),tgtMesh->GetMeshDS())->GetID() << endl;
435           }
436           else if ( tgtPP.size() > 0 )
437           {
438             if ( SMESHDS_SubMesh* tgtSmds = tgtMesh->GetMeshDS()->MeshElements( tgtShape ))
439             {
440               double srcDist = srcPP[0].Distance( p );
441               double eTol = BRep_Tool::Tolerance( TopoDS::Edge( tgtShape ));
442               if (eTol < tol) eTol = tol;
443               SMDS_NodeIteratorPtr nItT = tgtSmds->GetNodes();
444               while ( nItT->more() && !pOK )
445               {
446                 const SMDS_MeshNode* n = nItT->next();
447                 tgtP = SMESH_TNodeXYZ( n );
448                 pOK = ( fabs( srcDist - tgtPP[0].Distance( tgtP )) < 2*eTol );
449                 //cout << "E - nS " << p._node->GetID() << " - nT " << n->GetID()<< " OK - " << pOK<< " " << fabs( srcDist - tgtPP[0].Distance( tgtP ))<< " tol " << eTol<< endl;
450               }
451             }
452           }
453           if ( !pOK )
454             continue;
455
456           srcPP.push_back( p );
457           tgtPP.push_back( tgtP );
458         }
459       }
460       if ( srcPP.size() != 3 )
461         return false;
462
463       // make transformation
464       gp_Trsf fromTgtCS, toSrcCS; // from/to global CS
465       gp_Ax2 srcCS( srcPP[0], gp_Vec( srcPP[0], srcPP[1] ), gp_Vec( srcPP[0], srcPP[2]));
466       gp_Ax2 tgtCS( tgtPP[0], gp_Vec( tgtPP[0], tgtPP[1] ), gp_Vec( tgtPP[0], tgtPP[2]));
467       toSrcCS  .SetTransformation( gp_Ax3( srcCS ));
468       fromTgtCS.SetTransformation( gp_Ax3( tgtCS ));
469       fromTgtCS.Invert();
470
471       trsf = fromTgtCS * toSrcCS;
472     }
473
474     // Fill map of src to tgt nodes with nodes on edges
475
476     map<const SMDS_MeshNode* , const SMDS_MeshNode*> src2tgtNodes;
477     map<const SMDS_MeshNode* , const SMDS_MeshNode*>::iterator srcN_tgtN;
478
479     for ( TopExp_Explorer srcEdge( srcFace, TopAbs_EDGE); srcEdge.More(); srcEdge.Next() )
480     {
481       const TopoDS_Shape& tgtEdge = shape2ShapeMap( srcEdge.Current(), /*isSrc=*/true );
482
483       map< double, const SMDS_MeshNode* > srcNodes, tgtNodes;
484       if ( !SMESH_Algo::GetSortedNodesOnEdge( srcMesh->GetMeshDS(),
485                                               TopoDS::Edge( srcEdge.Current() ),
486                                               /*ignoreMediumNodes = */true,
487                                               srcNodes )
488            ||
489            !SMESH_Algo::GetSortedNodesOnEdge( tgtMesh->GetMeshDS(),
490                                               TopoDS::Edge( tgtEdge ),
491                                               /*ignoreMediumNodes = */true,
492                                               tgtNodes )
493            ||
494            srcNodes.size() != tgtNodes.size())
495         return false;
496
497       if ( !tgtEdge.IsPartner( srcEdge.Current() ))
498       {
499         // check that transformation is OK by three nodes
500         gp_Pnt p0S = SMESH_TNodeXYZ( (srcNodes.begin())  ->second);
501         gp_Pnt p1S = SMESH_TNodeXYZ( (srcNodes.rbegin()) ->second);
502         gp_Pnt p2S = SMESH_TNodeXYZ( (++srcNodes.begin())->second);
503
504         gp_Pnt p0T = SMESH_TNodeXYZ( (tgtNodes.begin())  ->second);
505         gp_Pnt p1T = SMESH_TNodeXYZ( (tgtNodes.rbegin()) ->second);
506         gp_Pnt p2T = SMESH_TNodeXYZ( (++tgtNodes.begin())->second);
507
508         // transform source points, they must coincide with target ones
509         if ( p0T.SquareDistance( p0S.Transformed( trsf )) > tol ||
510              p1T.SquareDistance( p1S.Transformed( trsf )) > tol ||
511              p2T.SquareDistance( p2S.Transformed( trsf )) > tol )
512         {
513           //cout << "KO trsf, 3 dist: "
514           //<< p0T.SquareDistance( p0S.Transformed( trsf ))<< ", "
515           //<< p1T.SquareDistance( p1S.Transformed( trsf ))<< ", "
516           //<< p2T.SquareDistance( p2S.Transformed( trsf ))<< ", "<<endl;
517           return false;
518         }
519       }
520
521       map< double, const SMDS_MeshNode* >::iterator u_tn = tgtNodes.begin();
522       map< double, const SMDS_MeshNode* >::iterator u_sn = srcNodes.begin();
523       for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
524         src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
525     }
526
527     // Make new faces
528
529     // prepare the helper to adding quadratic elements if necessary
530     SMESH_MesherHelper helper( *tgtMesh );
531     helper.SetSubShape( tgtFace );
532     helper.IsQuadraticSubMesh( tgtFace );
533     helper.SetElementsOnShape( true );
534
535     SMESH_MesherHelper srcHelper( *srcMesh );
536     srcHelper.SetSubShape( srcFace );
537
538     const SMDS_MeshNode* nullNode = 0;
539
540     // indices of nodes to create properly oriented faces
541     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
542     if ( trsf.Form() != gp_Identity )
543       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
544
545     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
546     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
547     vector< const SMDS_MeshNode* > tgtNodes;
548     while ( elemIt->more() ) // loop on all mesh faces on srcFace
549     {
550       const SMDS_MeshElement* elem = elemIt->next();
551       const int nbN = elem->NbCornerNodes(); 
552       tgtNodes.resize( nbN );
553       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
554       {
555         const SMDS_MeshNode* srcNode = elem->GetNode(i);
556         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
557         if ( srcN_tgtN->second == nullNode )
558         {
559           // create a new node
560           gp_Pnt tgtP = gp_Pnt(srcNode->X(),srcNode->Y(),srcNode->Z()).Transformed( trsf );
561           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
562           srcN_tgtN->second = n;
563
564           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
565                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)));
566           n->SetPosition( new SMDS_FacePosition( srcUV.X(), srcUV.Y() ));
567         }
568         tgtNodes[i] = srcN_tgtN->second;
569       }
570       // create a new face
571       switch ( nbN )
572       {
573       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
574       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
575       }
576     }
577     return true;
578
579   } //   bool projectPartner()
580
581   //================================================================================
582   /*!
583    * \brief Preform projection in case if the faces are similar in 2D space
584    */
585   //================================================================================
586
587   bool projectBy2DSimilarity(const TopoDS_Face&                tgtFace,
588                              const TopoDS_Face&                srcFace,
589                              SMESH_Mesh *                      tgtMesh,
590                              SMESH_Mesh *                      srcMesh,
591                              const TAssocTool::TShapeShapeMap& shape2ShapeMap,
592                              const bool                        is1DComputed)
593   {
594     // 1) Preparation
595
596     // get ordered src EDGEs
597     TError err;
598     TSideVector srcWires =
599       StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*ignoreMediumNodes = */false, err);
600     if ( err && !err->IsOK() )
601       return false;
602
603     // make corresponding sequence of tgt EDGEs
604     TSideVector tgtWires( srcWires.size() );
605     for ( unsigned iW = 0; iW < srcWires.size(); ++iW )
606     {
607       list< TopoDS_Edge > tgtEdges;
608       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
609       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
610       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
611       {
612         tgtEdges.push_back( TopoDS::Edge( shape2ShapeMap( srcWire->Edge( iE ), /*isSrc=*/true)));
613         // reverse a seam edge encountered for the second time
614         const int oldExtent = edgeMap.Extent();
615         edgeMap.Add( tgtEdges.back() );
616         if ( oldExtent == edgeMap.Extent() )
617           tgtEdges.back().Reverse();
618       }
619       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
620                                                      /*theIsForward = */ true,
621                                                      /*theIgnoreMediumNodes = */false));
622       if ( is1DComputed &&
623            srcWires[iW]->GetUVPtStruct().size() !=
624            tgtWires[iW]->GetUVPtStruct().size())
625         return false;
626     }
627
628     // 2) Find transformation
629
630     gp_Trsf2d trsf;
631     {
632       // get 2 pairs of corresponding UVs
633       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
634       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
635       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
636       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
637
638       // make transformation
639       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
640       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
641       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
642       toSrcCS  .SetTransformation( srcCS );
643       fromTgtCS.SetTransformation( tgtCS );
644       fromTgtCS.Invert();
645
646       trsf = fromTgtCS * toSrcCS;
647
648       // check transformation
649       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
650       for ( double u = 0.12; u < 1.; u += 0.1 )
651       {
652         gp_Pnt2d srcUV = srcWires[0]->Value2d( u );
653         gp_Pnt2d tgtUV = tgtWires[0]->Value2d( u );
654         gp_Pnt2d tgtUV2 = srcUV.Transformed( trsf );
655         if ( tgtUV.Distance( tgtUV2 ) > tol )
656           return false;
657       }
658     }
659
660     // 3) Projection
661
662     typedef map<const SMDS_MeshNode* , const SMDS_MeshNode*, TIDCompare> TN2NMap;
663     TN2NMap src2tgtNodes;
664     TN2NMap::iterator srcN_tgtN;
665
666     // fill src2tgtNodes in with nodes on EDGEs
667     for ( unsigned iW = 0; iW < srcWires.size(); ++iW )
668       if ( is1DComputed )
669       {
670         const vector<UVPtStruct>& srcUVs = srcWires[iW]->GetUVPtStruct();
671         const vector<UVPtStruct>& tgtUVs = tgtWires[iW]->GetUVPtStruct();
672         for ( unsigned i = 0; i < srcUVs.size(); ++i )
673           src2tgtNodes.insert( make_pair( srcUVs[i].node, tgtUVs[i].node ));
674       }
675       else
676       {
677         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
678         {
679           TopoDS_Vertex srcV = srcWires[iW]->FirstVertex(iE);
680           TopoDS_Vertex tgtV = tgtWires[iW]->FirstVertex(iE);
681           const SMDS_MeshNode* srcNode = SMESH_Algo::VertexNode( srcV, srcMesh->GetMeshDS() );
682           const SMDS_MeshNode* tgtNode = SMESH_Algo::VertexNode( tgtV, tgtMesh->GetMeshDS() );
683           if ( tgtNode && srcNode )
684             src2tgtNodes.insert( make_pair( srcNode, tgtNode ));
685         }
686       }
687
688     // make elements
689
690     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
691
692     SMESH_MesherHelper helper( *tgtMesh );
693     helper.SetSubShape( tgtFace );
694     if ( is1DComputed )
695       helper.IsQuadraticSubMesh( tgtFace );
696     else
697       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
698     helper.SetElementsOnShape( true );
699     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
700     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
701
702     SMESH_MesherHelper srcHelper( *srcMesh );
703     srcHelper.SetSubShape( srcFace );
704
705     const SMDS_MeshNode* nullNode = 0;
706
707     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
708     vector< const SMDS_MeshNode* > tgtNodes;
709     bool uvOK;
710     while ( elemIt->more() ) // loop on all mesh faces on srcFace
711     {
712       const SMDS_MeshElement* elem = elemIt->next();
713       const int nbN = elem->NbCornerNodes(); 
714       tgtNodes.resize( nbN );
715       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
716       {
717         const SMDS_MeshNode* srcNode = elem->GetNode(i);
718         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
719         if ( srcN_tgtN->second == nullNode )
720         {
721           // create a new node
722           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
723                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
724           gp_Pnt2d tgtUV = srcUV.Transformed( trsf );
725           gp_Pnt   tgtP  = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
726           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
727           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
728           {
729           case SMDS_TOP_FACE: {
730             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
731             break;
732           }
733           case SMDS_TOP_EDGE: {
734             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
735             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
736             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ));
737             double U = srcHelper.GetNodeU( TopoDS::Edge( srcEdge ), srcNode );
738             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
739             n->SetPosition(SMDS_PositionPtr(new SMDS_EdgePosition( U )));
740             break;
741           }
742           case SMDS_TOP_VERTEX: {
743             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
744             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
745             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
746             break;
747           }
748           }
749           srcN_tgtN->second = n;
750         }
751         tgtNodes[i] = srcN_tgtN->second;
752       }
753       // create a new face (with reversed orientation)
754       switch ( nbN )
755       {
756       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
757       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
758       }
759     }
760     return true;
761
762   } // bool projectBy2DSimilarity(...)
763
764 } // namespace
765
766
767 //=======================================================================
768 //function : Compute
769 //purpose  : 
770 //=======================================================================
771
772 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
773 {
774   MESSAGE("Projection_2D Compute");
775   if ( !_sourceHypo )
776     return false;
777
778   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
779   SMESH_Mesh * tgtMesh = & theMesh;
780   if ( !srcMesh )
781     srcMesh = tgtMesh;
782
783   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
784
785   // ---------------------------
786   // Make sub-shapes association
787   // ---------------------------
788
789   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
790   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
791
792   TAssocTool::TShapeShapeMap shape2ShapeMap;
793   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
794   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
795                                              shape2ShapeMap)  ||
796        !shape2ShapeMap.IsBound( tgtFace ))
797   {
798     if ( srcShape.ShapeType() == TopAbs_FACE )
799     {
800       int nbE1 = TAssocTool::Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
801       int nbE2 = TAssocTool::Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
802       if ( nbE1 != nbE2 )
803         return error(COMPERR_BAD_SHAPE,
804                      SMESH_Comment("Different number of edges in source and target faces: ")
805                      << nbE2 << " and " << nbE1 );
806     }
807     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
808   }
809   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
810
811   // ----------------------------------------------
812   // Assure that mesh on a source Face is computed
813   // ----------------------------------------------
814
815   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
816   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
817
818   if ( tgtMesh == srcMesh ) {
819     if ( !TAssocTool::MakeComputed( srcSubMesh ) || !srcSubMesh->IsMeshComputed() )
820       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not computed");
821   }
822   else {
823     if ( !srcSubMesh->IsMeshComputed() )
824       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not computed");
825   }
826
827   // ===========
828   // Projection
829   // ===========
830
831   // find out if EDGEs are meshed or not
832   bool is1DComputed = false;
833   SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
834                                                                    /*complexShapeFirst=*/true);
835   while ( smIt->more() && !is1DComputed )
836   {
837     SMESH_subMesh* sm = smIt->next();
838     if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
839       is1DComputed = sm->IsMeshComputed();
840   }
841
842   bool done = false;
843
844   if ( !done )
845   {
846     // try to project from the same face with different location
847     done = projectPartner( tgtFace, srcFace, tgtMesh, srcMesh, shape2ShapeMap );
848   }
849   if ( !done )
850   {
851     // projection in case if the faces are similar in 2D space
852     done = projectBy2DSimilarity( tgtFace, srcFace, tgtMesh, srcMesh, shape2ShapeMap, is1DComputed);
853   }
854
855   if ( !done )
856   {
857     // --------------------
858     // Prepare to mapping 
859     // --------------------
860
861     SMESH_MesherHelper helper( theMesh );
862     helper.SetSubShape( tgtFace );
863
864     // Check if node projection to a face is needed
865     Bnd_B2d uvBox;
866     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
867     int nbFaceNodes = 0;
868     for ( ; nbFaceNodes < 3 && faceIt->more();  ) {
869       const SMDS_MeshElement* face = faceIt->next();
870       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
871       while ( nodeIt->more() ) {
872         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
873         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ) {
874           nbFaceNodes++;
875           uvBox.Add( helper.GetNodeUV( srcFace, node ));
876         }
877       }
878     }
879     const bool toProjectNodes =
880       ( nbFaceNodes > 0 && ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN ));
881
882     // Load pattern from the source face
883     SMESH_Pattern mapper;
884     mapper.Load( srcMesh, srcFace, toProjectNodes );
885     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
886       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
887
888     // Find the first target vertex corresponding to first vertex of the <mapper>
889     // and <theReverse> flag needed to call mapper.Apply()
890
891     TopoDS_Vertex srcV1 = TopoDS::Vertex( mapper.GetSubShape( 1 ));
892     if ( srcV1.IsNull() )
893       RETURN_BAD_RESULT("Mesh is not bound to the face");
894     if ( !shape2ShapeMap.IsBound( srcV1, /*isSrc=*/true ))
895       RETURN_BAD_RESULT("Not associated vertices, srcV1 " << srcV1.TShape().operator->() );
896     TopoDS_Vertex tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
897
898     if ( !SMESH_MesherHelper::IsSubShape( srcV1, srcFace ))
899       RETURN_BAD_RESULT("Wrong srcV1 " << srcV1.TShape().operator->());
900     if ( !SMESH_MesherHelper::IsSubShape( tgtV1, tgtFace ))
901       RETURN_BAD_RESULT("Wrong tgtV1 " << tgtV1.TShape().operator->());
902
903     // try to find out orientation by order of edges
904     bool reverse = false;
905     list< TopoDS_Edge > tgtEdges, srcEdges;
906     list< int > nbEdgesInWires;
907     SMESH_Block::GetOrderedEdges( tgtFace, tgtV1, tgtEdges, nbEdgesInWires);
908     SMESH_Block::GetOrderedEdges( srcFace, srcV1, srcEdges, nbEdgesInWires);
909     if ( nbEdgesInWires.front() > 1 ) // possible to find out
910     {
911       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
912       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
913       reverse = ( ! srcE1.IsSame( srcE1bis ));
914     }
915     else if ( nbEdgesInWires.front() == 1 )
916     {
917       // TODO::Compare orientation of curves in a sole edge
918       //RETURN_BAD_RESULT("Not implemented case");
919     }
920     else
921     {
922       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
923     }
924
925     // --------------------
926     // Perform 2D mapping 
927     // --------------------
928
929     // Compute mesh on a target face
930
931     mapper.Apply( tgtFace, tgtV1, reverse );
932     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
933       return error("Can't apply source mesh pattern to the face");
934
935     // Create the mesh
936
937     const bool toCreatePolygons = false, toCreatePolyedrs = false;
938     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
939     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
940       return error("Can't make mesh by source mesh pattern");
941
942     // it will remove mesh built by pattern mapper on edges and vertices
943     // in failure case
944     MeshCleaner cleaner( tgtSubMesh );
945
946     // -------------------------------------------------------------------------
947     // mapper doesn't take care of nodes already existing on edges and vertices,
948     // so we must merge nodes created by it with existing ones 
949     // -------------------------------------------------------------------------
950
951     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
952
953     // Make groups of nodes to merge
954
955     // loop on edge and vertex submeshes of a target face
956     smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,/*complexShapeFirst=*/false);
957     while ( smIt->more() )
958     {
959       SMESH_subMesh*     sm = smIt->next();
960       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
961       if ( !smDS || smDS->NbNodes() == 0 )
962         continue;
963       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
964       //break;
965
966       // Sort new and old nodes of a submesh separately
967
968       bool isSeam = helper.IsRealSeam( sm->GetId() );
969
970       enum { NEW_NODES = 0, OLD_NODES };
971       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
972       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
973       set< const SMDS_MeshNode* > seamNodes;
974
975       // mapper puts on a seam edge nodes from 2 edges
976       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
977         RETURN_BAD_RESULT("getBoundaryNodes() failed");
978
979       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
980       while ( nIt->more() )
981       {
982         const SMDS_MeshNode* node = nIt->next();
983         bool isOld = isOldNode( node );
984
985         if ( !isOld && isSeam ) { // new node on a seam edge
986           if ( seamNodes.count( node ) )
987             continue; // node is already in the map
988         }
989
990         // sort nodes on edges by their position
991         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
992         switch ( node->GetPosition()->GetTypeOfPosition() )
993         {
994         case  SMDS_TOP_VERTEX: {
995           if ( !is1DComputed && !pos2nodes.empty() )
996             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
997           else
998             pos2nodes.insert( make_pair( 0, node ));
999           break;
1000         }
1001         case  SMDS_TOP_EDGE:   {
1002           const SMDS_EdgePosition* pos =
1003             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1004           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1005           break;
1006         }
1007         default:
1008           RETURN_BAD_RESULT("Wrong node position type: "<<
1009                             node->GetPosition()->GetTypeOfPosition());
1010         }
1011       }
1012       const bool mergeNewToOld =
1013         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1014       const bool mergeSeamToNew =
1015         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1016
1017       if ( !mergeNewToOld )
1018         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1019              u2nodesMaps[ OLD_NODES ].size() > 0 )
1020         {
1021           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1022           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1023           for ( ; u_oldNode != newEnd; ++u_oldNode )
1024             _badInputElements.push_back( u_oldNode->second );
1025           return error( COMPERR_BAD_INPUT_MESH,
1026                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1027                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1028                         << " #" << sm->GetId() );
1029         }
1030       if ( isSeam && !mergeSeamToNew ) {
1031         //RETURN_BAD_RESULT
1032         MESSAGE("Different nb of old and seam nodes " <<
1033                 u2nodesMaps[ OLD_NODES ].size() << " != " << u2nodesOnSeam.size());
1034       }
1035       // Make groups of nodes to merge
1036       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1037       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1038       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1039       u_newOnSeam = u2nodesOnSeam.begin();
1040       if ( mergeNewToOld )
1041         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1042         {
1043           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1044           groupsOfNodes.back().push_back( u_oldNode->second );
1045           groupsOfNodes.back().push_back( u_newNode->second );
1046           if ( mergeSeamToNew )
1047             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1048         }
1049       else if ( mergeSeamToNew )
1050         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1051         {
1052           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1053           groupsOfNodes.back().push_back( u_newNode->second );
1054           groupsOfNodes.back().push_back( u_newOnSeam->second );
1055         }
1056     }
1057
1058     // Merge
1059
1060     SMESH_MeshEditor editor( tgtMesh );
1061     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1062     editor.MergeNodes( groupsOfNodes );
1063     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1064     if ( nbFaceBeforeMerge != nbFaceAtferMerge )
1065       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1066
1067     // ----------------------------------------------------------------
1068     // The mapper can't create quadratic elements, so convert if needed
1069     // ----------------------------------------------------------------
1070
1071     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1072     bool srcIsQuad = faceIt->next()->IsQuadratic();
1073     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1074     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1075     if ( srcIsQuad && !tgtIsQuad )
1076     {
1077       TIDSortedElemSet tgtFaces;
1078       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1079       while ( faceIt->more() )
1080         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1081
1082       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces);
1083     }
1084
1085     cleaner.Release(); // not to remove mesh
1086
1087   } // end of projection using Pattern mapping
1088
1089
1090   // ---------------------------
1091   // Check elements orientation
1092   // ---------------------------
1093
1094   TopoDS_Face face = TopoDS::Face( theShape );
1095   if ( !theMesh.IsMainShape( tgtFace ))
1096   {
1097     // find the main shape
1098     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1099     switch ( mainShape.ShapeType() ) {
1100     case TopAbs_SHELL:
1101     case TopAbs_SOLID: break;
1102     default:
1103       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1104       for ( ; ancestIt.More(); ancestIt.Next() ) {
1105         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1106         if ( type == TopAbs_SOLID ) {
1107           mainShape = ancestIt.Value();
1108           break;
1109         } else if ( type == TopAbs_SHELL ) {
1110           mainShape = ancestIt.Value();
1111         }
1112       }
1113     }
1114     // find tgtFace in the main solid or shell to know it's true orientation.
1115     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1116     for ( ; exp.More(); exp.Next() ) {
1117       if ( tgtFace.IsSame( exp.Current() )) {
1118         face = TopoDS::Face( exp.Current() );
1119         break;
1120       }
1121     }
1122   }
1123   // Fix orientation
1124   if ( SMESH_Algo::IsReversedSubMesh( face, meshDS ))
1125   {
1126     SMESH_MeshEditor editor( tgtMesh );
1127     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1128     while ( eIt->more() ) {
1129       const SMDS_MeshElement* e = eIt->next();
1130       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1131         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1132     }
1133   }
1134
1135   return true;
1136 }
1137
1138
1139 //=======================================================================
1140 //function : Evaluate
1141 //purpose  : 
1142 //=======================================================================
1143
1144 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1145                                         const TopoDS_Shape& theShape,
1146                                         MapShapeNbElems&    aResMap)
1147 {
1148   if ( !_sourceHypo )
1149     return false;
1150
1151   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1152   SMESH_Mesh * tgtMesh = & theMesh;
1153   if ( !srcMesh )
1154     srcMesh = tgtMesh;
1155
1156   // ---------------------------
1157   // Make sub-shapes association
1158   // ---------------------------
1159
1160   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1161   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1162
1163   TAssocTool::TShapeShapeMap shape2ShapeMap;
1164   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1165   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1166                                              shape2ShapeMap)  ||
1167        !shape2ShapeMap.IsBound( tgtFace ))
1168     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1169
1170   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1171
1172   // -------------------------------------------------------
1173   // Assure that mesh on a source Face is computed/evaluated
1174   // -------------------------------------------------------
1175
1176   std::vector<int> aVec;
1177
1178   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1179   if ( srcSubMesh->IsMeshComputed() )
1180   {
1181     aVec.resize( SMDSEntity_Last, 0 );
1182     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
1183
1184     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
1185     while ( elemIt->more() )
1186       aVec[ elemIt->next()->GetEntityType() ]++;
1187   }
1188   else
1189   {
1190     MapShapeNbElems  tmpResMap;
1191     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
1192     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
1193       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
1194     aVec = srcResMap[ srcSubMesh ];
1195     if ( aVec.empty() )
1196       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
1197   }
1198
1199   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1200   aResMap.insert(std::make_pair(sm,aVec));
1201
1202   return true;
1203 }
1204
1205
1206 //=============================================================================
1207 /*!
1208  * \brief Sets a default event listener to submesh of the source face
1209   * \param subMesh - submesh where algo is set
1210  *
1211  * This method is called when a submesh gets HYP_OK algo_state.
1212  * After being set, event listener is notified on each event of a submesh.
1213  * Arranges that CLEAN event is translated from source submesh to
1214  * the submesh
1215  */
1216 //=============================================================================
1217
1218 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
1219 {
1220   TAssocTool::SetEventListener( subMesh,
1221                                 _sourceHypo->GetSourceFace(),
1222                                 _sourceHypo->GetSourceMesh() );
1223 }