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