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