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